dsh-model-think-level 2.3.5 → 2.4.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/key-mutation-queue.ts", "../src/key-route-core.ts", "../src/key-serves.ts", "../src/order-store.ts", "../src/multi-key-listing.ts", "../src/shared.ts", "../src/headers-core.ts", "../src/listing.ts", "../src/key-probe.ts", "../src/discovery-merge.ts", "../src/knowledge.ts", "../src/guard.ts", "../src/balance.ts", "../src/headers-fetch.ts", "../src/headers-pi-ai.ts", "../src/headers-conflict.ts", "../src/image/config.ts", "../src/image/sizes.ts", "../src/image/generate.ts", "../src/image/deadline.ts", "../src/image/command.ts", "../src/image/tool.ts", "../src/image/legacy-cleanup.ts", "../src/autofill.ts", "../src/fingerprint/bank.ts", "../src/fingerprint/core.ts", "../src/fingerprint/random.ts", "../src/fingerprint/challenges.ts", "../src/fingerprint/eligibility.ts", "../src/fingerprint/run.ts", "../src/fingerprint/store.ts", "../src/fingerprint/verdict.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 BALANCE_PATH,\n DIAG_PATH,\n FINGERPRINT_PATH,\n HEADERS_CONFIG_PATH,\n IMAGE_CONFIG_PATH,\n KEY_INDEX_PATH,\n ORDER_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 routeBalanceOf,\n routeEndpointsOf,\n updateKeyIndex,\n withKeyAlias,\n withKeyAutoScope,\n withKeyDisabled,\n withKeyEntry,\n withKeyModels,\n withKeyProtocol,\n withRouteBalance,\n withRouteEndpoints,\n withoutKeyEntry,\n writeKeyIndex,\n type KeyIndexEntry,\n} from './key-index.js'\nimport { acquireKeyMutation } from './key-mutation-queue.js'\nimport { keyRest, keysForModel, restKeyOf, type KeyCandidate, type ServingKnowledge } from './key-route-core.js'\nimport { keyServesFilePath, readKeyServes, servesOfRoute, withServes, withoutServes, writeKeyServes, type KeyServesDocument } from './key-serves.js'\nimport { commitUiOrderGuarded, readUiOrder, uiOrderFilePath } from './order-store.js'\nimport { collectKeyListings, mergeKeyListings } from './multi-key-listing.js'\nimport { listingTargetsOf, type ProbeTarget } from './key-probe.js'\nimport { probeListing } from './discovery-merge.js'\nimport { suggestEfforts } from './knowledge.js'\nimport type { ReasoningEfforts } from './knowledge.js'\nimport { resolveGuardEffort } from './guard.js'\nimport { parseBalancePayload } from './balance.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 redactUrlSecrets,\n type ListedModel,\n} from './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// Image generation (\u751F\u56FE): one config file, one generation core behind two\n// entries \u2014 the `generate_image` native tool (\u4E3B\u901A\u9053) and the /\u751F\u56FE host\n// command \u2014 plus the boot-time removal of the retired MCP patch entry.\nimport {\n deriveImageSeeds,\n emptyImageConfig,\n readImageConfig,\n syncImageConfig,\n updateImageConfig,\n type ImageConfig,\n} from './image/config.js'\nimport { generateImage, type GenerateDeps } from './image/generate.js'\nimport { registerImagegenCommand, type CommandsServiceLike } from './image/command.js'\nimport { imageToolHint, registerGenerateImageTool } from './image/tool.js'\nimport { removeLegacyImageMcpPatch } from './image/legacy-cleanup.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, buildCompatCleanupPatch, stripNewCompatKeysDeep } from './autofill.js'\n// Model fingerprint attribution (ModelTrace). The math is a pure port of\n// upstream `fingerprint-core.js` over a vendored bank; only the routing below\n// touches the llm service, so the whole attribution path stays unit-testable.\nimport { bankBuiltAt, loadBankSync, summarizeBank } from './fingerprint/bank.js'\nimport { generateChallenges } from './fingerprint/challenges.js'\nimport { analyzeGlobalOutputs, NO_USABLE_OUTPUT, type AttributionResult } from './fingerprint/core.js'\nimport { isEligibleModel } from './fingerprint/eligibility.js'\nimport { runProbe, type ProbeOutcome, type ProbeRunResult } from './fingerprint/run.js'\nimport {\n fingerprintFilePath,\n providerRecords,\n readFingerprintStore,\n updateFingerprintStore,\n withRecord,\n withoutRecord,\n type FingerprintRecord,\n type FingerprintChallenge,\n type FingerprintTiming,\n} from './fingerprint/store.js'\nimport { statusOf, topEntriesOf, EARLY_IDENTIFIED_PROBABILITY } from './fingerprint/verdict.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/** Legacy schema default only; absence no longer authorizes key deletion. */\nconst ROUTE_SWEEP_GRACE_MS = 30_000\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 * Balance fetch budget. One read per provider per page opening \u2014 but the read\n * runs on the host's web server, and a dead balance endpoint must not hold a\n * socket (and the page's chip, which spins until the answer) for the better\n * part of half a minute. A billing API that needs more than 8s will not get\n * faster on a retry either; the chip keeps the last reading meanwhile.\n */\nconst BALANCE_TIMEOUT_MS = 8_000\n\n/**\n * Bound on one credential-store IPC a KEY MUTATION waits on. The store is\n * local, so an answer normally lands in milliseconds \u2014 but a stalled store\n * (a hung keychain daemon, a wedged host service) must not hang the manager's\n * own route for ever: a mutation that cannot be pre-checked within this\n * budget refuses with a clear message the user can retry, and a forget that\n * outlives it rolls the metadata back the same way a refused forget does.\n */\nconst CREDENTIAL_IPC_BUDGET_MS = 10_000\n\n/**\n * Per-challenge budget for one fingerprint probe. Deliberately NOT derived from\n * `probeTimeoutMs`: that one bounds a tiny /models read (15s default), while a\n * challenge asks for ~300 integers and the answer alone is several hundred\n * tokens. A provider that cannot answer in two minutes is a `failed` row, not a\n * reason to widen the listing probe.\n */\nconst FINGERPRINT_CHALLENGE_TIMEOUT_MS = 120_000\n\n/**\n * Fold the accepted challenges' timings into one picture for the result card:\n * the wall clock and first-token wait of the SLOWEST accepted challenge (that\n * is what the user actually waited for), plus the characters-per-second the\n * provider pushed once text started flowing. Throughput counts only the\n * generation window (total minus the first-token wait) so a long thinking\n * preamble shows up as a first-token wait, not as slow streaming. Pure\n * statistics only \u2014 the answer text itself is never stored (design \u00A74.2).\n */\nfunction fingerprintTimingOf(outcomes: readonly ProbeOutcome[]): FingerprintTiming | undefined {\n const accepted = outcomes.filter(outcome => outcome.ok && typeof outcome.durationMs === 'number')\n if (accepted.length === 0) return undefined\n const durationMs = Math.max(...accepted.map(outcome => outcome.durationMs ?? 0))\n const firstTokenMs = Math.max(...accepted.map(outcome => outcome.firstTokenMs ?? outcome.durationMs ?? 0))\n let characters = 0\n let generatingMs = 0\n for (const outcome of accepted) {\n const total = outcome.durationMs ?? 0\n const first = Math.min(outcome.firstTokenMs ?? total, total)\n const generating = total - first\n if (generating > 0) {\n characters += outcome.text.length\n generatingMs += generating\n }\n }\n return {\n durationMs,\n ...(firstTokenMs > 0 ? { firstTokenMs } : {}),\n ...(generatingMs > 0 ? { charsPerSecond: characters / (generatingMs / 1000) } : {}),\n }\n}\n\n/**\n * Fold each challenge's outcome into the per-question ledger the result card\n * draws as pills: how many integers this one asked for, how many came back,\n * and whether that counted. The accepted flag is NOT recomputed here \u2014 it is\n * read from the attribution's own diagnostics when there is one, so the pill\n * and the verdict can never disagree about which answers were pooled. Only the\n * floor rule is duplicated, and only for the no-attribution case (every call\n * died), where there is nothing to read.\n *\n * `diagnostics` is indexed by position in `run.outputs`, which holds ONLY the\n * challenges that answered \u2014 so a dead challenge shifts every later entry by\n * one. The running `pooled` counter is what keeps a pill from borrowing its\n * neighbour's number.\n *\n * `skipped` marks the challenge an early exit aborted: it never answered, and\n * calling that \"\u672A\u8BA1\u5165\" would send the user chasing a failure that did not\n * happen. Statistics only \u2014 no answer text (design \u00A74.2).\n */\nfunction fingerprintChallengesOf(\n outcomes: readonly ProbeOutcome[],\n attribution: AttributionResult | null,\n): FingerprintChallenge[] {\n const diagnostics = attribution?.diagnostics\n let pooled = -1\n return outcomes.map((outcome, position) => {\n if (outcome.ok) pooled += 1\n const diagnostic = outcome.ok ? diagnostics?.[pooled] : undefined\n const parsed = diagnostic?.parsed_numbers ?? 0\n return {\n index: position + 1,\n expected: outcome.expectedCount,\n parsed,\n accepted: diagnostic?.accepted ?? false,\n ...(outcome.skipped === true ? { skipped: true } : {}),\n }\n })\n}\n\n/**\n * How long ONE raw listing probe may take while Auto-adapt is waiting on it.\n * The wire read it bounds is one tiny `/models` read per endpoint family; a\n * gateway slower than this still answers the next attempt, and the cached\n * answer keeps a whole pass from re-reading it per model.\n */\nconst LISTING_PROBE_BUDGET_MS = 6_000\n\n/**\n * How long a raw probe answer is reused before the next request re-reads it.\n * Auto-adapt asks per model; a bounded window keeps those repeats off the wire\n * without ever pinning a stale listing on the user.\n */\nconst LISTING_CACHE_MS = 30_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 /** Deprecated compatibility field; absent providers retain their keys. */\n routeSweepGraceMs?: 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 routeSweepGraceMs: Schema.natural().default(ROUTE_SWEEP_GRACE_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 /** Manual assignment, restricted to the models this route has added. */\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 = Object.hasOwn(providers, route) ? providers[route] : undefined\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 manual assignments, 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 const scopes = Object.create(null) as Record<string, readonly RouteKeyScope[]>\n let document: ReturnType<typeof readKeyIndex>\n try {\n document = readKeyIndex(keyIndexFilePath())\n } catch {\n return scopes\n }\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 = routeEndpointsOf(document, 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 and Anthropic), 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/** A request may answer before IPC settles, but its index lease must not. */\nclass PendingCredentialMutations {\n private readonly pending = new Set<Promise<void>>()\n\n track<T>(operation: Promise<T>): Promise<T> {\n // Handle both outcomes here too: a late rejection after an HTTP timeout is\n // observed, and a never-settling store deliberately keeps the lease closed.\n const settled: Promise<void> = operation.then(\n () => { this.pending.delete(settled) },\n () => { this.pending.delete(settled) },\n )\n this.pending.add(settled)\n return operation\n }\n\n releaseAfterSettled(release: () => void): void {\n if (this.pending.size === 0) release()\n else void Promise.all([...this.pending]).then(release, release)\n }\n}\n\n/** The HTTP budget is not cancellation of the tracked credential mutation. */\nasync function awaitCredentialMutation<T>(\n operation: Promise<T>,\n pending: PendingCredentialMutations,\n budgetMs: number,\n): Promise<T> {\n pending.track(operation)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(\n `the credential store did not answer within ${Math.round(budgetMs / 1000)}s; the write result is unknown until it settles`,\n )), budgetMs)\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\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 pending: PendingCredentialMutations,\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 invalidateCredentialDisplay(credentials, ref)\n try {\n const operation = Promise.resolve().then(() => set.call(credentials, ref, value))\n .finally(() => { invalidateCredentialDisplay(credentials, ref) })\n const answer = await awaitCredentialMutation(operation, pending, CREDENTIAL_IPC_BUDGET_MS)\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 } finally {\n invalidateCredentialDisplay(credentials, ref)\n }\n}\n\n/**\n * Forget one reference's value; the refusal text, or undefined. A timeout is\n * uncertain, not a cancelled unset: rollback retains metadata, while the\n * request's lease stays held until the underlying operation actually settles.\n */\nasync function forgetCredential(\n credentials: CredentialsService | undefined,\n ref: string,\n pending: PendingCredentialMutations,\n budgetMs: number = CREDENTIAL_IPC_BUDGET_MS,\n): 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 invalidateCredentialDisplay(credentials, ref)\n try {\n const operation = Promise.resolve().then(() => unset.call(credentials, ref))\n .finally(() => { invalidateCredentialDisplay(credentials, ref) })\n const answer = await awaitCredentialMutation(operation, pending, budgetMs)\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 } finally {\n invalidateCredentialDisplay(credentials, ref)\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/**\n * Whether the store positively holds NOTHING under one reference.\n *\n * Both faces must agree: `describe` says unconfigured AND no value could be\n * read. A `configured: false` contradicted by a readable value is a stale\n * metadata face, not an empty credential, and an absent entry means the store\n * could not answer at all \u2014 unknown, never empty. Callers that must not\n * overwrite a key lean on exactly this distinction.\n * @param fact - what {@link credentialFacts} answered for the reference.\n * @returns true only for a confirmed empty reference.\n */\nfunction holdsNothing(fact: CredentialFacts | undefined): boolean {\n return fact !== undefined && fact.configured === false && fact.masked === 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\nconst CREDENTIAL_DISPLAY_TTL_MS = 5_000\nconst CREDENTIAL_DISPLAY_MAX_REFS = 512\n\n/** Only display facts live here; secrets and mutation preconditions never do. */\ninterface CredentialDisplayRead {\n expiresAt: number\n resolved?: CredentialFacts\n described?: boolean\n settled: Promise<void>\n}\nconst credentialDisplayReads = new WeakMap<CredentialsService, Map<string, CredentialDisplayRead>>()\n\nfunction invalidateCredentialDisplay(credentials: CredentialsService | undefined, ref: string): void {\n if (credentials !== undefined) credentialDisplayReads.get(credentials)?.delete(ref)\n}\n\n/** Short-lived per-ref singleflight for list previews, not authoritative reads. */\nasync function displayCredentialFacts(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n budgetMs: number,\n): Promise<Record<string, CredentialFacts>> {\n if (credentials === undefined || refs.length === 0) return {}\n let cache = credentialDisplayReads.get(credentials)\n if (cache === undefined) {\n cache = new Map()\n credentialDisplayReads.set(credentials, cache)\n }\n const now = Date.now()\n // Expire stalled flights too: a broken IPC read must not pin a ref forever.\n for (const [ref, read] of cache) if (read.expiresAt <= now) cache.delete(ref)\n const selected = new Map<string, CredentialDisplayRead>()\n const missing: string[] = []\n for (const ref of new Set(refs)) {\n let read = cache.get(ref)\n if (read === undefined) {\n read = { expiresAt: now + CREDENTIAL_DISPLAY_TTL_MS, settled: Promise.resolve() }\n cache.set(ref, read)\n missing.push(ref)\n }\n selected.set(ref, read)\n }\n // Keep describe batched while overlapping lists share each reference's flight.\n const described = missing.length === 0 || typeof credentials.describe !== 'function'\n ? Promise.resolve(undefined)\n : (async () => {\n try {\n const answer = await credentials.describe?.(missing)\n return isRefusal(answer) ? undefined : describeRecords(answer)\n } catch {\n return undefined\n }\n })()\n for (const ref of missing) {\n const read = selected.get(ref)!\n const resolved = (async (): Promise<boolean> => {\n try {\n const value = await resolveCredential(credentials, ref)\n const masked = value === undefined ? undefined : maskKeyValue(value)\n read.resolved = masked === undefined || masked.length === 0\n ? { configured: value !== undefined }\n : { configured: true, masked }\n return true\n } catch {\n return false\n }\n })()\n const metadata = described.then(records => {\n const info = records?.[ref]\n if (isRecord(info) && typeof info['configured'] === 'boolean') read.described = info['configured']\n return typeof credentials.describe !== 'function' || read.described !== undefined\n })\n read.settled = Promise.all([resolved, metadata]).then(([resolvedOK, describedOK]) => {\n // Delete/replacement invalidates the identity, so an old flight cannot\n // repopulate a ref after a credential write (including a rollback).\n if (cache.get(ref) !== read) return\n // Partial answers can paint this response but failures are never cached.\n read.expiresAt = resolvedOK && describedOK ? Date.now() + CREDENTIAL_DISPLAY_TTL_MS : 0\n })\n }\n while (cache.size > CREDENTIAL_DISPLAY_MAX_REFS) {\n const oldest = cache.keys().next().value\n if (oldest === undefined) break\n cache.delete(oldest)\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.all([...selected.values()].map(read => read.settled)),\n new Promise<void>(resolve => { timer = setTimeout(resolve, budgetMs) }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n const out: Record<string, CredentialFacts> = {}\n for (const [ref, read] of selected) {\n if (cache.get(ref) !== read) continue\n const configured = read.described ?? read.resolved?.configured\n if (configured === undefined) continue\n out[ref] = read.resolved?.masked === undefined ? { configured } : { configured, masked: read.resolved.masked }\n }\n return out\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 budgetMs?: number,\n): Promise<Record<string, CredentialFacts>> {\n const described: Record<string, boolean> = {}\n const resolvedFacts: Record<string, CredentialFacts> = {}\n if (credentials === undefined || refs.length === 0) return {}\n // Metadata and preview reads are independent IPC calls. Neither a slow\n // describe nor an earlier reference should hold every remaining row up.\n const reads: Promise<void>[] = refs.map(async ref => {\n try {\n const value = await resolveCredential(credentials, ref)\n const masked = value === undefined ? undefined : maskKeyValue(value)\n resolvedFacts[ref] = masked === undefined || masked.length === 0\n ? { configured: value !== undefined }\n : { configured: true, masked }\n } catch {\n // Unavailable is unknown, never an empty credential.\n }\n })\n if (typeof credentials.describe === 'function') {\n reads.push((async () => {\n try {\n const answer = await credentials.describe?.([...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') described[ref] = info['configured']\n }\n } catch {\n // Resolved previews can still answer without describe.\n }\n })())\n }\n const settled = Promise.all(reads)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n // Only display callers use this bound; mutation preconditions still wait\n // for an authoritative answer and fail closed when the store cannot read.\n if (budgetMs === undefined) await settled\n else await Promise.race([settled, new Promise<void>(resolve => { timer = setTimeout(resolve, budgetMs) })])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n const out: Record<string, CredentialFacts> = {}\n for (const ref of refs) {\n const fact = resolvedFacts[ref]\n const configured = described[ref] ?? fact?.configured\n if (configured === undefined) continue\n out[ref] = fact?.masked === undefined ? { configured } : { configured, masked: fact.masked }\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. A mutation\n * precondition passes a budget: a store that cannot answer within it leaves\n * the reference out of the map, which every mutation reads as \"unknown\" and\n * refuses \u2014 fail closed, but bounded, instead of hanging the manager route.\n */\nasync function credentialConfigured(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n budgetMs?: number,\n): Promise<Record<string, boolean>> {\n const facts = await credentialFacts(credentials, refs, budgetMs)\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/** What a masked credential header value reads as in diagnostics responses. */\nconst SENSITIVE_HEADER_MASK = '[stored, not echoed]'\n\n/** Whether a header name is credential-shaped (auth keys, tokens, cookies). */\nfunction sensitiveHeader(name: string): boolean {\n return /authorization|api-?key|token|secret|cookie|session/i.test(name)\n}\n\n/** Copy a headers dict with credential-shaped values masked. */\nfunction maskSensitiveHeaders(headers: Record<string, string>): Record<string, string> {\n const masked: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers)) {\n masked[name] = sensitiveHeader(name) ? SENSITIVE_HEADER_MASK : value\n }\n return masked\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\n // the last resolved section until the settings document reports that it\n // moved. The descriptor (resolved value + raw user layer + revision) is\n // what is cached, so every boot-time consumer \u2014 the dispatch guard's\n // section, the autofill's fill, and the compat guard's sweep \u2014 shares ONE\n // describe per document generation.\n let piDescriptorCache: ReturnType<typeof settings.describe>[number] | undefined\n let piDescriptorCached = false\n const piDescriptor = (required = false): ReturnType<typeof settings.describe>[number] | undefined => {\n if (piDescriptorCached) return piDescriptorCache\n let descriptor: ReturnType<typeof settings.describe>[number] | undefined\n try {\n descriptor = settings.describe().find(entry => entry.ns === PI_NS)\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 -- so a\n // not-ready read is never cached: the retry must reach the wire again.\n if (descriptor === undefined || !isRecord(descriptor.value)) {\n if (required) throw new HostReadError('the llm-pi-ai settings entry is unavailable')\n return undefined\n }\n piDescriptorCache = descriptor\n piDescriptorCached = true\n return descriptor\n }\n const piSection = (required = false): unknown => piDescriptor(required)?.value\n ctx.on('settings/document-updated', (ns) => {\n if (ns === PI_NS) piDescriptorCached = 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 = piDescriptor()\n if (descriptor === undefined) 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 // Compat guard (boot sweep): a wire protocol switched after compat switches\n // were written leaves the old keys behind on the route's models, and the\n // kernel then refuses every model that still carries one -- the route serves\n // nothing until the keys are gone. This pass heals what is already stored\n // (and covers headless compositions, which have no browser half); the\n // browser half repairs what a session changes on its idle pass. Also\n // deliberately NEVER on `settings/document-updated`: the issue #7 rule\n // holds here too.\n {\n const logGuardFailure = (error: unknown): void => {\n console.error(`[dsh-model-think-level] compat cleanup failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n const guardTimers = new Set<ReturnType<typeof setTimeout>>()\n ctx.effect(() => () => {\n for (const timer of guardTimers) clearTimeout(timer)\n guardTimers.clear()\n }, 'dsh-model-think-level: compat-guard boot retries')\n\n /** One sweep; resolves false while the pi-ai namespace is unregistered. */\n const sweepOnce = async (): Promise<boolean> => {\n const descriptor = piDescriptor()\n if (descriptor === undefined) return false\n const user = descriptor.user\n const userProviders = isRecord(user) && isRecord((user as Record<string, unknown>)['providers'])\n ? (user as Record<string, unknown>)['providers'] as Record<string, unknown>\n : undefined\n if (userProviders === undefined) return true\n const patch = buildCompatCleanupPatch(userProviders)\n if (patch === undefined) return true\n try {\n await settings.update(PI_NS, patch, descriptor.revision)\n } catch (error) {\n // A conflict with the boot fill's own write (both read the shared\n // descriptor) retries on the boot backoff \u2014 against a FRESH read, so\n // the cache that just lost the race is dropped. Anything else is\n // logged and left to the next boot or the browser half's idle pass.\n logGuardFailure(error)\n piDescriptorCached = false\n return false\n }\n return true\n }\n const bootSweep = (attempt: number): void => {\n void sweepOnce().then((ready) => {\n if (ready || attempt >= resolved.bootRetryDelaysMs.length) return\n const timer = setTimeout(() => {\n guardTimers.delete(timer)\n bootSweep(attempt + 1)\n }, resolved.bootRetryDelaysMs[attempt])\n guardTimers.add(timer)\n }, logGuardFailure)\n }\n bootSweep(0)\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 metadata (references and manual assignments; 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 // The most recent per-key listing this process obtained, by reference. It is\n // the fallback that keeps a key's models in the catalogue when its next probe\n // fails (a timeout, a 429, a gateway hiccup): without it one slow request\n // silently shrinks a two-key route to one key's models until the next\n // successful pass, which is exactly the \"one key's models disappeared\"\n // symptom. `mergeKeyListings` reports such keys as `retained`.\n const lastKnownScopes = new Map<string, readonly string[]>()\n // The full listing records behind those ids (display name, limits, effort\n // ladder). A retained id must still resolve to its record when the catalogue\n // is rebuilt, or the merge would drop the very models it just kept.\n const lastKnownRecords = new Map<string, ListedModel[]>()\n // Merged catalogues, shortest-lived first: the harness re-requests `/models`\n // on refresh and on every reconnect, and the probe behind it can take\n // seconds per key. A short window turns those repeats into memory reads\n // without ever serving a catalogue the user cannot refresh.\n const listingCache = new Map<string, { at: number; body: string }>()\n // What each key's last successful listing advertised, persisted across restarts\n // (key-serves.ts). The overlay reads it to order keys by \"lists this model\" and\n // to guard an explicit model scope; the write is debounced because the hot path\n // that fills it runs inside a `/models` answer.\n const keyServes: { current: KeyServesDocument | undefined } = { current: undefined }\n const servesDocument = (): KeyServesDocument => (keyServes.current ??= readKeyServes(keyServesFilePath()))\n let servesTimer: ReturnType<typeof setTimeout> | undefined\n const flushServes = (): void => {\n servesTimer = undefined\n try {\n writeKeyServes(servesDocument(), keyServesFilePath())\n } catch {\n // Observations are a cache: a failed write costs one round of retries after\n // a restart, never an answer.\n }\n }\n const recordServes = (route: string, ref: string, models: readonly string[]): void => {\n // A listing with no ids asserts \"serves nothing\"; keep what was known instead.\n // The same rule as `withServes`, applied before the document is touched.\n const live = servesDocument()\n if (models.length === 0) return\n keyServes.current = withServes(live, route, ref, models, Date.now())\n if (servesTimer === undefined) servesTimer = setTimeout(flushServes, 200)\n }\n /** The serving knowledge of one route, or undefined when nothing is known yet. */\n const servingKnowledgeOf = (route: string): ServingKnowledge | undefined => {\n const listed = servesOfRoute(servesDocument(), route)\n return listed.size === 0 ? undefined : { listed }\n }\n /**\n * Forget what a key's listing said. Called when the key's VALUE changes (a\n * different credential is a different upstream account, so the old catalogue\n * describes nothing) and when it is removed. Written through immediately: these\n * are rare, user-initiated operations, and a stale observation outliving a\n * replaced key would send the next request to the wrong account.\n */\n const forgetServes = (route: string, ref: string): void => {\n keyServes.current = withoutServes(servesDocument(), route, ref)\n try {\n writeKeyServes(keyServes.current, keyServesFilePath())\n } catch {\n // Observations are a cache; the in-memory copy is already correct.\n }\n }\n // Raw listing answers for the probe route, by target. Auto-adapt asks for the\n // same route once per model, so this is what turns a whole pass into one\n // wire read; `?refresh=1` (and the TTL above) keeps it from going stale.\n const probeRouteCache = new Map<string, { at: number; data: Record<string, unknown>[] }>()\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 // Names and declared model edits do not change the upstream catalogue. A\n // Save followed by adapter refresh can reuse it without remote detection.\n // A half-written document can park `null` on a provider slot; skipped here,\n // or the boot read would throw before the routes even register.\n const catalogueSource = (): string => JSON.stringify(Object.entries(providersOf())\n .filter(([, profile]) => isRecord(profile))\n .map(([route, profile]) => [\n route, profile['api'], profile['baseURL'], profile['apiKeyEnv'], profile['headers'],\n ]).sort(([a], [b]) => String(a).localeCompare(String(b))))\n let catalogueSourceStamp = catalogueSource()\n /**\n * Drop the cached upstream catalogues.\n *\n * With a route: only that route's overlay answers go \u2014 its key list (or wire)\n * changed, and every OTHER route's keys and wires did not, so their answers\n * are still true. Clearing everything here made one provider's key edit\n * re-probe every provider on the next `/models`, seconds per key inside an\n * answer the caller is waiting on.\n *\n * Without a route (the settings catalogue itself changed \u2014 providers added,\n * re-pointed, re-credentialed): the whole cache, because which routes exist\n * and what they point at is no longer the one it was cached under.\n */\n const invalidateListings = (route?: string): void => {\n if (route === undefined) {\n probeRouteCache.clear()\n listingCache.clear()\n return\n }\n const prefix = `${route}\\u0000`\n for (const key of Array.from(listingCache.keys())) {\n if (key.startsWith(prefix)) listingCache.delete(key)\n }\n }\n\n // A missing provider is not a credential-deletion instruction. Boot,\n // reload and sync can all publish an incomplete (even valid empty) profile.\n // Keep its key metadata, endpoints and balance URL until an explicit key\n // operation removes them; never infer permission to unset a secret here.\n\n // ---- Scope probe: what each key serves, kept true automatically ----\n //\n // A relay resolves each key to a different upstream account with its own\n // catalogue, so the models a route declares are not the models every key\n // serves \u2014 requests discover the difference the hard way, one refusal per\n // model per key, unless each key's scope is kept to what it actually serves.\n // The probe does that: every switched-on key of a MULTI-KEY route is asked\n // for its own listing on the wires it could serve on, the answers are\n // recorded as observations (key-serves.ts), and each key's model scope is\n // then checked to the models it listed WITHIN the set the route declares:\n //\n // - it lists all of them \u2192 the catch-all it already reads as IS the\n // assignment, so no scope is written and the key keeps serving models\n // added later;\n // - it lists some of them \u2192 that intersection is written as the key's\n // scope (marked `auto`, so the panel can say whose assignment it is);\n // - it lists none of them \u2192 the key cannot serve this provider at all, so\n // the key's own row is switched off. The provider is left alone: one\n // unusable upstream account must not take the whole route down. A key\n // the user switched off by hand is never probed, and a key the probe\n // switched off stays off until the user switches it back on \u2014 the probe\n // has no separate \"was this me?\" bit to re-enable from.\n //\n // Every sweep rewrites whatever it finds, manual assignments included: with\n // two triggers (the key panel's \u81EA\u52A8\u63A2\u6D4B button, and a save that moves a\n // provider's address, protocol, key reference or model list) nobody has to\n // keep the split up to date by hand.\n\n /** In-flight probe runs, by route; the list payload reports this as `probing`. */\n const keyProbeRuns = new Map<string, Promise<void>>()\n let probeStopped = false\n ctx.effect(() => () => { probeStopped = true })\n\n /**\n * Probe one route now: resolve every switched-on key (and the profile's own\n * seat, when the index has never listed it), ask each on the wires a request\n * could take, record the observations, and write what each key serves within\n * the route's declared set \u2014 a scope when it carries part of the catalogue, a\n * switched-off row when it carries none of it, nothing when it carries all of\n * it. A route with fewer than two switched-on keys has nothing to divide \u2014\n * one key serves whatever it serves \u2014 so the sweep stops before the wire.\n */\n const probeRouteKeys = async (route: string): Promise<void> => {\n if (probeStopped) return\n const indexFile = keyIndexFilePath()\n let profile: Record<string, unknown> | undefined\n try {\n profile = providerProfileOf(piSection(true), route)\n } catch {\n return\n }\n if (profile === undefined) return\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\n // The route's own model list is the universe a scope is written in, so a\n // route without one has nothing to check any key against \u2014 and no reason to\n // spend a listing request finding that out.\n const declaredIds = Array.isArray(profile['models'])\n ? profile['models'].filter(isRecord).map(model => typeof model['id'] === 'string' ? model['id'].trim() : '').filter(Boolean)\n : []\n if (declaredIds.length === 0) return\n let document: ReturnType<typeof readKeyIndex>\n try {\n document = readKeyIndex(indexFile)\n } catch {\n // A malformed index is the key route's complaint to make, not the probe's.\n return\n }\n const endpoints = routeEndpointsOf(document, route)\n // A switched-off key is out of the pool already: the probe neither asks it\n // nor keeps asking a row it switched off itself.\n const listed = keyEntriesOf(document, route)\n const active = listed.filter(entry => entry.disabled !== true)\n const seat = enabledRefOf(profile)\n const keys: { ref: string; entry: KeyIndexEntry | undefined }[] = active.map(entry => ({ ref: entry.ref, entry }))\n if (seat !== undefined && !listed.some(entry => entry.ref === seat)) keys.push({ ref: seat, entry: undefined })\n // One key serves whatever it serves: the scope check exists to divide a\n // route's models across keys, and a single-key route has no division.\n if (keys.length < 2) return\n const credentials = ctx.get('credentials') as CredentialsService | undefined\n const values = await Promise.all(keys.map(async key => {\n try {\n return await resolveCredential(credentials, key.ref)\n } catch {\n return undefined\n }\n }))\n if (probeStopped) return\n const askable = keys.flatMap((key, index) => {\n const value = values[index]\n return value === undefined || value.length === 0 ? [] : [{ ...key, value }]\n })\n if (askable.length === 0) return\n // Background work nobody waits on: each listing gets the FULL probe budget\n // (the catalogue overlay caps at LISTING_PROBE_BUDGET_MS because it runs\n // inside the host's own /models answer; this probe has no such caller, so\n // a slow gateway just takes longer to be observed, never blocks anyone).\n const timeoutMs = resolved.probeTimeoutMs\n const send = headerOverlayBypass()\n const targetsOf = (entry: KeyIndexEntry | undefined): ProbeTarget[] =>\n entry?.protocol !== undefined\n ? listingTargetsOf({ protocol: entry.protocol, endpoint: endpoints?.[endpointFamilyOf(entry.protocol)] }, api, baseURL)\n : listingTargetsOf({ endpoints }, api, baseURL)\n const served = new Map<string, readonly string[]>()\n await collectKeyListings({\n keys: askable,\n refOf: key => key.ref,\n probe: async key => {\n if (probeStopped) return { ref: key.ref, models: undefined }\n // A key's targets are independent listings; they run together and fold\n // in target order, exactly as the catalogue overlay folds them.\n const listings = await Promise.all(targetsOf(key.entry).map(target => probeListing({\n baseURL: target.baseURL,\n api: target.api,\n apiKey: key.value,\n headers: profile?.['headers'],\n timeoutMs,\n send,\n })))\n if (probeStopped) return { ref: key.ref, models: undefined }\n const ids: string[] = []\n for (const listing of listings) {\n if (listing === undefined) continue\n for (const model of listing) {\n if (!ids.includes(model.id)) ids.push(model.id)\n }\n }\n if (ids.length === 0) return { ref: key.ref, models: undefined }\n // Keep wire results local until the live commit owns the shared lease.\n served.set(key.ref, ids)\n return { ref: key.ref, models: ids }\n },\n })\n if (probeStopped || served.size === 0) return\n // The POST only queues this probe; it never awaits it while holding a\n // mutation lease. Network work stays outside the shared commit lease.\n const releaseMutation = await acquireKeyMutation(indexFile)\n try {\n if (probeStopped) return\n const currentProfile = providerProfileOf(settings.describe().find(entry => entry.ns === PI_NS)?.value, route)\n if (currentProfile === undefined) return\n // Scope only the models still declared after acquiring the lease.\n const declared = Array.isArray(currentProfile['models'])\n ? currentProfile['models'].filter(isRecord).map(model => typeof model['id'] === 'string' ? model['id'].trim() : '').filter(Boolean)\n : []\n if (declared.length === 0) return\n // Keys, aliases, endpoints and manual claims may have changed on the wire\n // or while this commit waited for another writer. Read only now.\n let next = readKeyIndex(indexFile)\n let mutated = false\n const emptied: string[] = []\n for (const [ref, ids] of served) {\n // Publish observations only while this live commit owns the lease.\n lastKnownScopes.set(`${route}\\u0000${ref}`, ids)\n recordServes(route, ref, ids)\n const entry = keyEntriesOf(next, route).find(candidate => candidate.ref === ref)\n // An unlisted seat keeps its catch-all and recorded observations.\n if (entry === undefined) continue\n const target = declared.filter(id => ids.includes(id))\n if (target.length === 0) {\n // Nothing this key lists belongs to this provider: it cannot serve a\n // single model here, so its own row is switched off (never the\n // provider \u2014 one unusable upstream account must not take the route\n // down). Applied below, where the route's last key is protected.\n if (entry.disabled !== true) emptied.push(ref)\n continue\n }\n // Every declared model: the catch-all the entry already reads as IS the\n // assignment, so adding models later keeps working without another pass.\n const scope = target.length === declared.length ? undefined : target\n const unchanged = scope === undefined\n ? entry.models === undefined\n : entry.models !== undefined && entry.models.length === scope.length && scope.every(id => entry.models?.includes(id))\n if (unchanged) continue\n next = withKeyAutoScope(next, route, ref, scope)\n mutated = true\n }\n if (emptied.length > 0) {\n // A route must keep a key: switching off the last one would leave the\n // model list pointing at a provider nothing can sign for, which is a\n // bigger claim than \"these keys serve none of these models\" \u2014 most\n // often it means the ids simply do not line up, so the rows stay as\n // they are and the user keeps a pool to fix.\n const after = keyEntriesOf(next, route)\n const activeLeft = after.filter(entry => entry.disabled !== true && !emptied.includes(entry.ref)).length\n const seatLeft = seat !== undefined && !after.some(entry => entry.ref === seat) ? 1 : 0\n if (activeLeft + seatLeft > 0) {\n for (const ref of emptied) next = withKeyDisabled(next, route, ref, true)\n mutated = true\n }\n }\n if (!mutated) return\n try {\n writeKeyIndex(next, indexFile)\n } catch {\n // A failed write costs one round of re-probing after the next save.\n return\n }\n refreshKeyScopes()\n } finally {\n releaseMutation()\n }\n }\n\n /** Probe one route, queueing behind the run already in flight, if any. */\n const runKeyProbe = (route: string): Promise<void> => {\n if (probeStopped) return Promise.resolve()\n const previous = keyProbeRuns.get(route) ?? Promise.resolve()\n const run = previous\n .then(() => probeStopped ? undefined : probeRouteKeys(route))\n .catch(() => {\n // A probe never surfaces: the panel's next button press is the retry.\n })\n .finally(() => {\n if (keyProbeRuns.get(route) === run) keyProbeRuns.delete(route)\n })\n keyProbeRuns.set(route, run)\n return run\n }\n\n // ---- The second trigger: a save that moves a route ----\n //\n // The button is the deliberate trigger; a save is the automatic one. Only the\n // parts of a profile that decide what the sweep would ask (the wire, the key\n // reference, the declared models) count as a move \u2014 renaming a provider,\n // changing a display name or a balance URL leaves every scope true and must\n // not put a listing request on the wire. Saves also cluster (the official\n // card writes the whole profile, the autofill pass writes again), so one\n // timer collects them: a sweep per save would ask the same questions three\n // times in a row.\n const PROBE_SAVE_DELAY_MS = 1_000\n const probeSignatures = new Map<string, string>()\n const probeSavePending = new Set<string>()\n let probeSaveTimer: ReturnType<typeof setTimeout> | undefined\n /** What a sweep would ask about: a change here means the scopes may be stale. */\n const probeSignatureOf = (profile: Record<string, unknown>): string => JSON.stringify([\n profile['api'],\n profile['baseURL'],\n profile['apiKeyEnv'],\n profile['headers'],\n Array.isArray(profile['models'])\n ? profile['models']\n .filter(isRecord)\n .map(model => typeof model['id'] === 'string' ? model['id'].trim() : '')\n .filter(Boolean)\n .sort()\n : [],\n ])\n const armProbeTimer = (): void => {\n if (probeStopped || probeSavePending.size === 0 || probeSaveTimer !== undefined) return\n probeSaveTimer = setTimeout(() => {\n probeSaveTimer = undefined\n const routes = Array.from(probeSavePending)\n probeSavePending.clear()\n for (const route of routes) void runKeyProbe(route)\n }, PROBE_SAVE_DELAY_MS)\n }\n /**\n * Saves arrive through the settings listener; key edits (a new credential, a\n * switched-off row, a protocol pin) arrive through the POST below and name\n * their route outright. Both end in the same debounce.\n */\n const scheduleKeyProbes = (changed?: string): void => {\n if (probeStopped) return\n const providers = providersOf()\n for (const route of Array.from(probeSignatures.keys())) {\n if (!Object.hasOwn(providers, route)) probeSignatures.delete(route)\n }\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile)) continue\n const signature = probeSignatureOf(profile)\n if (probeSignatures.get(route) === signature) continue\n probeSignatures.set(route, signature)\n probeSavePending.add(route)\n }\n // A key edit changes the index, not the profile: the signature cannot see\n // it, so the caller names the route that must be asked again anyway.\n if (changed !== undefined && Object.hasOwn(providers, changed)) probeSavePending.add(changed)\n armProbeTimer()\n }\n // Boot seeds the signatures without sweeping: what is declared at boot was\n // declared before this process started, so nothing about it is news.\n for (const [route, profile] of Object.entries(providersOf())) {\n if (isRecord(profile)) probeSignatures.set(route, probeSignatureOf(profile))\n }\n ctx.effect(() => () => {\n if (probeSaveTimer !== undefined) clearTimeout(probeSaveTimer)\n probeSaveTimer = undefined\n probeSavePending.clear()\n })\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 // Refresh routing, but retain metadata and secrets for absent providers.\n // A settings snapshot is not an explicit key-removal request.\n // The image side rides the same events: the config file's derived\n // models[] re-derives from this document (config page, MCP, command).\n syncImageConfigNow()\n const source = catalogueSource()\n if (source !== catalogueSourceStamp) {\n catalogueSourceStamp = source\n invalidateListings()\n }\n // A save that moved a provider's wire, key reference or model list makes\n // the scopes it left behind a guess: sweep the affected routes once the\n // cluster of saves settles.\n scheduleKeyProbes()\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 servingKnowledgeOf(route),\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 // Which keys a catalogue was merged from decides what the cache may answer:\n // adding, removing or reordering a key changes the answer, so it changes\n // the key too. A hit skips the wire entirely \u2014 the same refresh (and the\n // many Auto-adapt probes) then costs nothing.\n const cacheKey = `${route}\\u0000${keys.map(key => key.ref).join(',')}`\n const cached = listingCache.get(cacheKey)\n if (cached !== undefined && Date.now() - cached.at < LISTING_CACHE_MS) {\n return new Response(cached.body, { status: 200, headers: { 'content-type': 'application/json' } })\n }\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 across keys, and one key's refusal never drops\n // the others \u2014 a key that cannot answer keeps the models it was last seen\n // serving (`lastKnownScopes`), so one slow request cannot shrink a two-key\n // route to one key's models until the next pass.\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 // One budget for the whole catalogue, not one per target: this runs INSIDE\n // the host's own `/models` GET, so the caller is waiting on it.\n const probeTimeoutMs = Math.min(resolved.probeTimeoutMs, LISTING_PROBE_BUDGET_MS)\n // The memory is stored per ROUTE and reference (two routes may name the same\n // `apiKeyEnv`), while the merge speaks one reference space. Narrow it here.\n const here = (ref: string): string => `${route}\\u0000${ref}`\n const knownHere = new Map<string, readonly string[]>()\n for (const key of keys) {\n const remembered = lastKnownScopes.get(here(key.ref))\n if (remembered !== undefined) knownHere.set(key.ref, remembered)\n }\n const { results } = await collectKeyListings({\n keys,\n refOf: key => key.ref,\n lastKnown: knownHere,\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 the post-save scope probe records.\n const distinct = listingTargetsOf(key, api, baseURL)\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 // The targets of ONE key are independent listings: asking them one after\n // another made a key with two addresses cost two timeouts in series\n // while the host's `/models` GET waited. They run together, and the\n // answers are folded in target order so the catalogue stays stable.\n const answered = await Promise.all(distinct.map(target => probeListing({\n baseURL: target.baseURL,\n api: target.api,\n apiKey: key.value,\n headers: profile?.['headers'],\n timeoutMs: probeTimeoutMs,\n send: sendListing,\n })))\n const records: ListedModel[] = []\n for (const listing of answered) {\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 }\n recordsByRef.set(key.ref, records)\n const ids = records.map(model => model.id)\n // Remember what this key serves, so a later failed probe retains it.\n lastKnownScopes.set(here(key.ref), ids)\n lastKnownRecords.set(here(key.ref), records)\n // And record it across restarts: routing prefers the key whose group\n // listed a model over one that did not (key-serves.ts).\n recordServes(route, key.ref, ids)\n return {\n ref: key.ref,\n models: ids,\n }\n },\n })\n const records = new Map<string, ListedModel>()\n for (const result of results) {\n // A key that could not answer contributes the records it was last seen\n // serving: the merge kept its ids, so their full records must be kept too.\n const owned = recordsByRef.get(result.ref) ?? lastKnownRecords.get(here(result.ref)) ?? []\n for (const model of owned) {\n if (!records.has(model.id)) records.set(model.id, model)\n }\n }\n const census = servesOfRoute(servesDocument(), route)\n // Only a COMPLETE census may hide a model: every key answered its listing, so\n // a model none of them advertises is one no key's upstream group carries \u2014\n // offering it would offer a request the provider answers with \"not supported\n // by any configured account in this group\" on every key. A key that could not\n // be listed is unknown, not empty: with one unknown, nothing is hidden.\n const censusComplete = keys.length > 0 && keys.every(key => census.has(key.ref))\n const models = mergeKeyListings(results, knownHere).ids\n .filter(id => !censusComplete || [...census.values()].some(served => served.includes(id)))\n .map(id => records.get(id))\n .filter((model): model is ListedModel => model !== undefined)\n if (models.length === 0) return undefined\n const body = JSON.stringify({ data: models })\n listingCache.set(cacheKey, { at: Date.now(), body })\n return new Response(body, {\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 // ---- Image generation (\u751F\u56FE): config sync, native tool, `/\u751F\u56FE` command ----\n\n // One-time migration: the retired stdio MCP server's patch entry must go,\n // or every boot would spawn a `lib/image-mcp.mjs` that no longer exists and\n // the profile would keep a duplicate `mcp__dsh-image__generate_image` beside\n // the native tool. Best-effort: a read-only file only costs the cleanup, and\n // the next boot retries.\n try {\n const removed = removeLegacyImageMcpPatch()\n if (removed !== undefined) {\n console.warn(`[dsh-model-think-level] \u5DF2\u81EA\u52A8\u79FB\u9664\u65E7\u7248\u751F\u56FE MCP \u7684\u8865\u4E01\u6761\u76EE\uFF08${removed}\uFF09\u2014\u2014\u91CD\u542F DSH \u540E\u5B8C\u5168\u751F\u6548`)\n }\n } catch (error) {\n console.warn(`[dsh-model-think-level] \u65E7\u7248\u751F\u56FE MCP \u8865\u4E01\u6761\u76EE\u81EA\u52A8\u79FB\u9664\u5931\u8D25\uFF08\u53EF\u624B\u52A8\u5220\u9664\u6807\u8BB0\u5757\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}`)\n }\n //\n // There is NO wire interception any more: a chat model asks for a picture by\n // CALLING the MCP tool (`mcp__dsh-image__generate_image`), so image models\n // stay out of the composer's switcher and nothing rewrites an outbound\n // chat/completions request.\n\n /**\n * Re-derive the config file's `models[]` from the settings document, keeping\n * every stored override. Runs on boot and on every pi-ai document update, so\n * the config page, the MCP server and the command all read one snapshot.\n * Skipped while llm-pi-ai has not registered (an empty providers\n * map at boot must not wipe a config the previous run wrote).\n */\n const syncImageConfigNow = (): void => {\n try {\n if (piSection() === undefined) return\n const providers = providersOf()\n // An EMPTY providers map is not the user deleting their models: it is what\n // the document looks like before it is readable (boot, HMR, a reload that\n // re-registers the section before its value lands). Syncing it would write\n // models: [] and stamp defaultModel to null, and no later pass recovers the\n // pick. Only a populated document may prune rows.\n if (Object.keys(providers).length === 0) return\n updateImageConfig(document => syncImageConfig(document, providers))\n } catch {\n // The config file is best-effort state: a failed sync leaves the last\n // snapshot on disk, which the next successful sync replaces wholesale.\n }\n }\n syncImageConfigNow()\n\n /** The generation deps the host serves the core with (credentials via the store). */\n const imageGenerateDeps: GenerateDeps = {\n config: () => readImageConfig(),\n resolveKey: async ref => {\n try {\n return await resolveCredential(ctx.get('credentials') as CredentialsService | undefined, ref)\n } catch {\n return undefined\n }\n },\n // Beneath the wrapper: the images call composes its own auth from the\n // model row's reference, exactly like the listing probe above.\n send: headerOverlayBypass(),\n persistLastGood: (modelId, params) => {\n try {\n updateImageConfig(document => ({\n ...document,\n models: document.models.map(model => {\n if (model.id !== modelId) return model\n if (params === null) {\n return { ...model, endpoint: { ...model.endpoint, status: 'unsupported' as const } }\n }\n return { ...model, lastGoodParams: params }\n }),\n }))\n } catch {\n // A diagnostics write must never fail the generation that earned it.\n }\n },\n }\n\n // The `/\u751F\u56FE` host command. Registered only when the context carries a\n // commands service (a headless composition may not) \u2014 cordis THROWS on an\n // undeclared service read, so the lookup is fenced.\n let commandsService: CommandsServiceLike | undefined\n try {\n commandsService = (ctx as unknown as { commands?: CommandsServiceLike }).commands\n } catch {\n commandsService = undefined\n }\n registerImagegenCommand(\n commandsService,\n {\n modelIds: () => readImageConfig().models.map(model => model.id),\n generate: generateImage,\n generateDeps: imageGenerateDeps,\n },\n )\n\n // The native `generate_image` tool: the conversation model's primary entry.\n // Deferred on purpose \u2014 a host without the tools or attachments service\n // (headless, sdk) keeps every other feature and simply gets no image tool;\n // a hard `inject` entry would refuse to apply the whole plugin there.\n // The registration state feeds the client's keyed image-card registration,\n // which reads the name back over the config route.\n const imageToolState: { name: string | undefined; error: string | undefined } = { name: undefined, error: undefined }\n // The route saves the switch, so it needs a way to make the registry follow:\n // without it the pane would claim \"on\" while the session still has no tool\n // (or still has one it should no longer see).\n let reconcileImageTool: (() => void) | undefined\n ctx.inject(['tools', 'attachments'], (toolCtx: Context) => {\n let registered: { readonly name: string; readonly dispose: () => void } | undefined\n const release = (): void => {\n const current = registered\n registered = undefined\n imageToolState.name = undefined\n if (current === undefined) return\n try {\n current.dispose()\n } catch {\n // A registry that refuses the removal still drops the tool with the\n // plugin scope; the switch has done all it can.\n }\n }\n const acquire = (): void => {\n if (registered !== undefined) return\n // A throwing registration must not throw out of the route either: record\n // the message so the pane can show why, exactly like the boot path did.\n try {\n registered = registerGenerateImageTool(toolCtx, {\n generateDeps: imageGenerateDeps,\n attachments: (toolCtx as unknown as { attachments: unknown }).attachments as Parameters<typeof registerGenerateImageTool>[1]['attachments'],\n readConfig: () => readImageConfig(),\n })\n imageToolState.name = registered.name\n imageToolState.error = undefined\n } catch (error) {\n imageToolState.name = undefined\n imageToolState.error = error instanceof Error ? error.message : String(error)\n console.warn(`[dsh-model-think-level] \u5185\u5EFA\u751F\u56FE\u5DE5\u5177\u6CE8\u518C\u5931\u8D25\uFF08\u8BCA\u65AD\u8DEF\u7531 ${IMAGE_CONFIG_PATH} \u7684 tool.error \u4F1A\u5E26\u56DE\u8FD9\u6761\u539F\u56E0\uFF09\uFF1A${imageToolState.error}`)\n }\n }\n const reconcile = (): void => {\n if (readImageConfig().enabled) acquire()\n else release()\n }\n reconcileImageTool = reconcile\n toolCtx.effect(\n () => {\n reconcile()\n return () => {\n reconcileImageTool = undefined\n release()\n }\n },\n 'dsh-model-think-level: generate_image tool',\n )\n // A few lines of live defaults per model request, so the tool is called\n // with omitted params instead of guessed ones (the dsh-image-gen\n // precedent). Optional: hosts without the system-prompt service boot\n // unchanged and the tool description alone still guides the model.\n ctx.inject(['systemPrompt'], (promptCtx: Context) => {\n promptCtx.effect(\n () => (promptCtx as unknown as { systemPrompt: { context(contribution: { name: string; order: number; text: () => string }): () => void } }).systemPrompt.context({\n name: 'dsh-model-think-level:image-tool',\n order: 61,\n text: () => imageToolHint(readImageConfig()),\n }),\n 'dsh-model-think-level: image tool hint',\n )\n })\n })\n\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 // The fingerprint route dispatches through the same service, discovered the\n // same way: whichever of the two shapes supplied it, and re-read at request\n // time so a late registration is picked up.\n let fingerprintDispatch: LlmDispatchLike | undefined = availableLlm as LlmDispatchLike | undefined\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) {\n fingerprintDispatch = llm as LlmDispatchLike\n installPiAiBridge(llm)\n }\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 // Serializes fingerprint store writes (POST and DELETE) so two clicks cannot\n // interleave a read-modify-write. Reads stay unqueued, exactly like\n // `acquireKeyMutation` below.\n let fingerprintMutationTail = Promise.resolve()\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 // One listing read answers a whole Auto-adapt pass (it asks per\n // model) and every key-panel probe of the same route inside the\n // window. The identity of a read is the target plus the credential\n // reference it was composed from, so re-pointing a route or swapping\n // its `apiKeyEnv` never serves the previous answer; `?refresh=1`\n // forces the wire instead of waiting out the window.\n const listingKey = `${listingURL}\\u0000${apiKeyEnv ?? ''}`\n const cacheable = url.searchParams.get('refresh') !== '1'\n const remembered = cacheable ? probeRouteCache.get(listingKey) : undefined\n if (remembered !== undefined && Date.now() - remembered.at < LISTING_CACHE_MS) {\n sendJson(res, 200, { ok: true, url: displayUrl(listingURL), data: remembered.data })\n return\n }\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 // This probe waits on an interactive pass (Auto-adapt asks for\n // it per model), so it gets the catalogue budget rather than the\n // diagnostic one: a gateway that cannot list within it yields no\n // endpoint evidence, and the pass moves on to the knowledge base.\n signal: AbortSignal.timeout(Math.min(resolved.probeTimeoutMs, LISTING_PROBE_BUDGET_MS)),\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 probeRouteCache.set(listingKey, { at: Date.now(), data: entries })\n sendJson(res, 200, { ok: true, url: displayUrl(listingURL), data: entries })\n } catch (error) {\n // undici's own failure texts quote the original URL verbatim\n // (\"Request cannot be constructed from a URL that includes\n // credentials: http://user:sekrit@\u2026\") \u2014 the message loses its\n // secrets before it reaches the response body.\n sendJson(res, 502, {\n ok: false,\n error: `could not reach ${displayUrl(listingURL)}: ${redactUrlSecrets(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 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 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 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 res.setHeader('x-dsh-key-integrity', '20261101-explicit-delete+history64+shared-lease-drain')\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 const indexFile = keyIndexFilePath()\n const pendingMutations = new PendingCredentialMutations()\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 release = await acquireKeyMutation(indexFile)\n let finished = false\n releaseMutation = () => {\n if (finished) return\n finished = true\n pendingMutations.releaseAfterSettled(release)\n }\n }\n // The endpoint pair a provider card paints, answered from the index\n // file alone.\n //\n // The page hydrates this once per card per second (see the client's\n // `readEndpoints`) just to show two URLs. It used to pull the whole\n // key list for it -- a settings read plus one credential resolve per\n // key, on a service that serialises -- so an opened card's own list\n // queued behind dozens of those and the panel showed its loader for\n // seconds. This branch touches no settings and no credential.\n if (req.method === 'GET' && url.searchParams.get('op') === 'endpoints') {\n if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a route is required' })\n return\n }\n const endpoints = routeEndpointsOf(readKeyIndex(indexFile), route)\n sendJson(res, 200, {\n ok: true,\n route,\n endpoints: {\n openai: endpoints?.openai ?? null,\n anthropic: endpoints?.anthropic ?? null,\n },\n })\n return\n }\n if (req.method === 'GET' && url.searchParams.get('op') === 'balance') {\n if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a route is required' })\n return\n }\n const endpoint = routeBalanceOf(readKeyIndex(indexFile), route)\n sendJson(res, 200, { ok: true, route, endpoint: endpoint ?? null })\n return\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 /**\n * The profile a READ renders, from the section the guard and probe\n * routes already cache.\n *\n * This list is repainted constantly -- one GET per provider card\n * per second, plus one per invalidation -- and every one of them\n * used to call `settings.describe()`, a call the settings service\n * serialises across the whole host: that queue, not the list\n * itself, is what made an opened card wait seconds for its first\n * answer. The cache is dropped on `settings/document-updated`, so a\n * write from anywhere (this route, the official card's Save, the\n * autofill pass) still reaches the next read. Writes keep their own\n * fresh read below: a precondition decided from a snapshot is how a\n * route moves a key it no longer owns.\n */\n const readProfile = (): Record<string, unknown> | undefined =>\n providerProfileOf(piSection(true), route)\n /** The profile this request may fence a write on. */\n const writeProfile = (): Record<string, unknown> | undefined =>\n providerProfileOf(entryOf()?.value, route)\n const profileOf = (): Record<string, unknown> | undefined =>\n req.method === 'POST' ? writeProfile() : readProfile()\n if (route.length === 0 || profileOf() === 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\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<Record<string, 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 // Reads render from the cached section; a POST renders what it\n // just wrote, so it reads the document again (see `profileOf`).\n const profile = profileOf()\n const seat = enabledRefOf(profile)\n const routeModels = Array.isArray(profile?.['models'])\n ? profile['models'].filter(isRecord).map(model => typeof model['id'] === 'string' ? model['id'].trim() : '').filter(Boolean)\n : []\n const declaredModels = new Set(routeModels)\n const listed = keyEntriesOf(document, route)\n const refs = listed.map(entry => entry.ref)\n // The seat (the reference the adapter itself resolves) joins the\n // list when it can answer for itself: the index lists it, or the\n // store holds a value for it \u2014 the adapter still needs that one.\n // A profile can also name a reference nothing was ever stored\n // under (`apiKeyEnv: MAGPIE_GATEWAY_KEY` written by a shipped\n // patch, with no such variable in the environment). That is a\n // route waiting for its first key, not a key: painting it as a\n // \"not stored\" row put a phantom beside the official warning\n // that already says the variable is missing. Only a store that\n // positively answers \"nothing, and no value to read\" hides it \u2014\n // a store that cannot answer is unknown, not empty.\n const probed = seat !== undefined && !refs.includes(seat) ? [...refs, seat] : refs\n const facts = await displayCredentialFacts(credentials, probed, 250)\n if (seat !== undefined && !refs.includes(seat) && !holdsNothing(facts[seat])) refs.push(seat)\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.models = stored.models.filter(id => declaredModels.has(id))\n // Whose assignment the scope is: the probe writes every scope\n // it lands itself and says so, so the panel can report that\n // the ticks follow what each key lists rather than a choice.\n if (stored?.auto === true) (view as { auto?: boolean }).auto = true\n if (stored?.protocol !== undefined) (view as { protocol?: RouteProtocol }).protocol = stored.protocol\n // The cooldown memory rides the view even though no row paints\n // a badge from it any more: the routing pool is the state's\n // source of truth, and the field carries what it sees.\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 = routeEndpointsOf(document, 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 // An in-flight scope probe rides along, so an open panel can\n // follow the assignments the probe writes \u2014 the button starts\n // it, and the assignments are the only thing that shows up.\n const probing = keyProbeRuns.has(route)\n return {\n ok: true,\n route,\n entries,\n models: routeModels,\n ...(probing ? { probing: true } : {}),\n endpoints: {\n openai: endpoints?.openai ?? null,\n anthropic: endpoints?.anthropic ?? 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 let addedRef: string | 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 activeSeat = enabledNow()\n // The official create form has already stored its first key.\n // Reuse that exact value during draft drain instead of minting\n // a duplicate credential and losing the user's first-key label.\n if (activeSeat !== undefined && await resolveCredential(credentials, activeSeat) === value) {\n updateKeyIndex(document => withKeyEntry(document, route, activeSeat, alias), indexFile)\n refreshKeyScopes()\n releaseMutation?.()\n releaseMutation = undefined\n sendJson(res, 200, { ...await payload(), addedRef: activeSeat })\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 // A reference this route already lists may hold this very value\n // under a name the seat does not use. The create card is the\n // ordinary way there: the official form stores its key under the\n // profile's `apiKeyEnv`, then this drain adds the SAME secret\n // again, and without this check the second copy became a second\n // row with an identical mask \u2014 two keys that are one. Reusing the\n // holder keeps the list honest; the label the user typed rides\n // onto that row (it is the same secret, so it is the same key).\n // Only a reference whose readable value EQUALS the incoming one\n // qualifies; a store that cannot be read never matches.\n for (const ref of taken) {\n let held: string | undefined\n try {\n held = await resolveCredential(credentials, ref)\n } catch {\n continue\n }\n if (held !== value) continue\n // One write: an unlisted holder joins the list, a listed one\n // keeps its own scope and protocol pin (the label is the only\n // thing an add carries for it).\n updateKeyIndex(document => withKeyEntry(document, route, ref, alias), indexFile)\n // The profile may still name an empty reference (the shipped\n // patch's `apiKeyEnv`, or a seat that lost its value). The key\n // the user just added is this one, so it takes the seat;\n // otherwise the official card keeps warning about the old name\n // while a working key sits right below it.\n if (active !== ref) {\n let seatEmpty = false\n if (active !== undefined) {\n try {\n seatEmpty = holdsNothing((await credentialFacts(credentials, [active], CREDENTIAL_IPC_BUDGET_MS))[active])\n } catch {\n seatEmpty = false\n }\n }\n if (active === undefined || seatEmpty) {\n const failed = await setEnabledKey(ref)\n if (failed !== undefined) throw new Error(failed)\n }\n }\n refreshKeyScopes()\n releaseMutation?.()\n releaseMutation = undefined\n sendJson(res, 200, { ...await payload(), addedRef: ref })\n return\n }\n // A listed row the store positively holds NOTHING under is an\n // empty slot, not a taken name. Filling it keeps the reference\n // the profile \u2014 and any other computer that synced that\n // profile \u2014 already uses; minting `_3` beside an empty `_2` is\n // what made a re-fill after a sync drift away from the name the\n // seat resolves and leave a \"not stored\" row behind.\n //\n // The seat comes first (storing there needs no re-point at\n // all), then the remaining rows in the order the page shows\n // them. Only a store that answered \"nothing, and no value to\n // read\" qualifies \u2014 an unreadable store is unknown, and this\n // path must never overwrite a key it could not see. The\n // readable face gets the final word, because metadata can\n // outlive the value it describes.\n const listedRefs = keyEntriesOf(readKeyIndex(indexFile), route).map(entry => entry.ref)\n const slotCandidates = active !== undefined && listedRefs.includes(active)\n ? [active, ...listedRefs.filter(candidate => candidate !== active)]\n : listedRefs\n const slotFacts = slotCandidates.length > 0\n ? await credentialFacts(credentials, slotCandidates, CREDENTIAL_IPC_BUDGET_MS)\n : {}\n const emptySlot = slotCandidates.find(candidate => holdsNothing(slotFacts[candidate]))\n let created = emptySlot !== undefined\n && await resolveCredential(credentials, emptySlot) === undefined\n ? emptySlot\n : undefined\n if (created === undefined) {\n 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], CREDENTIAL_IPC_BUDGET_MS)\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 }\n // A profile can name a reference the store holds NOTHING under:\n // a shipped patch writes `apiKeyEnv: MAGPIE_GATEWAY_KEY` ahead of\n // any key, and the official card then warns that the variable is\n // missing. Such a route has no working key at all \u2014 the same\n // state as a profile naming no reference \u2014 so this add takes the\n // seat, or the warning would outlive the key that fixed it and\n // the adapter would keep resolving an empty name. Only a store\n // that POSITIVELY holds nothing hands the seat over: an\n // unreadable store is unknown, and re-pointing a working key on\n // a bad read is the one mistake this must not make.\n const seatBefore = active\n const seatIsEmpty = seatBefore !== undefined\n && seatBefore !== created\n && holdsNothing((await credentialFacts(credentials, [seatBefore], CREDENTIAL_IPC_BUDGET_MS))[seatBefore])\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, pendingMutations)\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 (seatBefore === undefined || seatIsEmpty) {\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, pendingMutations, CREDENTIAL_IPC_BUDGET_MS)\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 addedRef = created\n } else if (op === 'scope') {\n // Store the manual assignment from the provider's added models.\n // Omission clears it to catch-all; [] is an explicit empty\n // assignment. Anything else that is not an array \u2014 a comma\n // string above all \u2014 is refused: silently widening a narrowed\n // key to catch-all is the one direction a typo must not go.\n if (isRecord(body) && body['models'] !== undefined && !Array.isArray(body['models'])) {\n refuse('model assignments must be an array of model ids')\n return\n }\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 profile = providerProfileOf(entryOf()?.value, route)\n const declared = new Set(Array.isArray(profile?.['models'])\n ? profile['models'].filter(isRecord).map(model => model['id']) : [])\n if (scope?.some(id => !declared.has(id))) {\n refuse('model assignments must use models already added to this provider')\n return\n }\n const target = ref\n updateKeyIndex(\n document2 =>\n withKeyModels(\n hasKeyEntry(document2, route, target) ? document2 : withKeyEntry(document2, route, target),\n route, target, scope,\n ),\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 withKeyProtocol(\n hasKeyEntry(document2, route, target) ? document2 : withKeyEntry(document2, route, target),\n route, target, protocol,\n ),\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 and the Anthropic wire.\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 })\n : undefined\n updateKeyIndex(document => withRouteEndpoints(document, route, endpoints), indexFile)\n } else if (op === 'balance') {\n // The one URL a provider's balance is read from. It is display\n // only and independent of the protocol-family addresses: an\n // empty value clears it, and a route without one shows no\n // balance on the Models page.\n const endpoint = isRecord(body) && typeof body['endpoint'] === 'string'\n ? body['endpoint']\n : ''\n updateKeyIndex(document => withRouteBalance(document, route, endpoint), indexFile)\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, pendingMutations)\n if (refused !== undefined) {\n refuse(refused)\n return\n }\n forgetServes(route, ref)\n // A new value is a new upstream account: whatever the old one\n // refused says nothing about this one.\n keyRest.clear(restKeyOf(route, ref))\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], CREDENTIAL_IPC_BUDGET_MS))[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 forgetServes(route, ref)\n invalidateCredentialDisplay(credentials, ref)\n if (configured) {\n const refused = await forgetCredential(credentials, ref, pendingMutations, CREDENTIAL_IPC_BUDGET_MS)\n if (refused !== undefined) throw new Error(refused)\n }\n } catch (error) {\n const failures: string[] = []\n try {\n updateKeyIndex(current => {\n const original = Object.hasOwn(document.providers, route) ? document.providers[route] : undefined\n if (original !== undefined) return { ...current, providers: { ...current.providers, [route]: original } }\n const providers = { ...current.providers }\n delete providers[route]\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 === 'probe') {\n // The key panel's \u81EA\u52A8\u63A2\u6D4B button: ask every switched-on key of\n // a multi-key route what its own listing advertises, and write\n // what each key actually serves within the route's declared set\n // \u2014 a scope when it carries part of it, a switched-off row when\n // it carries none of it, nothing when it carries all of it. A\n // route with a single switched-on key has nothing to divide \u2014\n // one key serves whatever it serves \u2014 so the refusal says so\n // instead of running a sweep that can only confirm what the row\n // already reads.\n const listed = keyEntriesOf(readKeyIndex(indexFile), route)\n const seat = enabledNow()\n const distinct = new Set(listed.filter(entry => entry.disabled !== true).map(entry => entry.ref))\n if (seat !== undefined && !listed.some(entry => entry.ref === seat)) distinct.add(seat)\n if (distinct.size < 2) {\n refuse('a scope probe needs a second key; a single key serves whatever it serves')\n return\n }\n // Fire and forget: the probe answers through the list's\n // `probing` flag and the scope writes it lands, never through\n // this request, which returns as soon as the run is queued.\n void runKeyProbe(route)\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 or scoped just now would not sign a request until some\n // unrelated settings change happened to refresh it.\n refreshKeyScopes()\n if (['add', 'remove', 'value', 'protocol', 'endpoints', 'enable'].includes(op)) {\n invalidateListings(route)\n // A key edit is exactly the news a sweep exists to digest: a\n // new credential is a new upstream account, a fresh row has no\n // scope yet, and a row switched back on has to be asked again.\n scheduleKeyProbes(route)\n }\n // The transaction is committed. Slow display-only credential reads\n // must not hold the next unrelated mutation in the global queue.\n releaseMutation?.()\n releaseMutation = undefined\n const answer = await payload()\n sendJson(res, 200, addedRef === undefined ? answer : { ...answer, addedRef })\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 // One provider's balance, fetched from the URL that provider configured.\n //\n // The browser half cannot make this call itself: the balance API is a\n // third-party origin (CORS), and the request is signed with a stored key\n // that only the host can resolve. The URL itself is plugin state in the key\n // index (`balances`), written from the provider card's balance row. A route\n // with no URL answers `configured:false` \u2014 the Models page shows nothing in\n // that case \u2014 while a configured route that fails answers an error, so a\n // broken endpoint does not masquerade as \"not configured\".\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: BALANCE_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') {\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 if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a route is required' })\n return\n }\n let document: ReturnType<typeof readKeyIndex>\n try {\n document = readKeyIndex(keyIndexFilePath())\n } catch (error) {\n sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n return\n }\n const endpoint = routeBalanceOf(document, route)\n if (endpoint === undefined) {\n sendJson(res, 200, { ok: true, route, configured: false })\n return\n }\n let profile: Record<string, unknown> | undefined\n try {\n profile = providerProfileOf(piSection(true), route)\n } catch {\n sendJson(res, 502, { ok: false, configured: true, error: 'the llm-pi-ai settings could not be read' })\n return\n }\n if (profile === undefined) {\n sendJson(res, 400, {\n ok: false,\n configured: true,\n error: `no llm-pi-ai provider route \"${route}\"`,\n })\n return\n }\n // Only the FIRST key of the provider is asked for a balance.\n // Further keys may resolve to different upstream accounts, but the\n // row shows one amount per provider, so asking them would multiply\n // traffic for values nobody sees. A route whose key list is empty\n // falls back to the profile's seat (the only key it can have); a\n // route with no key at all still gets the call, because some\n // balance endpoints are public.\n const credentials = ctx.get('credentials') as CredentialsService | undefined\n const ref = keyEntriesOf(document, route)[0]?.ref ?? enabledRefOf(profile)\n let apiKey: string | undefined\n if (ref !== undefined) {\n try {\n apiKey = await resolveCredential(credentials, ref)\n } catch {\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: 'the credential store could not read the reference',\n })\n return\n }\n }\n try {\n const headers: Record<string, string> = { accept: 'application/json' }\n if (apiKey !== undefined) {\n // The upstream protocol family decides the header the provider\n // expects for an account-level call; the two are not combined,\n // so an endpoint that rejects the other family's header (or a\n // WAF that flags it) is not handed a credential it never asked\n // for. Redirects are refused for the same reason: the key must\n // only reach the authority the user typed.\n const api = typeof profile['api'] === 'string' ? profile['api'] : ''\n if (api === 'anthropic-messages') headers['x-api-key'] = apiKey\n else headers['authorization'] = `Bearer ${apiKey}`\n }\n const upstream = await headerOverlayBypass()(endpoint, {\n method: 'GET',\n headers,\n redirect: 'error',\n signal: AbortSignal.timeout(BALANCE_TIMEOUT_MS),\n })\n if (!upstream.ok) {\n const hint = upstream.status === 401 || upstream.status === 403 ? '; check the API key' : ''\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: `${displayUrl(endpoint)} answered ${upstream.status}${hint}`,\n })\n return\n }\n const text = await readBounded(upstream, endpoint)\n const reading = parseBalancePayload(text)\n if (reading === undefined) {\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: `${displayUrl(endpoint)} answered no recognisable balance`,\n })\n return\n }\n sendJson(res, 200, {\n ok: true,\n route,\n configured: true,\n amount: reading.amount,\n ...(reading.currency === undefined ? {} : { currency: reading.currency }),\n })\n } catch (error) {\n // undici's own failure texts quote the original URL verbatim;\n // strip credentials before the reason reaches the page.\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: `could not reach ${displayUrl(endpoint)}: ${redactUrlSecrets(error instanceof Error ? error.message : String(error))}`,\n })\n }\n },\n }),\n 'dsh-model-think-level: balance 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 UI-order document: the provider-row sequence and every provider's\n // model-row sequence the user set by dragging on the official Models page.\n //\n // The browser half keeps the live preference in localStorage \u2014 fast, and\n // shared across tabs through storage events \u2014 but localStorage does not\n // travel between machines, and the orderings are exactly what a user wants\n // everywhere. This route owns the synced copy (`ui-order.json` beside the\n // key index): the client pulls at boot and pushes every drag, arbitrated\n // last-writer-wins by the `savedAt` stamp each side carries; the host only\n // folds what arrives over what is stored, so a partial or buggy payload\n // cannot blank a good file. No secrets \u2014 provider routes and model ids\n // only \u2014 which is what makes the file safe to point a sync tool at.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: ORDER_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') {\n // An absent or malformed file is an EMPTY document, never an\n // error: the client decides whether to adopt or to seed it.\n sendJson(res, 200, { ok: true, data: readUiOrder(uiOrderFilePath()) })\n return\n }\n if (req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n // One document per deployment: a provider order plus every\n // provider's model order. 64KiB covers a hundred routes with\n // hundred-row model lists several times over.\n const body = await readJsonBody(req, 65_536)\n if (body === undefined) {\n sendJson(res, 400, { ok: false, error: 'the body is not a JSON document' })\n return\n }\n try {\n // Read-fold-write is synchronous (order-store is), so two\n // overlapping pushes cannot interleave the read-modify-write.\n // A payload no newer than the stored document is refused with\n // 409: it is a page that never saw the newer file, and letting it\n // win would roll the order and the switches back.\n const { document, stale } = commitUiOrderGuarded(body, Date.now())\n if (stale) {\n sendJson(res, 409, { ok: false, error: 'stale', data: document })\n return\n }\n sendJson(res, 200, { ok: true, data: document })\n } catch (error) {\n sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n }\n },\n }),\n 'dsh-model-think-level: ui-order 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 // The override map can carry credential headers the user configured\n // for a gateway (an `authorization`, an `x-api-key`); nothing this\n // answers may sit in a cache, and those values must not echo.\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 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 * Credential-shaped values are masked: this is a status report,\n * not the editor's data source (the editor reads the settings\n * document through its own face), so no consumer needs them. */\n overrides: index.overrides.map(entry => ({\n origin: entry.origin,\n route: entry.route,\n headers: maskSensitiveHeaders(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 * with credential-shaped values masked the same way. */\n headerConflicts: index.headerConflicts.map(conflict => ({\n ...conflict,\n values: sensitiveHeader(conflict.header)\n ? conflict.values.map(() => SENSITIVE_HEADER_MASK)\n : conflict.values,\n })),\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 // Model fingerprint attribution (ModelTrace). One path, three verbs: GET\n // reads the stored verdicts for a provider, POST runs one model's three\n // challenges and stores the verdict, DELETE forgets one model.\n //\n // The POST answers as NDJSON -- one `progress` line per finished challenge,\n // then one `result` line -- because the page shows `\u68C0\u6D4B\u4E2D \u00B7 n/3` and only\n // the host knows when a challenge lands. A proxy that buffers the whole\n // response degrades this safely: the progress lines just arrive late, the\n // page falls back to an indeterminate badge, and the final line is still\n // the truth. Raw answer text never leaves this process; only statistics\n // are stored (design \u00A74.2).\n //\n // Early exit rides on `runProbe.shouldStop` below: two confident answers\n // close the run before the slowest challenge lands, and the verdict is\n // graded on the bank's own 2-query calibration (verdict.ts).\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: FINGERPRINT_PATH,\n handler: async (req, res) => {\n // Verdicts are per-model state the page re-reads: nothing this\n // route answers belongs in a cache (the NDJSON POST branch used to\n // set this only for itself; GET/DELETE were cacheable).\n res.setHeader('cache-control', 'no-store')\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n const method = req.method ?? 'GET'\n if (method !== 'GET' && method !== 'POST' && method !== 'DELETE') {\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 if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a provider route is required' })\n return\n }\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 let bank: ReturnType<typeof loadBankSync>\n try {\n bank = loadBankSync()\n } catch (error) {\n sendJson(res, 500, {\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n })\n return\n }\n const file = fingerprintFilePath()\n const stamp = bankBuiltAt(bank)\n\n if (method === 'GET') {\n const document = readFingerprintStore(stamp, file)\n sendJson(res, 200, {\n ok: true,\n data: {\n bank: summarizeBank(bank),\n records: providerRecords(document, route),\n },\n })\n return\n }\n\n // Both writers go through one tail so two clicks cannot interleave a\n // read-modify-write on the same file. Reads stay unqueued.\n let releaseMutation: (() => void) | undefined\n const previous = fingerprintMutationTail\n fingerprintMutationTail = new Promise<void>(resolve => {\n releaseMutation = resolve\n })\n await previous\n try {\n if (method === 'DELETE') {\n const model = url.searchParams.get('model') ?? ''\n if (model.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a model id is required' })\n return\n }\n updateFingerprintStore(\n document => withoutRecord(document, route, model),\n stamp,\n file,\n )\n sendJson(res, 200, { ok: true })\n return\n }\n\n const body = await readJsonBody(req, 2048)\n const model = isRecord(body) && typeof body['model'] === 'string' ? body['model'] : ''\n if (model.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a model id is required' })\n return\n }\n // Eligibility is a page-level rule (design \u00A70.1): a model outside\n // the two families cannot produce a verdict this bank can express,\n // so the route refuses instead of spending three calls to say\n // \"failed\".\n if (!isEligibleModel(model)) {\n sendJson(res, 400, {\n ok: false,\n error: `model \"${model}\" is not a GPT or Claude model`,\n })\n return\n }\n\n const llm = (fingerprintDispatch ?? (ctx as unknown as { llm?: unknown }).llm) as\n | LlmDispatchLike\n | undefined\n if (llm === undefined || typeof llm.prepareCall !== 'function') {\n sendJson(res, 503, { ok: false, error: 'the llm service is unavailable' })\n return\n }\n\n res.statusCode = 200\n res.setHeader('content-type', 'application/x-ndjson; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n // Tell any reverse proxy in front of us not to sit on the lines.\n res.setHeader('x-accel-buffering', 'no')\n const emit = (line: Record<string, unknown>): void => {\n res.write(`${JSON.stringify(line)}\\n`)\n }\n\n const challenges = generateChallenges(3)\n const controller = new AbortController()\n res.on('close', () => {\n if (!res.writableEnded) controller.abort()\n })\n\n let run: ProbeRunResult\n try {\n run = await runProbe({\n provider: route,\n model,\n challenges,\n llm,\n signal: controller.signal,\n timeoutMs: FINGERPRINT_CHALLENGE_TIMEOUT_MS,\n onOutcome: outcome => {\n emit({\n type: 'progress',\n index: outcome.index,\n ok: outcome.ok,\n ...(outcome.error === undefined ? {} : { error: outcome.error }),\n })\n },\n // Early exit (design \u00A75.3): the bank's 2-query calibration\n // carries 99.7% cross-validated accuracy, so two confident\n // answers may close the run before the slowest challenge\n // lands. The gate is deliberately double: the POOLED pair\n // must clear the 2-query probability bar, AND each answer\n // on its own must name the same winner \u2014 two answers biting\n // different candidates must not fuse into a lucky spike.\n shouldStop: settled => {\n const accepted = settled.filter(outcome => outcome.ok)\n if (accepted.length < 2) return false\n try {\n const outputs = accepted.map(outcome => ({\n text: outcome.text,\n expected_count: outcome.expectedCount,\n }))\n const pooled = analyzeGlobalOutputs(outputs, bank)\n if (pooled.probability < EARLY_IDENTIFIED_PROBABILITY) return false\n const first = analyzeGlobalOutputs(outputs.slice(0, 1), bank)\n const second = analyzeGlobalOutputs(outputs.slice(1), bank)\n return first.prediction === second.prediction\n } catch {\n return false\n }\n },\n })\n } catch (error) {\n emit({\n type: 'error',\n error: error instanceof Error ? error.message : String(error),\n })\n res.end()\n return\n }\n\n let attribution: AttributionResult | null = null\n let failure: string | undefined\n try {\n attribution = analyzeGlobalOutputs(run.outputs, bank)\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error)\n }\n // `analyzeGlobalOutputs` throws only when nothing was accepted, so\n // the failure case is exactly \"no usable answer\". When every call\n // died before producing text, say what actually went wrong.\n const usedOutputs = attribution === null ? 0 : attribution.used_outputs\n const record: FingerprintRecord = {\n provider: route,\n model,\n status: statusOf(attribution, usedOutputs),\n checkedAt: Date.now(),\n usedOutputs,\n }\n // \u9010\u9898\u8BB0\u8D26\u5728\u4E24\u79CD\u7ED3\u5C40\u4E0B\u90FD\u5199\uFF1A\u4E09\u9898\u5168\u5E9F\u65F6\uFF0C\u300C\u662F\u54EA\u4E00\u9898\u6CA1\u7B54\u3001\u7B54\u56DE\u6765\n // \u591A\u5C11\u300D\u6B63\u662F\u7528\u6237\u63A5\u7740\u8981\u95EE\u7684\u90A3\u53E5\u3002\u5B83\u8BB0\u7684\u662F\u5C1D\u8BD5\uFF0C\u4E0D\u662F\u7ED3\u8BBA\uFF0C\u6240\u4EE5\u4E0D\n // \u8DDF\u7740 failed \u6E05\u7A7A\u3002\n record.challenges = fingerprintChallengesOf(run.outcomes, attribution)\n if (attribution === null) {\n const firstFailure = run.outcomes.find(outcome => !outcome.ok)\n record.error =\n run.outputs.length === 0 && firstFailure?.error !== undefined\n ? firstFailure.error\n : (failure ?? NO_USABLE_OUTPUT)\n } else {\n record.prediction = attribution.prediction\n record.predictionName = attribution.prediction_name\n record.probability = attribution.probability\n record.familyPrediction = attribution.family_prediction\n record.familyProbability = attribution.family_probability\n record.top = topEntriesOf(attribution.results, 3)\n record.calibration = {\n queries: attribution.calibration.queries,\n cvAccuracy: attribution.calibration.cv_accuracy,\n }\n const timing = fingerprintTimingOf(run.outcomes)\n if (timing !== undefined) record.timing = timing\n }\n\n updateFingerprintStore(\n document => withRecord(document, record),\n stamp,\n file,\n )\n emit({ type: 'result', record })\n res.end()\n } catch (error) {\n sendJson(res, 500, {\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n })\n } finally {\n releaseMutation?.()\n }\n },\n }),\n 'dsh-model-think-level: fingerprint route',\n )\n\n // Image-generation config: GET answers the derived list merged with the\n // stored overrides (re-syncing first, so the snapshot is never stale), POST\n // saves the defaults and the default model.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: IMAGE_CONFIG_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 if (req.method === 'GET') {\n // A GET re-syncs first (an expired snapshot must not be served as\n // fresh); a failed sync leaves the stored document, still useful.\n syncImageConfigNow()\n const config = readImageConfig()\n sendJson(res, 200, {\n ok: true,\n enabled: config.enabled,\n models: config.models,\n defaultModel: config.defaultModel,\n defaults: config.defaults,\n outputDir: config.outputDir,\n syncedAt: config.syncedAt,\n // The native tool's registration state: the pane's status card\n // and the client's keyed image card both read this name back.\n tool: {\n registered: imageToolState.name !== undefined,\n name: imageToolState.name ?? null,\n ...(imageToolState.error === undefined ? {} : { error: imageToolState.error }),\n },\n })\n return\n }\n const body = await readJsonBody(req, 65_536)\n if (!isRecord(body)) {\n sendJson(res, 400, { ok: false, error: 'a JSON body is required' })\n return\n }\n // Save: defaults, output dir, default model, per-model row overrides.\n try {\n updateImageConfig(document => {\n let next: ImageConfig = document\n // The service switch: off unregisters the tool and refuses\n // every generation entry, while the models and params stay put.\n if (typeof body['enabled'] === 'boolean') next = { ...next, enabled: body['enabled'] }\n if (typeof body['defaultModel'] === 'string' && body['defaultModel'].length > 0) {\n next = { ...next, defaultModel: body['defaultModel'] }\n }\n if (body['defaultModel'] === null) next = { ...next, defaultModel: null }\n if (typeof body['outputDir'] === 'string' && body['outputDir'].length > 0) {\n next = { ...next, outputDir: body['outputDir'] }\n }\n if (isRecord(body['defaults'])) {\n const raw = body['defaults']\n next = {\n ...next,\n defaults: {\n size: typeof raw['size'] === 'string' && raw['size'].length > 0 ? raw['size'] : next.defaults.size,\n quality: typeof raw['quality'] === 'string' && raw['quality'].length > 0 ? raw['quality'] : next.defaults.quality,\n n: typeof raw['n'] === 'number' && Number.isInteger(raw['n']) && raw['n'] >= 1 ? Math.min(raw['n'], 16) : next.defaults.n,\n timeoutMs: typeof raw['timeoutMs'] === 'number' && raw['timeoutMs'] >= 60_000\n ? Math.min(raw['timeoutMs'], 3_600_000)\n : next.defaults.timeoutMs,\n },\n }\n }\n // A `models` row in the body (older clients send per-row param\n // overrides) is accepted and ignored: those overrides were\n // removed with the pane's row controls, so the params row is\n // now the only place size/quality/n are picked.\n return next\n })\n syncImageConfigNow()\n // Make the registry follow the saved switch before answering, so\n // the pane's next read reports the truth the session already has.\n try {\n reconcileImageTool?.()\n } catch {\n // A registry hiccup is reported through tool.error on the GET.\n }\n sendJson(res, 200, { ok: true })\n } catch (error) {\n sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n }\n },\n }),\n 'dsh-model-think-level: image 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 reads one provider's balance.\n *\n * The URL itself is configured per route in the plugin's key index (the\n * `balances` map) and is queried host-side, because only the host can resolve\n * the route's stored API key for the upstream call and the page would otherwise\n * face CORS on a third-party balance API. The route answers\n * `{ok, configured:false}` when the provider has no balance endpoint at all, so\n * the browser half can tell \"not configured\" (show nothing) from \"configured but\n * unreadable\" (show nothing but keep the endpoint).\n */\nexport const BALANCE_PATH = '/dsh-model-think-level/balance'\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/**\n * Same-origin host route owning model fingerprint attribution (ModelTrace).\n *\n * Three verbs on one path: `GET` returns the stored records for one provider\n * plus the bank summary the page needs to label families; `POST` runs one\n * model's three challenges and stores the verdict; `DELETE` forgets one model.\n * The attribution itself is `src/fingerprint/`, a pure port of ModelTrace's\n * `fingerprint-core.js` over a vendored bank -- so this route only does the\n * plumbing: run challenges through the llm service, parse, store.\n */\nexport const FINGERPRINT_PATH = '/dsh-model-think-level/fingerprint'\n\n/**\n * Same-origin host route owning the UI-order document: the provider-row\n * sequence and every provider's model-row sequence the user set by dragging\n * on the official Models page. `GET` answers the stored document,\n * `POST` folds a (whole-state) payload over it \u2014 the synced copy the browser\n * half pulls at boot and pushes on every drag, so the orderings survive a\n * machine switch (see {@link ORDER_FILE}).\n */\nexport const ORDER_PATH = '/dsh-model-think-level/ui-order'\n\n/**\n * File name of the UI-order document inside the plugin's home dir. Holds no\n * secrets \u2014 provider routes and model ids only \u2014 which is what makes it safe\n * to carry through a sync mechanism.\n */\nexport const ORDER_FILE = 'ui-order.json'\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 marker declaring the row an IMAGE-GENERATION model (\u751F\u56FE).\n *\n * The chat wire's own `input` vocabulary (pi-ai's MODALITY_GATE) only knows\n * text/image \u2014 the request modalities a model ACCEPTS \u2014 and an image generator\n * is not a request-modality answer at all: it is a different kind of model that\n * the composer's model switcher must hide (its entries cannot serve a chat\n * turn), so it lives beside the declaration as its own marker. Schemastery\n * passes unknown model keys through, so the marker survives official-page saves\n * and restarts like the other three; absence means \"not an image generator\",\n * and `false`/absent are the same state.\n */\nexport const INPUT_IMAGE_GEN_MARKER = 'inputImageGen'\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/**\n * Same-origin host route owning the image-generation config surface: `GET`\n * answers the derived image-model list merged with the stored overrides,\n * `POST` saves default model / default params / output dir / per-model rows.\n * Backing file: `<DSH_HOME>/dsh-model-think-level/image.json` (see\n * {@link IMAGE_CONFIG_FILE}).\n */\nexport const IMAGE_CONFIG_PATH = '/dsh-model-think-level/image-config'\n\n/** File name of the image-generation config inside the plugin's home dir. */\nexport const IMAGE_CONFIG_FILE = 'image.json'\n\n/**\n * The patch-layer id the RETIRED image-MCP entry carried. No entry is written\n * any more \u2014 the native `generate_image` tool replaced the stdio server \u2014 but\n * the id and the marker below still matter: the boot-time migration\n * (`src/image/legacy-cleanup.ts`) recognizes and removes a leftover block, so\n * an upgraded profile stops spawning the now-missing `lib/image-mcp.mjs` and\n * stops exposing the duplicate `mcp__dsh-image__generate_image`.\n */\nexport const IMAGE_MCP_PATCH_ID = 'dsh-image-mcp'\n\n/**\n * Marker-block name the retired installer used inside `cordis.patch.yml`. The\n * begin/end comment lines are `# >>> <name>:begin` / `# <<< <name>:end`; the\n * legacy cleanup splices exactly that byte range, so third-party marker blocks\n * (the dsh-skill-mcp-panel precedent) survive untouched.\n */\nexport const IMAGE_MCP_PATCH_MARK = 'dsh-model-think-level:image-mcp'\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 user's model assignment. Absent means a catch-all; an empty array is a\n * concrete empty assignment. Nothing but the user's explicit choice may\n * change this field \u2014 except a scope the host's own post-save probe wrote\n * (marked by {@link KeyEntry.auto}, and re-written by that probe on every\n * later pass until the user claims the scope with a manual edit).\n */\n readonly models?: readonly string[]\n /**\n * Whether the model scope is the probe's assignment rather than the user's.\n * The host rewrites an auto scope whenever it re-probes the route; a manual\n * scope edit clears the mark, and a manually claimed scope is never touched\n * by the probe again. Absent means the scope (or the catch-all) is the\n * user's, or has never been assigned at all.\n */\n readonly auto?: boolean\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 route's default\n * 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. Only the\n * host-supported OpenAI and Anthropic protocols are offered.\n */\nexport type RouteProtocol =\n | 'openai-completions'\n | 'anthropic-messages'\n | 'openai-responses'\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]\n\n/** The endpoint families a protocol can draw its base URL from. */\nexport type EndpointFamily = 'openai' | 'anthropic'\n\n/** Every endpoint family, in the order address rows and pickers show them. */\nexport const ENDPOINT_FAMILIES: readonly EndpointFamily[] = ['openai', 'anthropic']\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 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}\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 * A stored probe-maintained mark, or undefined when the scope is not the\n * probe's. Only a literal `true` counts \u2014 the same rule as\n * {@link normalizeKeyDisabled} \u2014 so a hand-edited index file cannot half-claim\n * the mark, and an entry never carries a redundant `auto: false`.\n * @param value - whatever arrived (the probe's write, or a hand-edited file).\n * @returns `true` when the scope is the probe's assignment, else undefined.\n */\nexport function normalizeKeyAuto(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 and an Anthropic-family endpoint.\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}\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 } = {}\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 return out.openai === undefined && out.anthropic === undefined\n ? undefined\n : out\n}\n\n/**\n * A stored balance endpoint, or undefined when the value carries nothing usable.\n *\n * This is the one URL a provider may add beside its base addresses: the host\n * queries it (with that route's enabled key) and the Models page shows the\n * amount in front of the provider's enable switch. It is not a request endpoint\n * and never takes part in routing, so it is kept outside {@link RouteEndpoints}\n * \u2014 a route may configure a balance URL without configuring either family\n * address, and vice versa. Blank and non-http(s) values are dropped rather than\n * stored, so \"no balance endpoint\" stays distinguishable from an empty string.\n * @param value - whatever arrived (the card's balance field, or a hand-edited file).\n * @returns the trimmed URL, or undefined when there is none.\n */\nexport function normalizeBalanceEndpoint(value: unknown): string | undefined {\n return isEndpointUrl(value) ? value.trim() : undefined\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 * Writes also keep immutable, bounded metadata-only pre-write history. A\n * synchronous read-modify-write cannot interleave in one JS thread; a detected\n * stale snapshot is rejected, but other processes and external synchronizers\n * still need a coordinated write/merge protocol.\n *\n * @module dsh-model-think-level/key-index\n */\n\nimport { mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { randomUUID } from 'node:crypto'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport {\n normalizeBalanceEndpoint,\n normalizeKeyAlias,\n normalizeKeyAuto,\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 * being user-assigned is the default for scopes, so only a probe-maintained\n * scope carries `auto`.\n */\nfunction makeEntry(\n ref: string,\n alias: string | undefined,\n models: readonly string[] | undefined,\n protocol: RouteProtocol | undefined,\n disabled: boolean | undefined,\n auto: boolean | undefined,\n): KeyIndexEntry {\n const entry: {\n ref: string\n alias?: string\n models?: readonly string[]\n protocol?: RouteProtocol\n disabled?: boolean\n auto?: 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 if (auto === true) entry.auto = 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 * Route \u2192 the URL that answers that provider's remaining balance.\n *\n * A balance endpoint is display-only: requests never use it, so it lives\n * beside the key metadata rather than in the pi-ai profile. Absent (or a\n * route without an entry) means \"not configured\", which is what the Models\n * page reads to decide whether to show a balance at all.\n */\n readonly balances?: Record<string, string>\n}\n\n/** JSON dictionaries treat every route, including __proto__, as an own key. */\nfunction setOwnRouteValue<T>(map: Record<string, T>, route: string, value: T): void {\n Object.defineProperty(map, route, { value, enumerable: true, configurable: true, writable: true })\n}\n\n/** Missing route names must never resolve through Object.prototype. */\nfunction ownRouteValue<T>(map: Record<string, T> | undefined, route: string): T | undefined {\n return map !== undefined && Object.hasOwn(map, route) ? map[route] : undefined\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 const auto = normalizeKeyAuto(record['auto'])\n list.push(makeEntry(ref, alias, models, protocol, disabled, auto))\n }\n if (list.length > 0) setOwnRouteValue(out, route, list)\n }\n const endpoints = parseEndpoints(root['endpoints'])\n const balances = parseBalances(root['balances'])\n let document: KeyIndexDocument = { version: 1, providers: out }\n if (endpoints !== undefined) document = { ...document, endpoints }\n if (balances !== undefined) document = { ...document, balances }\n return document\n}\n\n/**\n * Read the per-route balance URLs, dropping unusable entries. Separate for the\n * same reason the endpoint map is: an older file that never carried balances\n * still parses, and one bad line costs only that route.\n * @param raw - the decoded `balances` member (or anything else).\n * @returns the cleaned map, or undefined when it holds nothing usable.\n */\nfunction parseBalances(raw: unknown): Record<string, string> | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const out: Record<string, string> = {}\n for (const [route, value] of Object.entries(raw as Record<string, unknown>)) {\n if (route.length === 0) continue\n const endpoint = normalizeBalanceEndpoint(value)\n if (endpoint !== undefined) setOwnRouteValue(out, route, endpoint)\n }\n return Object.keys(out).length === 0 ? undefined : out\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) setOwnRouteValue(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 let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n // The raw SyntaxError names neither the file nor the repair; every caller\n // surfaces this message verbatim, so it carries the essentials itself.\n throw new Error('the key index is malformed; repair it before changing keys')\n }\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/** Metadata-only, immutable pre-write snapshots; never credential values. */\nexport const KEY_INDEX_HISTORY_LIMIT = 64\n\n/** Directory beside the index, deliberately outside the synced config file. */\nexport function keyIndexHistoryPath(file: string = keyIndexFilePath()): string {\n return `${file}.history`\n}\n\n/** Keep a bounded history, without making a committed write fail on cleanup. */\nfunction trimKeyIndexHistory(file: string): void {\n try {\n const directory = keyIndexHistoryPath(file)\n const snapshots = readdirSync(directory, { withFileTypes: true })\n .filter(entry => entry.isFile() && /^\\d{13}-[0-9a-f-]{36}\\.json$/.test(entry.name))\n .map(entry => entry.name).sort()\n for (const name of snapshots.slice(0, Math.max(0, snapshots.length - KEY_INDEX_HISTORY_LIMIT))) {\n unlinkSync(join(directory, name))\n }\n } catch {\n // Retaining extra snapshots is safer than reporting a successful commit\n // as a failure (which could trigger credential compensation).\n }\n}\n\n/** Write atomically, only after preserving the previous metadata successfully. */\nexport function writeKeyIndex(document: KeyIndexDocument, file: string = keyIndexFilePath()): void {\n const text = `${JSON.stringify(document, null, 2)}\\n`\n let previous: string | undefined\n try {\n previous = readFileSync(file, 'utf8')\n } catch (error) {\n if (!(typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT')) throw error\n }\n if (previous === text) return\n mkdirSync(dirname(file), { recursive: true })\n if (previous !== undefined) {\n // Never wash a malformed existing file into a fresh valid document.\n readKeyIndex(file)\n const directory = keyIndexHistoryPath(file)\n mkdirSync(directory, { recursive: true, mode: 0o700 })\n writeFileSync(join(directory, `${Date.now()}-${randomUUID()}.json`), previous,\n { encoding: 'utf8', flag: 'wx', mode: 0o600 })\n // Backup errors intentionally stop the overwrite; the original stays put.\n }\n const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`\n try {\n writeFileSync(temporary, text, { encoding: 'utf8', flag: 'wx', mode: 0o600 })\n renameSync(temporary, file)\n } catch (error) {\n try {\n unlinkSync(temporary)\n } catch {\n // The temp file is best-effort cleanup; the write failure is the news.\n }\n throw error\n }\n if (previous !== undefined) trimKeyIndexHistory(file)\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 current = readKeyIndex(file)\n const next = mutate(current)\n // A pure transform may overlap a different process or a re-entrant writer.\n // Refuse a detected stale snapshot instead of silently deleting its changes.\n if (JSON.stringify(readKeyIndex(file)) !== JSON.stringify(current)) {\n throw new Error('the key index changed while updating; retry the operation')\n }\n writeKeyIndex(next, file)\n return next\n}\n\n/** One route's keys, or an empty list; inherited names are never entries. */\nexport function keyEntriesOf(document: KeyIndexDocument, route: string): readonly KeyIndexEntry[] {\n const entries = ownRouteValue(document.providers, route)\n return Array.isArray(entries) ? entries : []\n}\n\n/** One route's extra endpoints, without inherited prototype members. */\nexport function routeEndpointsOf(document: KeyIndexDocument, route: string): RouteEndpoints | undefined {\n return ownRouteValue(document.endpoints, route)\n}\n\n/** One route's balance URL, without inherited prototype members. */\nexport function routeBalanceOf(document: KeyIndexDocument, route: string): string | undefined {\n return ownRouteValue(document.balances, route)\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, 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 touches its scope, nor silently re-pins\n // its protocol, nor switches it back on. A probe-maintained scope stays\n // probe-maintained: the label is not a claim on it.\n const keptLabel = label === undefined ? existing?.alias : label\n list[index] = makeEntry(ref, keptLabel, existing?.models, existing?.protocol, existing?.disabled, existing?.auto)\n }\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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, list[index]?.auto)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(document) }\n}\n\n/**\n * Set (or clear) the user's model assignment. `undefined` means catch-all, and\n * an empty array remains a concrete empty assignment.\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 // A manual assignment is a claim: the user chose what this key serves, so\n // the probe's maintenance mark goes with it and the probe never rewrites\n // this scope again.\n list[index] = makeEntry(ref, list[index]?.alias, scope, list[index]?.protocol, list[index]?.disabled, undefined)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(document) }\n}\n\n/**\n * Write the probe's model assignment, marking it as maintained.\n *\n * This is the host's post-save probe speaking, not the user: the scope is\n * rewritten on every probe pass until a manual edit (via {@link withKeyModels})\n * claims it. `undefined` stores a marked catch-all \u2014 the probe found the key\n * serving every declared model, and the catch-all is both the honest reading\n * and the one that keeps serving models added later.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param models - the ids the probe observed within the route's declared set,\n * or undefined for a maintained catch-all.\n */\nexport function withKeyAutoScope(\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, true)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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, list[index]?.auto)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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, existing?.auto)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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 setOwnRouteValue(map, route, cleaned)\n const next: KeyIndexDocument = { version: 1, providers: document.providers, ...balancesOf(document) }\n return Object.keys(map).length === 0 ? next : { ...next, endpoints: map }\n}\n\n/**\n * Set (or clear) one route's balance endpoint.\n *\n * The URL is display-only and independent of the protocol-family addresses, so\n * it is stored in its own map: writing endpoints never clears a balance URL and\n * writing a balance URL never disturbs the routing addresses.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param endpoint - the URL to store, or undefined/blank to clear it.\n */\nexport function withRouteBalance(\n document: KeyIndexDocument,\n route: string,\n endpoint: string | undefined,\n): KeyIndexDocument {\n const map: Record<string, string> = { ...(document.balances ?? {}) }\n const cleaned = normalizeBalanceEndpoint(endpoint)\n if (cleaned === undefined) delete map[route]\n else setOwnRouteValue(map, route, cleaned)\n const next: KeyIndexDocument = { version: 1, providers: document.providers, ...endpointsOf(document) }\n return Object.keys(map).length === 0 ? next : { ...next, balances: map }\n}\n\n/**\n * Carry a document's existing balance map forward on a write that does not\n * touch it, exactly as {@link endpointsOf} does for the routing addresses.\n * @param document - the source document.\n * @returns `{ balances }` when one exists, else `{}` (spreads to nothing).\n */\nfunction balancesOf(document: KeyIndexDocument): { balances?: Record<string, string> } {\n return document.balances === undefined ? {} : { balances: document.balances }\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), ...balancesOf(document) }`\n * so the writers above never silently drop a route's endpoints or balance URL\n * 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 setOwnRouteValue(providers, route, list)\n return { version: 1, providers, ...endpointsOf(document), ...balancesOf(document) }\n}\n\n/**\n * Drop one route entirely: its key list, its extra endpoints and its balance\n * URL. This is what a provider's deletion from the settings document reads as\n * \u2014 {@link withoutKeyEntry} only empties a list the user cleaned key by key,\n * and it deliberately leaves the endpoint maps alone, so a provider removed\n * wholesale by the host would otherwise leave its addresses and balance URL\n * behind for ever.\n * @param document - the current document.\n * @param route - the provider route key.\n */\nexport function withoutRoute(document: KeyIndexDocument, route: string): KeyIndexDocument {\n const providers: Record<string, readonly KeyIndexEntry[]> = { ...document.providers }\n delete providers[route]\n const endpoints = document.endpoints === undefined ? undefined : { ...document.endpoints }\n if (endpoints !== undefined) delete endpoints[route]\n const balances = document.balances === undefined ? undefined : { ...document.balances }\n if (balances !== undefined) delete balances[route]\n let next: KeyIndexDocument = { version: 1, providers }\n if (endpoints !== undefined && Object.keys(endpoints).length > 0) next = { ...next, endpoints }\n if (balances !== undefined && Object.keys(balances).length > 0) next = { ...next, balances }\n return next\n}\n", "/**\n * A process-wide key-mutation queue, shared by all plugin instances and HMR\n * generations. Reference allocation, credential writes and compensation must\n * not interleave merely because two apply() calls have different closures.\n * This is not a cross-process lock; external writers still need reconciliation.\n */\nimport { resolve } from 'node:path'\nimport { keyIndexFilePath } from './key-index.js'\n\nconst KEY_MUTATION_QUEUES = Symbol.for('dsh-model-think-level.key-mutation-queues')\ntype QueueRegistry = typeof globalThis & {\n [KEY_MUTATION_QUEUES]?: Map<string, Promise<void>>\n}\nconst registry = globalThis as QueueRegistry\nconst queues = registry[KEY_MUTATION_QUEUES] ??= new Map<string, Promise<void>>()\n\n/** Acquire one index's mutation turn; release in finally, even on failures. */\nexport async function acquireKeyMutation(file: string = keyIndexFilePath()): Promise<() => void> {\n const absolute = resolve(file)\n const key = process.platform === 'win32' ? absolute.toLowerCase() : absolute\n const previous = queues.get(key) ?? Promise.resolve()\n let releaseTurn: () => void = () => {}\n const turn = new Promise<void>(done => { releaseTurn = done })\n queues.set(key, turn)\n await previous\n let released = false\n return () => {\n if (released) return\n released = true\n if (queues.get(key) === turn) queues.delete(key)\n releaseTurn()\n }\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 TWO different kinds of knowledge, which are never\n * mixed up:\n * - an ASSIGNMENT ({@link KeyCandidate.models}): the user's own scope. A scope\n * that lists the model can serve it; a scope that does not is an exact\n * denial; an UNSCOPED key is a catch-all that serves whatever is left\n * (the state before a key has been scoped, and the way a user says \"this\n * key takes whatever is left\");\n * - an OBSERVATION ({@link ServingKnowledge}): what each key's `/models`\n * listing advertised the last time it answered. Keys on one route can sit\n * in different upstream groups, so \"key B lists this model, key A does not\"\n * is a real fact about the pair \u2014 but only when a sibling DOES list it: a\n * failed listing is not an empty one, and a key nobody probed stays a\n * candidate. This is the case a per-key scope cannot express, because the\n * user never assigned anything and the first key is a catch-all.\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. A\n * failure that names THIS model ({@link classifyFailure}'s `unserved`) rests\n * only the (key, model) pair, so a key that carries one group's models and\n * not another's keeps serving the ones it does carry.\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\":\n * deliberately left as a catch-all. An array (possibly empty) is a concrete\n * 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 * 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/**\n * What the plugin has OBSERVED about one route's keys, as opposed to what the\n * user ASSIGNED in each key's `models`.\n *\n * A listing says what an account's upstream group actually carries; an\n * assignment says what the user ordered. They answer different questions, so\n * they travel separately: an assignment always wins, and an observation only\n * decides between keys the user left unscoped.\n */\nexport interface ServingKnowledge {\n /**\n * Each reference's last successful listing: the model ids that key's\n * `/models` answer advertised. A reference with NO entry never answered and\n * is therefore unknown \u2014 never \"serves nothing\", because a failed listing must\n * not be read as an empty one.\n */\n readonly listed: ReadonlyMap<string, readonly string[]>\n}\n\n/**\n * Whether `key` can serve `model`, per the assignment and observation rules.\n * @param key - the candidate, with its manual scope (if any).\n * @param model - the model id the request names, or undefined when unknown.\n * @param knowledge - what the route's keys were last observed serving.\n */\nexport function canServe(key: KeyCandidate, model: string | undefined, knowledge?: ServingKnowledge): 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 // The user's assignment is the authority: it excludes a model exactly the way\n // it includes one.\n if (models !== undefined) return models.includes(model)\n // An unscoped key is a catch-all until something observes otherwise.\n if (knowledge === undefined) return true\n const listed = knowledge.listed.get(key.ref)\n // Never probed: unknown, so it keeps the benefit of the doubt.\n if (listed === undefined) return true\n if (listed.includes(model)) return true\n // This key's listing does not name the model. That is only evidence of a\n // refusal when a SIBLING key's listing does name it: several keys of one route\n // can sit in different upstream groups, and \"key B carries it, key A does not\"\n // is exactly the pair this rule exists for. When nobody lists it, no\n // observation is decisive and the key stays a candidate.\n for (const [ref, other] of knowledge.listed) {\n if (ref !== key.ref && other.includes(model)) return false\n }\n return true\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, grouped into\n * four tiers: a key the user assigned this model to, then a key whose own\n * listing advertises it, then a key nothing is known about, then \u2014 last, when no\n * sibling lists it either \u2014 a key that was probed and does not carry it. When\n * the 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 * @param knowledge - what the route's keys were last observed serving.\n * @returns the ordered candidates to try.\n */\nexport function keysForModel(\n keys: readonly KeyCandidate[],\n model: string | undefined,\n knowledge?: ServingKnowledge,\n): KeyCandidate[] {\n if (model === undefined) return [...keys]\n const eligible = keys.filter(key => canServe(key, model, knowledge))\n if (eligible.length === 0) return [...keys]\n const rankOf = (key: KeyCandidate): number => {\n // An explicit assignment outranks an observation: honouring \"this model\n // belongs to that key\" is what makes the user's rule true on the wire.\n if (key.models !== undefined) return 0\n const listed = knowledge?.listed.get(key.ref)\n if (listed === undefined) return 2\n return listed.includes(model) ? 1 : 3\n }\n // A stable sort keeps the \"both can serve -> first key\" rule inside a tier.\n return [...eligible].sort((a, b) => rankOf(a) - rankOf(b))\n}\n\n/** The wire families: one body format and one endpoint shape each. */\nexport type WireFamily = 'anthropic' | 'openai'\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 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`)\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\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 (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 family has exactly one wire, so a key pinned to it needs no\n * 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 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 \u2014 but only when the key actually carries that family's\n * 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 : '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 bare\n * 400/404/422 is a request-shape problem that every key would answer identically,\n * so it is returned to the caller unchanged rather than multiplied across keys.\n *\n * The one exception is a 400/404/422 whose BODY names the model as unsupported:\n * that is not a request-shape problem at all but a fact about this key's upstream\n * group (a multi-account relay answers exactly this way for a model another\n * account carries), so it fails over like any other key-level refusal.\n * @param status - the response status code.\n * @param bodyText - the (bounded) response body, when the caller has read it.\n */\nexport function shouldFailover(status: number, bodyText = ''): boolean {\n if (classifyFailure(status, bodyText) === 'unserved') return true\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 bare 400 has no kind at all \u2014 and between \"this key\" and \"this key\n * for THIS model\", which is why `unserved` exists.\n */\nexport type FailureKind = 'auth' | 'rate' | 'quota' | 'server' | 'timeout' | 'refused' | 'unserved'\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 * Bodies that say \"this account does not carry this model\" rather than \"your\n * request is malformed\".\n *\n * A relay that fans one route out over several upstream accounts answers a model\n * only SOME accounts carry with a 404 whose text names the model (\"Model\n * \\\"x\\\" is not supported by any configured account in this group\") or a 400 with\n * `model_not_found`. Every key repeating that error is the bug this pattern\n * fixes: the model exists, the key's group just does not carry it, so the next\n * key must be tried. Deliberately anchored on model words \u2014 a bare 404 (\"404 page\n * not found\") is still a request-shape failure.\n */\nconst UNSERVED_FAILURE = new RegExp([\n 'model_not_found',\n 'model[_\\\\s-](?:not[_\\\\s-](?:found|supported|available|exist(?:s)?)|does\\\\s+not\\\\s+exist|is\\\\s+not\\\\s+(?:found|supported))',\n // The same sentence with the model id between the noun and the verdict:\n // `Model \"gpt-6.1-sol\" is not supported`, `model kimi-k2 not found`.\n 'model[\\\\s\\\\S]{0,80}?(?:not\\\\s+(?:supported|found|available|allowed)|does\\\\s+not\\\\s+exist)',\n '(?:invalid|unknown|unsupported|unrecognized|unrecognised|no\\\\s+such|invalid_request)[_\\\\s-]*model',\n 'not\\\\s+supported\\\\s+by\\\\s+(?:any|this)',\n 'no\\\\s+(?:available\\\\s+)?(?:channel|account)s?\\\\s+(?:for|to\\\\s+serve)',\n '\u6A21\u578B[^,\uFF0C\"\u300D]{0,24}?(?:\u4E0D\u5B58\u5728|\u4E0D\u5B58\u5728\u6216\u4E0D\u652F\u6301|\u4E0D\u652F\u6301|\u672A\u627E\u5230|\u65E0\u6743\u9650|\u4E0D\u53EF\u7528|\u65E0\u6548)',\n '\u4E0D\u652F\u6301[^,\uFF0C\"\u300D]{0,12}?\u6A21\u578B',\n '\u65E0\u53EF\u7528(?:\u6E20\u9053|\u8D26\u53F7|\u8D26\u6237)|\u5206\u7EC4(?:\u4E2D|\u5185)?[^,\uFF0C\"\u300D]{0,12}?(?:\u4E0D\u652F\u6301|\u65E0\u6B64|\u6CA1\u6709)',\n].join('|'), 'i')\n\n/** Bodies that announce an authentication problem rather than a model one. */\nconst AUTH_FAILURE = /invalid[_\\s-]*(?:api[_\\s-]*)?(?:key|token|secret)|unauthorized|authentication|api[_\\s-]*key[_\\s-]*(?:is[_\\s-]*)?(?:invalid|expired|revoked)|\u5BC6\u94A5|\u8BA4\u8BC1\u5931\u8D25/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) {\n if (QUOTA_FAILURE.test(bodyText)) return 'quota'\n // A stream that died with the provider's own \"no such model\" text is the\n // same pair-level refusal a 404 would have carried.\n return UNSERVED_FAILURE.test(bodyText) ? 'unserved' : 'refused'\n }\n if (status === 400 || status === 404 || status === 422) {\n return UNSERVED_FAILURE.test(bodyText) ? 'unserved' : undefined\n }\n if (status === 401 || status === 403) {\n // A relay can refuse a model it does not carry with a 403 as well; the\n // authentication wording, when present, still wins.\n if (UNSERVED_FAILURE.test(bodyText) && !AUTH_FAILURE.test(bodyText)) return 'unserved'\n return 'auth'\n }\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 // A group membership changes when the provider re-plans its accounts, not when\n // a request goes wrong: bench the pair for long enough to stop asking every\n // turn, short enough to pick the model back up after a server-side reshuffle.\n unserved: 10 * 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, plus\n * the model when the failure was about ONE model rather than the credential.\n *\n * A 401 or a 429 describes the credential and its account, so charging the same\n * key a known failure on every model of the route is exactly what a cooldown\n * exists to prevent. An `unserved` refusal is narrower: the account's group\n * carries some models and not others, so benching the whole key would throw away\n * the models it does carry. Those pass a `model` and get a pair-scoped entry.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param model - the model the refusal named, when the cooldown is pair-scoped.\n */\nexport function restKeyOf(route: string, ref: string, model?: string | undefined): string {\n const pair = `${route}\\u0000${ref}`\n return model === undefined || model.length === 0 ? pair : `${pair}\\u0000${model}`\n}\n\n/**\n * Whether a key should be deferred for this request: it may be benched as a\n * whole, or benched for this model alone.\n * @param store - the cooldown memory.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param model - the model this request names.\n * @param now - the clock.\n */\nexport function isRestingFor(\n store: RestStore,\n route: string,\n ref: string,\n model: string | undefined,\n now: number,\n): boolean {\n if (store.isResting(restKeyOf(route, ref), now)) return true\n return model !== undefined && store.isResting(restKeyOf(route, ref, model), now)\n}\n\n/**\n * Retire every cooldown a successful attempt disproves: the key works, and for\n * this model it works too.\n * @param store - the cooldown memory.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param model - the model that just answered.\n */\nexport function clearRest(store: RestStore, route: string, ref: string, model?: string | undefined): void {\n store.clear(restKeyOf(route, ref))\n if (model !== undefined) store.clear(restKeyOf(route, ref, model))\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 * Known credential header names, including legacy/profile-owned headers.\n * Recognizing `x-goog-api-key` here prevents stale credentials from leaking;\n * it does not enable a Google protocol. Used to overwrite the credential the\n * transport already set and remove it when re-signing 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 * What each key's own listing said it serves \u2014 the observed half of routing.\n *\n * A provider route fans one request shape out over several credentials, and a\n * relay may resolve each of them to a different upstream ACCOUNT with its own\n * catalogue: one key's group carries `gpt-6.1-sol`, another key's group does not\n * and answers \"Model ... is not supported by any configured account in this\n * group\". The plugin cannot derive that split from configuration \u2014 keys are\n * opaque references and the upstream group an account belongs to is declared\n * nowhere \u2014 so it records what it observed: every successful model listing per\n * key, with the moment it was taken.\n *\n * `canServe` and `keysForModel` read these observations as a preference and a\n * guardrail (see key-route-core.ts), never as an assertion: a list that could not\n * be read is UNKNOWN, not empty, and a model no key lists is still tried on\n * every key \u2014 the provider, not the plugin, has the last word.\n *\n * The document is derived, not authored: losing it costs a round of failed\n * requests until the next listing, never correctness. It is therefore parsed\n * leniently \u2014 a malformed entry is dropped instead of thrown over \u2014 unlike the\n * key index, which holds what the user wrote.\n *\n * @module dsh-model-think-level/key-serves\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { harnessHome } from './key-index.js'\n\n/** What one key's last successful listing advertised. */\nexport interface KeyServesEntry {\n /** Model ids, as the listing sent them, de-duplicated and in listing order. */\n readonly models: readonly string[]\n /** When that listing was read (epoch ms), so a client merge can tell ages apart. */\n readonly at: number\n}\n\n/** Every route's per-key observations. */\nexport interface KeyServesDocument {\n readonly version: 1\n readonly providers: Readonly<Record<string, Readonly<Record<string, KeyServesEntry>>>>\n}\n\n/**\n * The bound a single key's recorded catalogue may reach. A relay advertising\n * thousands of ids is a misconfiguration; keeping the first few hundred still\n * answers \"does this key serve the model\" without letting one document grow\n * without limit.\n */\nconst MODELS_PER_KEY = 512\n\n/** A fresh, empty document. */\nexport function emptyKeyServes(): KeyServesDocument {\n return { version: 1, providers: {} }\n}\n\n/** Absolute path of the observation document beside the key index. */\nexport function keyServesFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', 'key-serves.json')\n}\n\n/** One model id, cleaned to the shape a listing can carry. */\nfunction normalizeModelId(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const id = value.trim()\n return id.length === 0 ? undefined : id\n}\n\n/**\n * Parse an already-decoded document, dropping whatever does not fit. Never\n * throws: this file is a cache of observations, so a corrupt one is an empty one.\n * @param raw - the decoded JSON value (or anything else).\n * @returns a well-formed document.\n */\nexport function parseKeyServes(raw: unknown): KeyServesDocument {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return emptyKeyServes()\n const providers = (raw as Record<string, unknown>)['providers']\n if (typeof providers !== 'object' || providers === null || Array.isArray(providers)) return emptyKeyServes()\n const out: Record<string, Record<string, KeyServesEntry>> = {}\n for (const [route, keys] of Object.entries(providers as Record<string, unknown>)) {\n if (route.length === 0 || typeof keys !== 'object' || keys === null || Array.isArray(keys)) continue\n const list: Record<string, KeyServesEntry> = {}\n for (const [ref, entry] of Object.entries(keys as Record<string, unknown>)) {\n if (ref.length === 0 || typeof entry !== 'object' || entry === null || Array.isArray(entry)) continue\n const record = entry as Record<string, unknown>\n const models = Array.isArray(record['models'])\n ? [...new Set(record['models'].map(normalizeModelId).filter((id): id is string => id !== undefined))]\n : []\n const at = typeof record['at'] === 'number' && Number.isFinite(record['at']) ? record['at'] : 0\n if (models.length === 0) continue\n list[ref] = { models: models.slice(0, MODELS_PER_KEY), at }\n }\n if (Object.keys(list).length > 0) out[route] = list\n }\n return { version: 1, providers: out }\n}\n\n/**\n * Read the document. Never throws: an absent file and an unreadable one both\n * mean \"nothing observed yet\".\n * @param file - document path (tests pass a temp file).\n */\nexport function readKeyServes(file: string = keyServesFilePath()): KeyServesDocument {\n try {\n return parseKeyServes(JSON.parse(readFileSync(file, 'utf8')) as unknown)\n } catch {\n return emptyKeyServes()\n }\n}\n\n/** Write the document at one path, atomically. */\nexport function writeKeyServes(document: KeyServesDocument, file: string = keyServesFilePath()): 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/** What one key last advertised, or undefined when it was never listed. */\nexport function servesOf(\n document: KeyServesDocument,\n route: string,\n ref: string,\n): readonly string[] | undefined {\n return document.providers[route]?.[ref]?.models\n}\n\n/**\n * One route's observations, keyed by reference \u2014 the shape `canServe` reads.\n * @param document - the observation document.\n * @param route - the provider route.\n */\nexport function servesOfRoute(\n document: KeyServesDocument,\n route: string,\n): ReadonlyMap<string, readonly string[]> {\n const entries = document.providers[route] ?? {}\n return new Map(Object.entries(entries).map(([ref, entry]) => [ref, entry.models]))\n}\n\n/**\n * Record one key's listing, replacing whatever it said before. A key with an\n * empty catalogue is dropped from the document: an empty list would assert\n * \"serves nothing\", which is the reading this module exists to avoid.\n * @param document - the current document.\n * @param route - the provider route.\n * @param ref - the credential reference.\n * @param models - the listing's model ids.\n * @param at - when the listing was read (epoch ms).\n */\nexport function withServes(\n document: KeyServesDocument,\n route: string,\n ref: string,\n models: readonly string[],\n at: number,\n): KeyServesDocument {\n const ids = [...new Set(models.map(normalizeModelId).filter((id): id is string => id !== undefined))]\n .slice(0, MODELS_PER_KEY)\n const current = document.providers[route] ?? {}\n const next: Record<string, KeyServesEntry> = { ...current }\n if (ids.length === 0) delete next[ref]\n else next[ref] = { models: ids, at }\n return { version: 1, providers: { ...document.providers, [route]: next } }\n}\n\n/**\n * Forget one key's observations, for a key that was removed or re-pointed.\n * @param document - the current document.\n * @param route - the provider route.\n * @param ref - the credential reference.\n */\nexport function withoutServes(document: KeyServesDocument, route: string, ref: string): KeyServesDocument {\n const current = document.providers[route]\n if (current === undefined || current[ref] === undefined) return document\n const next = { ...current }\n delete next[ref]\n const providers = { ...document.providers }\n if (Object.keys(next).length === 0) delete providers[route]\n else providers[route] = next\n return { version: 1, providers }\n}\n", "/**\n * The UI-order document: the sequence the user set by dragging the provider\n * rows, and every provider's model-row sequence, mirrored host-side.\n *\n * The live preference lives in the browser half's localStorage\n * (provider-order.ts / model-order.ts) \u2014 fast, and shared across tabs through\n * storage events. localStorage does not travel, though, and the orderings are\n * exactly the kind of setting a user wants on every machine, so the document\n * is mirrored into `<DSH_HOME>/dsh-model-think-level/ui-order.json` beside the\n * key index: a file the user can carry through any sync mechanism. The client\n * is the only writer (it pulls at boot and pushes every drag, last-writer-wins\n * on the `savedAt` stamp); the host only reads, stores and serves it.\n *\n * The file holds no secrets \u2014 provider routes and model ids only \u2014 which is\n * what makes it safe to point a sync tool at. It is parsed leniently: an\n * unreadable or malformed document degrades to \"nothing stored\", never an\n * error, and a partial payload MERGES over what is already stored, so a\n * buggy writer cannot wipe a good file with an empty one. Every write is\n * atomic, like the key index's.\n *\n * @module dsh-model-think-level/order-store\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { harnessHome } from './key-index.js'\nimport { ORDER_FILE } from './constants.js'\n\n/** The whole synced ordering state, stamped by the writing client. */\nexport interface UiOrderDocument {\n readonly version: 1\n /**\n * Epoch ms of the writing client's last ORDER CHANGE \u2014 set by the browser\n * at change time, not by the host at write time, so machines can arbitrate\n * which side is newer. Zero means \"unstamped\" (a hand-made file).\n */\n readonly savedAt: number\n /** The dragged provider-row sequence, first row first. */\n readonly providerOrder: readonly string[]\n /** Every provider's dragged model-row sequence, keyed by provider id. */\n readonly modelOrder: Readonly<Record<string, readonly string[]>>\n /**\n * The provider ids switched OFF on the Models page. The DISABLED set, not\n * the enabled one \u2014 an empty list means \"everything is on\", which is a real\n * state a machine can hold and another machine must be able to adopt, not\n * the absence of an opinion.\n */\n readonly providersDisabled: readonly string[]\n}\n\n/** A fresh, empty document. */\nexport function emptyUiOrder(): UiOrderDocument {\n return { version: 1, savedAt: 0, providerOrder: [], modelOrder: {}, providersDisabled: [] }\n}\n\n/** Absolute path of the document beside the key index. */\nexport function uiOrderFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', ORDER_FILE)\n}\n\n/** One id, cleaned to the shape an order can carry. */\nfunction normalizeId(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const id = value.trim()\n return id.length === 0 ? undefined : id\n}\n\n/** An id sequence, de-duplicated keeping the first occurrence's position. */\nfunction normalizeIds(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n return [...new Set(value.map(normalizeId).filter((id): id is string => id !== undefined))]\n}\n\n/**\n * Parse an already-decoded payload, dropping whatever does not fit. Never\n * throws: this file is a UI preference, so a corrupt one is an empty one.\n * @param raw - the decoded JSON value (or anything else).\n */\nexport function parseUiOrder(raw: unknown): UiOrderDocument {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return emptyUiOrder()\n const record = raw as Record<string, unknown>\n const savedAt = typeof record['savedAt'] === 'number' && Number.isFinite(record['savedAt'])\n ? record['savedAt']\n : 0\n const rawProviders = record['providerOrder']\n const rawModels = record['modelOrder']\n const modelOrder: Record<string, readonly string[]> = {}\n if (typeof rawModels === 'object' && rawModels !== null && !Array.isArray(rawModels)) {\n for (const [provider, value] of Object.entries(rawModels as Record<string, unknown>)) {\n if (provider.length === 0) continue\n const ids = normalizeIds(value)\n // An entry with no nameable model left is not an order: keeping it would\n // pin the provider's rows to slots they can no longer hold.\n if (ids.length > 0) modelOrder[provider] = ids\n }\n }\n return {\n version: 1,\n savedAt,\n providerOrder: normalizeIds(rawProviders),\n modelOrder,\n providersDisabled: normalizeIds(record['providersDisabled']),\n }\n}\n\n/**\n * Fold a (possibly partial) payload over a current document: a field the\n * payload carries in a usable shape replaces the stored one, every other\n * field keeps the stored value. A writer that can only name what it knows \u2014\n * or a corrupted body \u2014 therefore can never blank a good file.\n * @param current - the stored document.\n * @param patch - the incoming payload, as posted by the client.\n * @param at - the savedAt to stamp when the payload carries no usable one.\n */\nexport function mergeUiOrder(current: UiOrderDocument, patch: unknown, at: number): UiOrderDocument {\n if (typeof patch !== 'object' || patch === null || Array.isArray(patch)) return current\n const record = patch as Record<string, unknown>\n const providers = record['providerOrder']\n const models = record['modelOrder']\n const disabled = record['providersDisabled']\n const savedAt = typeof record['savedAt'] === 'number' && Number.isFinite(record['savedAt'])\n ? record['savedAt']\n : at\n const parsedModels = parseUiOrder({\n version: 1,\n savedAt,\n providerOrder: Array.isArray(providers) ? providers : current.providerOrder,\n modelOrder: typeof models === 'object' && models !== null && !Array.isArray(models) ? models : current.modelOrder,\n // An absent field keeps the stored set; an explicit empty ARRAY is a real\n // \"everything is on\" and replaces it.\n providersDisabled: Array.isArray(disabled) ? disabled : current.providersDisabled,\n })\n return parsedModels\n}\n\n/**\n * Read the document. Never throws: an absent file and an unreadable one both\n * mean \"nothing stored yet\" \u2014 the client decides whether to adopt or to seed.\n * @param file - document path (tests pass a temp file).\n */\nexport function readUiOrder(file: string = uiOrderFilePath()): UiOrderDocument {\n try {\n return parseUiOrder(JSON.parse(readFileSync(file, 'utf8')) as unknown)\n } catch {\n return emptyUiOrder()\n }\n}\n\n/** Write the document at one path, atomically. */\nexport function writeUiOrder(document: UiOrderDocument, file: string = uiOrderFilePath()): 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/** The payload's own stamp, when it carries a usable one (0 and junk mean none). */\nfunction savedAtOf(patch: unknown): number | undefined {\n if (typeof patch !== 'object' || patch === null) return undefined\n const at = (patch as Record<string, unknown>)['savedAt']\n return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : undefined\n}\n\n/** Whether two documents say the same thing, their stamps aside. */\nexport function sameUiOrderContent(left: UiOrderDocument, right: UiOrderDocument): boolean {\n const shape = (document: UiOrderDocument): string => JSON.stringify([\n document.providerOrder,\n document.modelOrder,\n document.providersDisabled,\n ])\n return shape(left) === shape(right)\n}\n\n/**\n * Read, fold a payload over it, and write back \u2014 the POST route's whole body.\n * The read and the write bracket one synchronous section, so two overlapping\n * requests cannot interleave the read-modify-write.\n * @returns the document as it now stands on disk.\n */\nexport function commitUiOrder(patch: unknown, at: number, file: string = uiOrderFilePath()): UiOrderDocument {\n const next = mergeUiOrder(readUiOrder(file), patch, at)\n writeUiOrder(next, file)\n return next\n}\n\n/**\n * The guarded fold the route uses: a payload that is not NEWER than the stored\n * document may not rewrite it.\n *\n * `savedAt` is the arbitration every machine shares, so a push that carries an\n * older (or the same) stamp with different content is a page that never saw the\n * newer file \u2014 a second computer, or a tab whose boot answer arrived late. Letting\n * it write would flip the stored order and the switches back to what that page\n * still held, which is exactly how a disabled set \"un-syncs\" itself. The answer\n * tells the sender it lost, and carries the document that actually won so it can\n * adopt it instead of retrying.\n * @param patch - the posted payload.\n * @param at - the stamp to use when the payload carries none.\n * @param file - document path (tests pass a temp file).\n * @returns the stored document, and whether the payload was refused as stale.\n */\nexport function commitUiOrderGuarded(patch: unknown, at: number, file: string = uiOrderFilePath()): { document: UiOrderDocument, stale: boolean } {\n const current = readUiOrder(file)\n const incoming = savedAtOf(patch)\n const merged = mergeUiOrder(current, patch, at)\n if (incoming !== undefined && incoming <= current.savedAt) {\n // An old identical POST is an idempotent success, not permission to lower\n // savedAt: otherwise a later-arriving intermediate edit could win next.\n return { document: current, stale: !sameUiOrderContent(merged, current) }\n }\n const document = { ...merged, savedAt: Math.max(current.savedAt, merged.savedAt) }\n writeUiOrder(document, file)\n return { document, stale: false }\n}\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 fetch overlay and every\n * other catalogue reader 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 (the overlay's per-key probe). */\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 }\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 * 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 * Header names that must never ride a configured overlay onto the wire. Node's\n * `Headers` (unlike the browser) accepts these silently, and undici then fails\n * the whole request \u2014 a configured `transfer-encoding` kills every request the\n * route makes, and a mismatched `content-length` hangs it with no response and\n * no error. Refusing them at configuration time turns \"the route is down\" into\n * \"the header is ignored\".\n */\nconst WIRE_FORBIDDEN_HEADERS: ReadonlySet<string> = new Set([\n 'host',\n 'content-length',\n 'transfer-encoding',\n 'connection',\n 'te',\n 'trailer',\n 'upgrade',\n 'expect',\n 'keep-alive',\n 'proxy-connection',\n 'proxy-authenticate',\n 'proxy-authorization',\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 \u2014 except the wire-forbidden set\n * above, which `Headers.set()` (an editing API, not a wire validator) happily\n * accepts and the wire then chokes on.\n */\nexport function isSendableHeader(name: string, value: string): boolean {\n if (name.length === 0) return false\n if (WIRE_FORBIDDEN_HEADERS.has(name.toLowerCase())) 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, rawProfile] of Object.entries(providers)) {\n // A half-written settings document can park `null` on a provider slot;\n // one unguarded read here would throw through refreshHeaders into the\n // host's settings write path. Skip the slot, keep the plugin alive.\n if (!isRecord(rawProfile)) continue\n const profile: Record<string, unknown> = rawProfile\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 * 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'\nimport { isSendableHeader } from './headers-core.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 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). */\nexport const LISTABLE_PROTOCOLS: ReadonlySet<string> = new Set([\n 'anthropic-messages',\n 'openai-completions',\n 'openai-responses',\n])\n\n/**\n * A URL safe to echo in responses: a baseURL may carry userinfo\n * (https://user:pass@host) or a key in its query (?api_key=\u2026 \u2014 a common relay\n * spelling), and failure messages must never repeat either. The path is what\n * identifies the probe; credentials live in the userinfo and the query, both\n * of which are dropped, along with the fragment. A string that is not a\n * parseable URL is replaced with a placeholder \u2014 echoing the raw input back\n * would defeat the whole point (the opaque `user:pass@host` spelling parses\n * as a non-special scheme whose userinfo setters are no-ops).\n */\nexport function displayUrl(raw: string): string {\n try {\n const url = new URL(raw)\n url.username = ''\n url.password = ''\n url.search = ''\n url.hash = ''\n // A non-special scheme ('user:pass@host' parses as scheme 'user' with an\n // opaque path and NO host) keeps its credentials in the path text, where\n // the setters above are no-ops: refuse to echo such a string at all.\n if (!url.username && !url.password && url.host === '' && /^[^\\s@/]+:[^\\s@]+@/.test(raw)) {\n return '[unparseable URL]'\n }\n return url.toString()\n } catch {\n return '[unparseable URL]'\n }\n}\n\n/**\n * Redact credential-bearing URL shapes from free-form error text: any\n * `user:password@` authority (with or without a scheme \u2014 the opaque spelling\n * parses as scheme+path and survives URL-level stripping) loses its secret.\n * Applied to upstream error messages before they reach a response body, since\n * undici's own texts quote the original URL verbatim.\n */\nexport function redactUrlSecrets(text: string): string {\n return text.replace(\n /([a-z][a-z0-9+.-]*:\\/\\/)?([^\\s'\"@/]+):([^\\s'\"@]+)@/gi,\n (match, scheme: string | undefined) => (scheme === undefined ? '[redacted]@' : `${scheme}[redacted]@`),\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).\n */\nexport function 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/**\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 * 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 // The same wire-forbidden rule the header overlay applies: a configured\n // `transfer-encoding` must be dropped here too, or the probe dies on it.\n if (!isSendableHeader(name, value)) 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 */\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). 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 (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. */\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. */\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 * Shared facts and target derivation of per-key model probing.\n *\n * A key is not tied to one protocol: a route can answer on an OpenAI-family\n * address and an Anthropic-family one, and each key may\n * pin a protocol of its own. Asking every key against the route's default wire\n * would therefore ask half of them a question their credential cannot answer \u2014\n * an Anthropic-pinned key returns `401` from an OpenAI gateway. The probe\n * targets a key may be asked of are derived 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 \u2014 wherever a per-key listing is wanted, from\n * the fetch overlay that assembles a provider's catalogue to the post-save\n * probe that auto-checks each key's scope.\n *\n * The exact rules live on {@link listingTargetsOf}, the one derivation every\n * caller shares.\n *\n * @module dsh-model-think-level/key-probe\n */\n\nimport type { EndpointFamily, RouteEndpoints, RouteProtocol } from './key-refs.js'\nimport { endpointFamilyOf } from './key-refs.js'\nimport { LISTABLE_PROTOCOLS, 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}\n\n/** One address a key's listing may be asked on. */\nexport interface ProbeTarget {\n readonly api: RouteProtocol\n readonly baseURL: string\n}\n\n/**\n * What one key's probe learned, as the catalogue merge reads it.\n */\nexport interface KeyProbeResult {\n readonly ref: string\n /**\n * The key's scope: the union of every address that answered. Undefined when\n * no address answered \u2014 the caller must then keep the previous scope rather\n * than recording \"serves nothing\".\n */\n readonly models: string[] | undefined\n}\n\n/** The per-key probe facts a target derivation reads (the routing scope's shape). */\nexport interface ProbeKeyShape {\n /** The wire this key pins, when it pins one. */\n readonly protocol?: RouteProtocol\n /** The base URL a pinned key signs against (its family's address). */\n readonly endpoint?: string\n /** The family addresses an UNPINNED key may dispatch on. */\n readonly endpoints?: RouteEndpoints\n}\n\n/**\n * The addresses one key's listing may be asked on, deduplicated by listing URL.\n *\n * The rules mirror routing (key-route-core):\n * - a pin is honoured only through its own wire; its address is the family's\n * stored endpoint when the route configured one, the route's own URL\n * otherwise (a same-family pin rides the route's address \u2014 only the wire\n * changes, and the route's URL serves that family);\n * - an unpinned key is AUTOMATIC (the request speaks the model family's own\n * wire where the provider addressed it), so it is asked on the route's wire\n * plus every cross-family address the route configured \u2014 the only way to\n * learn that the key also reaches those families' models;\n * - targets whose listing this plugin cannot read, and addresses that are\n * empty, are dropped; a gateway that spells one listing under two protocols\n * is asked once.\n */\nexport function listingTargetsOf(\n key: ProbeKeyShape,\n routeAPI: RouteProtocol,\n routeBaseURL: string,\n): ProbeTarget[] {\n const wanted: ProbeTarget[] = key.protocol !== undefined\n ? [{ api: key.protocol, baseURL: key.endpoint ?? routeBaseURL }]\n : [\n { api: routeAPI, baseURL: routeBaseURL },\n ...Object.entries(key.endpoints ?? {})\n .filter(([family]) => family !== endpointFamilyOf(routeAPI))\n .map(([family, url]) => ({ api: FAMILY_PROTOCOL[family as EndpointFamily], baseURL: url ?? '' })),\n ]\n const asked = new Set<string>()\n const distinct: ProbeTarget[] = []\n for (const target of wanted) {\n if (!LISTABLE_PROTOCOLS.has(target.api) || target.baseURL.length === 0) continue\n const url = probeListingUrl(target.baseURL, target.api)\n if (asked.has(url)) continue\n asked.add(url)\n distinct.push(target)\n }\n return distinct\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 * 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 * The family is IMAGE GENERATION (\u751F\u56FE): these models produce images from\n * prompts and cannot serve a chat turn, so the composer's model switcher\n * hides them and the row editor's modality pills stand down to the single\n * \u751F\u56FE answer. Such an entry declares `efforts: false` (a generator takes no\n * reasoning_effort) and no `input` \u2014 the two chat-input answers would read\n * it back as a vision chat model.\n */\n imageGen?: true\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 /**\n * The listing's OUTPUT-modality disclosure, normalized to lowercase strings,\n * when it named one (OpenRouter's `architecture.output_modalities` and its\n * flattened copies). This is the disclosure that answers \"is this an image\n * generator\": a model whose listing says it outputs images and not text\n * cannot serve a chat turn.\n */\n output?: 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 /** Whether the model is an image generator (\u751F\u56FE), when derivable. */\n imageGen?: boolean\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 // ---- Image-generation families (\u751F\u56FE) -----------------------------------\n // These models produce images from prompts and cannot serve a chat turn, so\n // every entry declares `imageGen: true` with `efforts: false` and NO `input`:\n // the composer's switcher hides the row and the row editor's modality pills\n // stand down to the single \u751F\u56FE answer. A relay renaming them keeps matching\n // through the name heuristic below.\n {\n id: 'openai-gpt-image',\n // 'dalle' covers aggregator spellings that strip the hyphen.\n patterns: ['gpt-image', 'dall-e', 'dalle'],\n efforts: false,\n imageGen: true,\n note: 'OpenAI \u751F\u56FE\u7CFB\uFF08gpt-image-1 / DALL\u00B7E 3\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'google-imagen',\n // '-image' keys the Gemini-native image-output generations\n // (gemini-2.5-flash-image \"nano banana\", gemini-3-pro-image\u2026), whose ids\n // carry the word as its own token; 'imagen' keys the dedicated generator.\n patterns: ['imagen', 'flash-image', 'pro-image', 'nano-banana'],\n efforts: false,\n imageGen: true,\n note: 'Google \u751F\u56FE\u7CFB\uFF08Imagen / Gemini-Image \"nano banana\"\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'black-forest-flux',\n patterns: ['flux'],\n efforts: false,\n imageGen: true,\n note: 'FLUX \u7CFB\uFF08FLUX.1 schnell/dev/pro \u7B49\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'stability-sd',\n patterns: ['stable-diffusion', 'sdxl', 'sd3'],\n efforts: false,\n imageGen: true,\n note: 'Stability \u751F\u56FE\u7CFB\uFF08Stable Diffusion / SDXL / SD3\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'zhipu-cogview',\n patterns: ['cogview'],\n efforts: false,\n imageGen: true,\n note: '\u667A\u8C31 CogView \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'aliyun-wanx',\n patterns: ['wanx'],\n efforts: false,\n imageGen: true,\n note: '\u963F\u91CC\u4E07\u76F8 Wanx \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'bytedance-seedream',\n patterns: ['seedream', 'seededit'],\n efforts: false,\n imageGen: true,\n note: '\u5B57\u8282 Seedream / SeedEdit \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'qwen-image',\n // The generation line only: 'qwen-vl' stays with the vision entry above\n // (longest-hit keeps the strictly longer 'qwen-vl' ahead where both fire).\n patterns: ['qwen-image'],\n efforts: false,\n imageGen: true,\n note: '\u901A\u4E49\u5343\u95EE Qwen-Image \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'midjourney',\n patterns: ['midjourney', 'niji'],\n efforts: false,\n imageGen: true,\n note: 'Midjourney / Niji \u751F\u56FE\u7CFB\uFF08\u4E2D\u8F6C\u5E38\u89C1\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\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 *\n * A letter immediately followed by a generation digit also gains a space\n * ('qwen3' \u2192 'qwen 3'): both the haystack and the patterns go through this\n * same normalizer, so dotted spellings ('qwen3.8' \u2194 pattern 'qwen3.8') keep\n * matching while the previously-dead compact forms ('qwen3-max', 'glm4-plus',\n * 'gemini3-pro') now reach their family entries instead of falling to generic.\n */\nfunction normalizeLoose(value: string): string {\n return value\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, ' ')\n .replace(/([a-z])(\\d)/g, '$1 $2')\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 // Only the host-supported OpenAI/Anthropic protocols are inferred. Models\n // such as Gemini served through an OpenAI-compatible gateway keep that wire;\n // the plugin does not provide a native Gemini protocol.\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 RESPONSES_PROTOCOL = 'openai-responses'\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 // An IPv6 literal arrives bracketed from URL.hostname. Only loopback and\n // site-local/link-local scopes read as self-hosted; a public v6 address is\n // someone else's machine exactly as a public v4 would be.\n if (host.startsWith('[')) {\n const v6 = host.slice(1, -1)\n return v6 === '::1' || v6 === '::' || v6.startsWith('fe80:') || v6.startsWith('fc') || v6.startsWith('fd')\n }\n if (host === 'localhost' || 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 false\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/**\n * Compat switches the openai-completions gate offers and NO sibling wire\n * protocol takes (llm-pi-ai COMPLETIONS_COMPAT_GATE vs RESPONSES_COMPAT_GATE\n * and the anthropic gate). These are exactly the keys this plugin's knowledge\n * base and editors write, so a route switched off openai-completions leaves\n * them behind on its models -- and the kernel then refuses every model that\n * still carries one (\"sets compat ..., but its api is ..., which does not\n * take it\"), dropping it from the served catalog.\n */\nexport const COMPLETIONS_ONLY_COMPAT: readonly string[] = [\n 'supportsReasoningEffort',\n 'thinkingFormat',\n 'thinkingTokenBudgetField',\n 'supportsThinkingTokenBudget',\n 'vllmPriority',\n]\n\n/** The anthropic-messages gate's exclusive switch (see sanitizeCompatForProtocol). */\nexport const ANTHROPIC_ONLY_COMPAT: readonly string[] = ['forceAdaptiveThinking']\n\n/**\n * Drop the compat switches one STORED block carries that its route's wire\n * protocol does not take -- the repair for a protocol switched after the\n * switches were written: openai-completions \u2192 openai-responses leaves\n * `supportsReasoningEffort` behind, and the kernel then refuses the model at\n * catalog resolution. Returns the cleaned copy, or undefined when there is\n * nothing to drop (the common case, so a caller never writes speculatively).\n *\n * Deliberately a denylist of the keys this plugin writes, not an allowlist of\n * each gate: a hand-tuned key this plugin does not know stays exactly as\n * stored -- the same courtesy {@link sanitizeCompatForProtocol} extends to\n * suggestions. A protocol this module does not know strips nothing.\n */\nexport function stripForeignCompat(\n compat: Record<string, unknown>,\n api: string,\n): Record<string, unknown> | undefined {\n const norm = normalize(api)\n let foreign: readonly string[]\n if (norm === COMPAT_CAPABLE_PROTOCOL) foreign = ANTHROPIC_ONLY_COMPAT\n else if (norm === RESPONSES_PROTOCOL) foreign = [...COMPLETIONS_ONLY_COMPAT, ...ANTHROPIC_ONLY_COMPAT]\n else if (norm === ANTHROPIC_PROTOCOL) foreign = COMPLETIONS_ONLY_COMPAT\n else return undefined\n let stripped = false\n const copy: Record<string, unknown> = { ...compat }\n for (const key of foreign) {\n if (key in copy) {\n delete copy[key]\n stripped = true\n }\n }\n return stripped ? copy : undefined\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 // A budget field is a claim that the model consumes thinking tokens: an\n // entry that explicitly declares \"does not reason\" must never gain one,\n // whatever the endpoint shape suggests (the mistral-legacy / gpt-4o\n // self-hosted case).\n const reasoning = entry.efforts !== false\n if (compat === undefined) {\n return reasoning && isSelfHostedEndpoint(route.baseURL)\n ? { thinkingTokenBudgetField: 'thinking_token_budget' }\n : undefined\n }\n if (reasoning && 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 * Image-generation name tokens -- the last-resort tier for rows neither the\n * knowledge base nor the endpoint named: the vendor/generator tokens that\n * appear in image-generation ids. Boundary matching keeps 'flux' from hitting\n * 'afflux' and 'sd3' from hitting 'sd3x5-anything-else' spellings it should\n * still hit ('sd3.5' normalizes to 'sd3 5', where the boundary holds).\n */\nconst IMAGE_GEN_NAME_TOKENS: readonly string[] = [\n 'dall-e',\n 'dalle',\n 'gpt-image',\n 'imagen',\n 'flux',\n 'stable-diffusion',\n 'sdxl',\n 'sd3',\n 'cogview',\n 'wanx',\n 'seedream',\n 'seededit',\n 'midjourney',\n 'niji',\n 'nano-banana',\n 'image-gen',\n 'imagegen',\n 'qwen-image',\n 'grok-2-image',\n]\n\n/** Whether the id alone reads as an image generator (\u751F\u56FE) -- the lowest-confidence tier. */\nexport function inferImageGenFromName(modelId: string): boolean {\n const haystack = normalizeLoose(modelId)\n for (const token of IMAGE_GEN_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 true\n at = haystack.indexOf(needle, at + 1)\n }\n }\n return false\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 imageGen: boolean | undefined\n let contextWindow: number | undefined\n let maxTokens: number | undefined\n\n if (entry?.imageGen === true) imageGen = true\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. The\n // OUTPUT disclosure is the endpoint's word on \"is this an image generator\":\n // a listing that says the model outputs images and not text cannot serve a\n // chat turn, and one that names text output is a chat model even when a\n // relay renamed it into a generator-looking id.\n const listedInput = declaredCoreInput(endpoint?.input)\n if (listedInput !== undefined) {\n input = listedInput\n inputSource = 'endpoint'\n }\n const listedOutput = endpoint?.output\n if (listedOutput !== undefined) {\n imageGen = listedOutput.includes('image') && !listedOutput.includes('text')\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. The\n // image-generation guess stands beside it: an id that names a generator is\n // answered with the \u751F\u56FE marker instead of a vision-chat declaration.\n if (input === undefined) {\n const guessed = inferModalitiesFromName(modelId)\n if (guessed !== undefined) {\n input = guessed\n inputSource = 'heuristic'\n }\n }\n if (imageGen === undefined && inferImageGenFromName(modelId)) imageGen = true\n\n // The \u751F\u56FE answer replaces the chat-input declaration, whichever tier named\n // it: a request-modality array beside the marker would read the row back as\n // a vision chat model on every reader that ignores the marker.\n if (imageGen === true) {\n input = undefined\n inputSource = undefined\n }\n\n const modalityParts = {\n ...(input === undefined ? {} : { input }),\n ...(inputSource === undefined ? {} : { inputSource }),\n ...(imageGen === undefined ? {} : { imageGen }),\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 * Reading a provider's balance out of its balance endpoint's answer.\n *\n * Balance APIs are not standardised: a DeepSeek-compatible gateway answers\n * `balance_infos[].total_balance`, an OpenAI-compatible one usually carries\n * `total_available`, a Moonshot-style one nests `available_balance` under\n * `data`, and some return a bare number. The host therefore does not try to\n * understand a vendor: it walks the decoded JSON and picks the first value\n * whose FIELD reads like a balance, preferring the loudest spelling (`balance`)\n * over weaker synonyms (`remaining`, `credit`, `amount`) and shallower values\n * over deeper ones. A response with no recognisable field yields no reading, so\n * the page shows nothing rather than a made-up zero.\n *\n * This module is deliberately free of `node:` imports: the browser half uses\n * {@link formatBalance} to render the chip, and the host half uses\n * {@link parseBalancePayload} on the raw response. Pure functions only, so both\n * sides share one definition of \"a balance\".\n *\n * @module dsh-model-think-level/balance\n */\n\n/** A balance read from a provider endpoint. */\nexport interface BalanceReading {\n /** The amount itself, in the endpoint's own currency/unit. */\n readonly amount: number\n /** ISO code or symbol the endpoint named, when it named one. */\n readonly currency?: string\n}\n\n/**\n * Field names that mean \"balance\", strongest first. Keys are compared after\n * {@link normalizeKey}, so `total_balance`, `totalBalance` and `TOTAL-BALANCE`\n * all read as `totalbalance`.\n */\nconst BALANCE_KEYS: readonly string[] = [\n 'balance',\n 'totalbalance',\n 'availablebalance',\n 'remainingbalance',\n 'creditbalance',\n 'balanceusd',\n 'totalavailable',\n 'available',\n 'remaining',\n 'credits',\n 'credit',\n 'amount',\n 'left',\n 'remain',\n 'remainingquota',\n 'quotaremaining',\n 'remainquota',\n 'availablequota',\n 'points',\n]\n\n/** The rank of each accepted field name. Lower wins. */\nconst BALANCE_RANK = new Map(BALANCE_KEYS.map((key, index) => [key, index]))\n\n/**\n * Rank of the `total_credits - total_usage` fallback used by OpenRouter-style\n * credit APIs. It loses to every explicit balance field, wins over nothing.\n */\nconst CREDIT_PAIR_RANK = (BALANCE_RANK.get('totalavailable') ?? 0) + 0.5\n\n/** The two halves OpenRouter-style credit endpoints split a balance into. */\nconst TOTAL_CREDIT_KEYS: readonly string[] = ['totalcredits', 'totalgranted']\nconst USED_CREDIT_KEYS: readonly string[] = ['totalusage', 'totalused']\n\n/** Fields beside the amount that name its currency or unit. */\nconst CURRENCY_KEYS: readonly string[] = [\n 'currency',\n 'currencycode',\n 'currencyname',\n 'unit',\n 'unitname',\n 'symbol',\n]\n\n/** How deep and how wide a response is walked before it is given up on. */\nconst MAX_DEPTH = 8\nconst MAX_NODES = 2_000\n\n/** The largest response text worth decoding for a balance. */\nconst MAX_TEXT_LENGTH = 256_000\n\n/** A candidate value found by the walk. */\ninterface Candidate {\n readonly reading: BalanceReading\n readonly rank: number\n readonly depth: number\n readonly order: number\n}\n\n/** Fold a field name to its comparison form. */\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[\\s_-]+/g, '')\n}\n\n/**\n * Read a numeric amount out of a JSON value or a numeric string.\n *\n * Numbers must be finite; strings may carry thousands separators, a leading\n * currency symbol or a trailing currency code, but nothing else (an HTML page\n * or a date must not read as money). Anything longer than a short label is\n * refused rather than searched for a number.\n * @param value - a number or string from the response.\n * @returns the amount, or undefined when the value is not one.\n */\nfunction amountOf(value: unknown): number | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined\n if (typeof value !== 'string') return undefined\n const text = value.trim().replace(/,/g, '')\n if (text.length === 0 || text.length > 32) return undefined\n const match = /^[\\s$\u00A5\u20AC\u00A3\u20A9]*(-?\\d+(?:\\.\\d+)?)[\\sA-Za-z$\u00A5\u20AC\u00A3\u20A9]*$/.exec(text)\n if (match === null) return undefined\n const amount = Number(match[1])\n return Number.isFinite(amount) ? amount : undefined\n}\n\n/** The currency/unit a record names beside its amount, if any. */\nfunction currencyOf(record: Record<string, unknown>): string | undefined {\n for (const key of CURRENCY_KEYS) {\n const normalized = normalizeKey(key)\n for (const [field, value] of Object.entries(record)) {\n if (normalizeKey(field) !== normalized || typeof value !== 'string') continue\n const currency = value.trim()\n if (currency.length === 0 || currency.length > 16) continue\n // A three-letter ISO code is upper-cased so `usd` and `USD` render alike;\n // a symbol is kept verbatim.\n return /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : currency\n }\n }\n return undefined\n}\n\n/** One named numeric field of a record, or undefined when it holds none. */\nfunction numericField(record: Record<string, unknown>, names: readonly string[]): number | undefined {\n for (const [field, value] of Object.entries(record)) {\n if (!names.includes(normalizeKey(field))) continue\n const amount = amountOf(value)\n if (amount !== undefined) return amount\n }\n return undefined\n}\n\n/**\n * `total_credits - total_usage`, the shape OpenRouter-style credit APIs use\n * instead of a single remaining-balance field. Only answered when BOTH halves\n * are present, so half a pair never becomes money.\n */\nfunction creditPairOf(record: Record<string, unknown>): number | undefined {\n const total = numericField(record, TOTAL_CREDIT_KEYS)\n const used = numericField(record, USED_CREDIT_KEYS)\n if (total === undefined || used === undefined) return undefined\n return total - used\n}\n\n/** Walk one decoded value, collecting every balance-shaped field. */\nfunction collect(\n value: unknown,\n depth: number,\n out: Candidate[],\n budget: { nodes: number },\n order: { next: number },\n): void {\n if (depth > MAX_DEPTH || budget.nodes <= 0) return\n budget.nodes -= 1\n if (Array.isArray(value)) {\n for (const item of value) collect(item, depth + 1, out, budget, order)\n return\n }\n if (typeof value !== 'object' || value === null) return\n const record = value as Record<string, unknown>\n const currency = currencyOf(record)\n const pair = creditPairOf(record)\n if (pair !== undefined) {\n out.push({\n reading: currency === undefined ? { amount: pair } : { amount: pair, currency },\n rank: CREDIT_PAIR_RANK,\n depth,\n order: order.next++,\n })\n }\n for (const [key, entry] of Object.entries(record)) {\n const rank = BALANCE_RANK.get(normalizeKey(key))\n if (rank !== undefined) {\n const amount = amountOf(entry)\n if (amount !== undefined) {\n out.push({\n reading: currency === undefined ? { amount } : { amount, currency },\n rank,\n depth,\n order: order.next++,\n })\n // The value is the amount itself; there is nothing below it to read.\n continue\n }\n }\n collect(entry, depth + 1, out, budget, order)\n }\n}\n\n/**\n * Pick the most balance-shaped value out of a decoded response.\n * @param body - the decoded JSON value.\n * @returns the chosen reading, or undefined when no field was recognised.\n */\nfunction readingOf(body: unknown): BalanceReading | undefined {\n const out: Candidate[] = []\n collect(body, 0, out, { nodes: MAX_NODES }, { next: 0 })\n if (out.length === 0) return undefined\n // The field name outranks its depth: a shallow `total_available` is a\n // balance, while a deep `remaining` may belong to some unrelated sub-object.\n out.sort((a, b) => a.rank - b.rank || a.depth - b.depth || a.order - b.order)\n return out[0]?.reading\n}\n\n/**\n * Read one balance endpoint's raw response body.\n *\n * JSON is preferred; a body that is not JSON is accepted only when the whole\n * (trimmed) body is a number, which covers the plain-text balance endpoints.\n * @param text - the raw response body, as text.\n * @returns the reading, or undefined when nothing in it names a balance.\n */\nexport function parseBalancePayload(text: string): BalanceReading | undefined {\n const trimmed = text.trim()\n if (trimmed.length === 0 || trimmed.length > MAX_TEXT_LENGTH) return undefined\n let body: unknown\n try {\n body = JSON.parse(trimmed) as unknown\n } catch {\n const amount = amountOf(trimmed)\n return amount === undefined ? undefined : { amount }\n }\n if (typeof body === 'number') return Number.isFinite(body) ? { amount: body } : undefined\n if (typeof body === 'string') {\n const amount = amountOf(body)\n return amount === undefined ? undefined : { amount }\n }\n if (typeof body !== 'object' || body === null) return undefined\n return readingOf(body)\n}\n\n/** Currency symbols the chip can show in front of the number. */\nconst CURRENCY_SYMBOLS = new Map<string, string>([\n ['USD', '$'],\n ['US$', '$'],\n ['$', '$'],\n ['CNY', '\u00A5'],\n ['RMB', '\u00A5'],\n ['\u00A5', '\u00A5'],\n ['EUR', '\u20AC'],\n ['\u20AC', '\u20AC'],\n ['GBP', '\u00A3'],\n ['\u00A3', '\u00A3'],\n ['JPY', '\u00A5'],\n ['KRW', '\u20A9'],\n ['HKD', 'HK$'],\n ['TWD', 'NT$'],\n])\n\n/** Format an amount with at most two decimals, grouped by thousands. */\nfunction formatAmount(amount: number): string {\n const sign = amount < 0 ? '-' : ''\n const absolute = Math.abs(amount)\n const fixed = Number.isInteger(absolute)\n ? String(absolute)\n : absolute.toFixed(2).replace(/0+$/, '').replace(/\\.$/, '')\n const [whole = '0', fraction] = fixed.split('.')\n const grouped = whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return `${sign}${grouped}${fraction === undefined ? '' : `.${fraction}`}`\n}\n\n/**\n * Render a reading for the provider row: `$12.34` when the endpoint named a\n * currency the plugin knows, `12.34 USD` for other codes, and the bare number\n * when it named no currency at all.\n * @param reading - the parsed balance.\n * @returns the display text, never empty.\n */\nexport function formatBalance(reading: BalanceReading): string {\n const number = formatAmount(reading.amount)\n const currency = reading.currency?.trim() ?? ''\n if (currency.length === 0) return number\n const symbol = CURRENCY_SYMBOLS.get(currency.toUpperCase())\n if (symbol !== undefined) return `${symbol}${number}`\n return `${number} ${currency}`\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 clearRest,\n isRestingFor,\n keyRest,\n parseRetryAfter,\n restKeyOf,\n restLast,\n shouldFailover,\n WIRE_DISPATCH_HEADER,\n type FailureKind,\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/**\n * Registry key for the DISPATCH hooks: the seam that can answer a request\n * without sending it (the image-generation wire dispatch). Kept beside the\n * header registry, but deliberately separate \u2014 a dispatch hook must run for\n * every request regardless of which routes the header index matches, and its\n * lifecycle is independent of header entries.\n */\nconst DISPATCH_REGISTRY = Symbol.for('dsh-model-think-level.dispatch-overrides')\n\n/** What a dispatch hook is told about the request it may claim. */\nexport interface DispatchContext {\n /** The request URL, as resolved by the wrapper. */\n readonly url: string\n /** The request method, uppercased (GET when neither side named one). */\n readonly method: string\n /**\n * Lazily read the request body as text. Cached; a `Request` input is cloned\n * (the caller's stream survives), an `init.body` string is taken directly,\n * and any other shape yields undefined \u2014 the hook decides what \"unreadable\"\n * means (the image dispatch lets those through rather than mis-claiming).\n */\n readonly bodyText: () => Promise<string | undefined>\n /** The fetch beneath this wrapper, avoiding recursive interception. */\n readonly send: typeof globalThis.fetch\n}\n\n/** A dispatch candidate: return a Response to fully claim the request (it is never sent); undefined passes it through. */\nexport type DispatchHook = (context: DispatchContext) => Promise<Response | undefined>\n\n/** The process-wide dispatch hook list. */\ninterface DispatchRegistry {\n readonly hooks: DispatchHook[]\n}\n\nfunction dispatchRegistryOf(): DispatchRegistry {\n const holder = globalThis as unknown as Record<symbol, DispatchRegistry | undefined>\n let registry = holder[DISPATCH_REGISTRY]\n if (registry === undefined) {\n registry = { hooks: [] }\n holder[DISPATCH_REGISTRY] = registry\n }\n return registry\n}\n\n/**\n * Register one dispatch hook. Order is registration order; the FIRST hook to\n * return a Response claims the request. @returns the remover (idempotent).\n */\nexport function registerDispatchHook(hook: DispatchHook): () => void {\n const registry = dispatchRegistryOf()\n registry.hooks.push(hook)\n return () => {\n const at = registry.hooks.indexOf(hook)\n if (at !== -1) registry.hooks.splice(at, 1)\n }\n}\n\n/** How many dispatch hooks are live (diagnostics; 0 = the seam costs nothing). */\nexport function dispatchHookCount(): number {\n return dispatchRegistryOf().hooks.length\n}\n\n/** The caller's request method, the way Fetch resolves it. */\nfunction methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {\n if (init?.method !== undefined && init.method.length > 0) return init.method.toUpperCase()\n if (typeof Request !== 'undefined' && input instanceof Request) return input.method.toUpperCase()\n return 'GET'\n}\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 * 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\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/**\n * The caller's request as it should leave the wrapper when this layer does NOT\n * claim it: identical to what came in, except an internal wire-dispatch marker\n * (see WIRE_DISPATCH_HEADER) is stripped. The wire seam marks the requests it\n * has already signed \u2014 including ones this layer will never match (a key\n * endpoint on another origin than the route's base URL leaves the index\n * empty) \u2014 and a marker that survives a passthrough ships an internal\n * identifier upstream. Unmarked requests come back untouched, so the plain\n * passthrough keeps the caller's exact object identity.\n */\nfunction passthroughInit(input: RequestInfo | URL, init: RequestInit | undefined): RequestInit | undefined {\n if (init?.headers === undefined || init.headers === null) return init\n const headers = new Headers(init.headers as HeadersInit)\n if (headers.get(WIRE_DISPATCH_HEADER) !== '1') return init\n headers.delete(WIRE_DISPATCH_HEADER)\n return { ...init, 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, passthroughInit(input, init))\n // The dispatch seam runs BEFORE any header matching: a hook that claims\n // the request answers it without a send (the image-generation wire\n // dispatch is the user), so a claimed request never reaches the route\n // logic below. When no hook is registered this is one length check.\n const hooks = dispatchRegistryOf().hooks\n if (hooks.length > 0) {\n const context: DispatchContext = {\n url,\n method: methodOf(input, init),\n bodyText: () => bodyTextOf(input, init),\n send: base,\n }\n for (const hook of hooks) {\n let claimed: Response | undefined\n try {\n claimed = await hook(context)\n } catch {\n // A throwing hook must not take the request down: it simply does\n // not claim anything.\n claimed = undefined\n }\n if (claimed !== undefined) return claimed\n }\n }\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, passthroughInit(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, passthroughInit(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. The marker is\n // stripped from a COPY either way: a route that declares no headers of its\n // own (the common shape) has `hasPatch === false`, and returning the\n // original input/init here would ship the internal marker upstream.\n if (patched.get(WIRE_DISPATCH_HEADER) === '1') {\n patched.delete(WIRE_DISPATCH_HEADER)\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 // A key may be benched as a whole (auth, quota, a server fault) or for this\n // model alone (a group whose plan does not carry it); either defers it.\n candidate => isRestingFor(keyRest, override.route, candidate.ref, model, Date.now()),\n )\n\n const method = init?.method ?? (typeof Request !== 'undefined' && input instanceof Request ? input.method : undefined)\n const listingRequest = isModelListingRequest(url, method)\n if (listingRequest && keyed) {\n // The create/edit form may be trying a new key against an address an\n // existing route already uses. Its explicit signature belongs to this\n // listing; replacing it with saved keys would test the wrong credential.\n const supplied = seedHeaders(input, init)\n const authNames = ['authorization', 'x-api-key', 'x-goog-api-key'] as const\n const suppliedKeys = authNames.map(name => {\n const value = supplied.get(name)\n return name === 'authorization' ? value?.replace(/^Bearer\\s+/i, '').trim() : value?.trim()\n }).filter((value): value is string => value !== undefined && value.length > 0)\n if (suppliedKeys.some(value => !keyCandidates.some(candidate => candidate.value === value))) {\n for (const name of authNames) {\n const value = supplied.get(name)\n if (value === null) patched.delete(name)\n else patched.set(name, value)\n }\n return attempt(undefined)\n }\n }\n\n if (entry.modelListing !== undefined && listingRequest && 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, passthroughInit(input, init))\n\n /**\n * Read a failed attempt's body, bounded: enough to tell \"out of quota\" and\n * \"this account does not carry the model\" from \"too fast\". Best effort \u2014 a\n * body that cannot be read still leaves the status, which is the part that\n * matters.\n */\n const failureBody = async (response: Response): Promise<string> => {\n try {\n return await readBoundedText(response, 4096)\n } catch {\n return ''\n }\n }\n\n /**\n * Charge one rejected attempt to the key that placed it: the status, the\n * provider's `Retry-After` and the body decide how long it rests \u2014 and WHAT\n * rests. An `unserved` refusal names the model, so it benches the (key,\n * model) pair and leaves the key free for the models its group does carry; a\n * refusal whose model could not be read benches nothing, because the KEY is\n * not what is known to have failed.\n */\n const chargeFailure = (candidate: KeyCandidate, response: Response, kind: FailureKind | undefined): void => {\n if (kind === undefined) return\n if (kind === 'unserved' && model === undefined) return\n const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'), Date.now())\n const restKey = kind === 'unserved'\n ? restKeyOf(override.route, candidate.ref, model)\n : restKeyOf(override.route, candidate.ref)\n keyRest.note(restKey, kind, retryAfterMs === undefined ? undefined : { retryAfterMs })\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 (response.status < 400) {\n clearRest(keyRest, override.route, solo.ref, model)\n return response\n }\n const bodyText = await failureBody(response)\n if (shouldFailover(response.status, bodyText)) {\n chargeFailure(solo, response, classifyFailure(response.status, bodyText))\n } else {\n clearRest(keyRest, override.route, solo.ref, model)\n }\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 \u2014\n // UNLESS its body names the model, which makes it a fact about this key's\n // upstream group instead (see `shouldFailover`): a relay answering \"this\n // model is not supported by any configured account in this group\" for one\n // account must be asked of the next.\n let lastFailure: unknown\n let unserved = 0\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 (response.status < 400) {\n clearRest(keyRest, override.route, candidate.ref, model)\n return response\n }\n const bodyText = await failureBody(response)\n if (!shouldFailover(response.status, bodyText)) {\n clearRest(keyRest, override.route, candidate.ref, model)\n return response\n }\n const kind = classifyFailure(response.status, bodyText)\n if (kind === 'unserved') unserved += 1\n chargeFailure(candidate, response, kind)\n if (index === keyCandidates.length - 1) {\n // Every key refused the same model: the provider's own error is the\n // truth but not the whole story, so the answer names what the plugin\n // found (see `withUnservedNote`).\n return unserved === keyCandidates.length && model !== undefined\n ? await withUnservedNote(response, bodyText, model, unserved)\n : response\n }\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/** A plain JSON object, for reading an error envelope without a shape assumption. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * The sentence appended to a route-wide model refusal: the provider's own error\n * says which group refused it, this says what that means and what to do.\n * @param model - the model every key refused.\n * @param tried - how many keys were tried.\n */\nfunction unservedNote(model: string, tried: number): string {\n return ` [dsh-model-think-level: all ${tried} keys of this provider refused model \"${model}\" \u2014 `\n + 'none of their upstream groups carries it. Add a key whose group does, or assign the model '\n + 'to a key\\'s scope in the provider\\'s Keys panel.]'\n}\n\n/**\n * Append the unserved note to the first message field of a JSON error body.\n * @returns the rewritten payload, or undefined when the body has no field to\n * append to (a shape this module does not know stays untouched).\n */\nfunction noteInto(payload: unknown, note: string): Record<string, unknown> | undefined {\n if (!isPlainObject(payload)) return undefined\n const message = payload['message']\n if (typeof message === 'string' && message.length > 0) return { ...payload, message: `${message}${note}` }\n const error = payload['error']\n if (isPlainObject(error) && typeof error['message'] === 'string' && error['message'].length > 0) {\n return { ...payload, error: { ...error, message: `${error['message']}${note}` } }\n }\n if (typeof error === 'string' && error.length > 0) return { ...payload, error: `${error}${note}` }\n return undefined\n}\n\n/**\n * The final answer when every key of a route refused the same model: the\n * provider's error, plus one sentence naming the real cause.\n *\n * A relay that fans one route out over several upstream accounts answers \"this\n * model is not supported by any configured account in this group\" per ACCOUNT,\n * so the user reads a 404 that looks like a typo in the model id while the model\n * is simply on a group another key holds. Only a JSON error body with a message\n * field is rewritten; any other shape is returned exactly as the provider sent it.\n * @param response - the last attempt's response.\n * @param bodyText - its body, already read (bounded) by the caller.\n * @param model - the model every key refused.\n * @param tried - how many keys were tried.\n */\nasync function withUnservedNote(\n response: Response,\n bodyText: string,\n model: string,\n tried: number,\n): Promise<Response> {\n const text = bodyText.length > 0 ? bodyText : await response.text().catch(() => '')\n let payload: unknown\n try {\n payload = JSON.parse(text)\n } catch {\n return response\n }\n const patched = noteInto(payload, unservedNote(model, tried))\n if (patched === undefined) return response\n const headers = new Headers(response.headers)\n // The body is re-encoded: its old length and encoding no longer describe it.\n headers.delete('content-length')\n headers.delete('content-encoding')\n headers.set('content-type', 'application/json')\n return new Response(JSON.stringify(patched), {\n status: response.status,\n statusText: response.statusText,\n headers,\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 } from './listing.js'\nimport {\n classifyFailure,\n clearRest,\n isHonoured,\n isRestingFor,\n keyRest,\n planKeys,\n recordRoutePlan,\n restKeyOf,\n wireOf,\n WIRE_DISPATCH_HEADER,\n type FailureKind,\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 '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 : 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 => isRestingFor(keyRest, route ?? '', candidate.ref, modelId, 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 /**\n * The cooldown a failed attempt answers for. A refusal that names the\n * model is a fact about the (key, model) pair \u2014 a relay whose accounts\n * sit in different groups carries some models on one key and not the\n * other \u2014 so it benches only that pair; everything else (a bad\n * credential, a quota, a dead server) benches the key itself.\n */\n const restKeyFor = (candidate: KeyCandidate, kind: FailureKind): string =>\n kind === 'unserved' && modelId !== undefined\n ? restKeyOf(route ?? '', candidate.ref, modelId)\n : restKeyOf(route ?? '', candidate.ref)\n let lastErrorEvent: Record<string, unknown> | undefined\n let lastError: unknown\n for (const candidate of plan.ordered) {\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 const kind = classifyFailure(undefined, error instanceof Error ? error.message : '') ?? 'refused'\n keyRest.note(restKeyFor(candidate, kind), kind)\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 const kind = classifyFailure(undefined, errorTextOf(event as Record<string, unknown>)) ?? 'refused'\n keyRest.note(restKeyFor(candidate, kind), kind)\n break\n }\n committed = true\n clearRest(keyRest, route ?? '', candidate.ref, modelId)\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 image-generation config: `<DSH_HOME>/dsh-model-think-level/image.json`.\n *\n * The file holds no secrets \u2014 credential references only \u2014 which is what makes\n * it safe to keep in plain text and to hand to the MCP subprocess through one\n * `DSH_IMAGE_CONFIG` env var. Its `models[]` is a DERIVED SNAPSHOT: the source\n * of truth is the `llm-pi-ai` settings document's `inputImageGen` rows (the\n * same marker the Models page and the auto-fill write), and this file layers\n * the user's per-model overrides (endpoint verdict, param abilities, picked\n * size/quality/n) on top. Syncing keeps every override keyed by model id, so a\n * model that leaves the settings document drops out and one that comes back\n * keeps its overrides.\n *\n * Parsing follows `key-index.ts`: read-never-throw for absent files, defensive\n * field-by-field drops for malformed content, and an atomic temp-then-rename\n * write so a crash mid-write cannot leave a half-parsed config behind.\n *\n * @module dsh-model-think-level/image/config\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { IMAGE_CONFIG_FILE } from '../constants.js'\nimport { harnessHome } from '../key-index.js'\nimport { IMAGE_SIZE_TIERS } from './sizes.js'\n\n/** Endpoint verdict of one image model. `unverified` is the honest default. */\nexport type EndpointStatus = 'unverified' | 'ok' | 'unsupported'\n\n/** Wire shape the model row speaks. Only OpenAI-compatible images is wired up. */\nexport type ImageApi = 'images' | 'none'\n\n/** The conservative ability table every freshly derived row starts with. */\nexport interface ImageParams {\n readonly sizes: readonly string[]\n readonly qualities: readonly string[]\n readonly maxN: number\n /** How the endpoint wants its answer: b64 inline, an output_format field, or nothing. */\n readonly responseFormat: 'b64_json' | 'output_format' | 'none'\n}\n\n/** One derived model row, before user overrides. */\nexport interface ImageModelSeed {\n readonly id: string\n readonly route: string\n readonly modelId: string\n readonly label: string\n /** The route profile's `displayName` (the provider name the Models page\n * shows), when the profile has one; absent when the profile does not. */\n readonly providerLabel?: string\n readonly api: ImageApi\n readonly baseURL: string\n readonly keyRef?: string\n}\n\n/** One image model as the config stores it: derived facts + user overrides. */\nexport interface ImageModel {\n readonly id: string\n readonly route: string\n readonly modelId: string\n readonly label: string\n readonly providerLabel?: string\n readonly api: ImageApi\n readonly baseURL: string\n readonly keyRef?: string\n readonly endpoint: { readonly kind: 'images'; readonly status: EndpointStatus; readonly checkedAt: string | null }\n readonly params: ImageParams\n readonly lastGoodParams: ImageParams | null\n}\n\n/** The defaults every model row inherits when it does not override. */\nexport interface ImageDefaults {\n readonly size: string\n readonly quality: string\n readonly n: number\n readonly timeoutMs: number\n}\n\n/** The whole config document, exactly as it sits on disk. */\nexport interface ImageConfig {\n readonly version: 2\n /**\n * Whether the image-generation service is on. Off means the native tool is\n * not registered and every generation entry refuses; the models and image\n * params stay in the file untouched, so switching back on costs one click.\n */\n readonly enabled: boolean\n /** When `models[]` was last re-derived from the settings document. */\n readonly syncedAt: string\n /** `\"<route>/<modelId>\"` of the default model, when the user picked one. */\n readonly defaultModel: string | null\n readonly defaults: ImageDefaults\n readonly outputDir: string\n readonly models: readonly ImageModel[]\n}\n\n/** A mutable view of the config the writers build from. */\nexport type ImageConfigDraft = {\n -readonly [K in keyof ImageConfig]: ImageConfig[K]\n}\n\n/** Conservative defaults: nothing here assumes a capability the API may not have. */\nexport const IMAGE_FALLBACK_PARAMS: ImageParams = {\n sizes: IMAGE_SIZE_TIERS.map(tier => tier.value),\n qualities: ['low', 'medium', 'high', 'auto'],\n maxN: 4,\n responseFormat: 'b64_json',\n}\n\n/** Absolute path of the image config. */\nexport function imageConfigFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', IMAGE_CONFIG_FILE)\n}\n\n/** A fresh, empty config. */\nexport function emptyImageConfig(now: () => Date = () => new Date()): ImageConfig {\n return {\n version: 2,\n enabled: true,\n syncedAt: now().toISOString(),\n defaultModel: null,\n defaults: { size: '1024x1024', quality: 'high', n: 1, timeoutMs: 300_000 },\n outputDir: 'generated-images',\n models: [],\n }\n}\n\n/** Whether a value is a plain-ish object (not null, not an array). */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isSize(value: unknown): value is string {\n return typeof value === 'string' && /^\\d{2,5}x\\d{2,5}$/.test(value)\n}\n\nfunction stringList(value: unknown, limit = 32): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out = value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0).slice(0, limit)\n return out.length > 0 ? out : undefined\n}\n\nfunction parseParams(raw: unknown): ImageParams | undefined {\n if (!isRecord(raw)) return undefined\n const sizes = stringList(raw['sizes'])?.filter(isSize)\n const qualities = stringList(raw['qualities'])\n const maxN = typeof raw['maxN'] === 'number' && Number.isInteger(raw['maxN']) && raw['maxN'] >= 1\n ? Math.min(raw['maxN'], 16)\n : undefined\n const responseFormat = raw['responseFormat'] === 'output_format' || raw['responseFormat'] === 'none'\n ? raw['responseFormat']\n : raw['responseFormat'] === 'b64_json' ? 'b64_json' as const : undefined\n if (sizes === undefined && qualities === undefined && maxN === undefined && responseFormat === undefined) return undefined\n return {\n sizes: sizes ?? IMAGE_FALLBACK_PARAMS.sizes,\n qualities: qualities ?? IMAGE_FALLBACK_PARAMS.qualities,\n maxN: maxN ?? IMAGE_FALLBACK_PARAMS.maxN,\n responseFormat: responseFormat ?? IMAGE_FALLBACK_PARAMS.responseFormat,\n }\n}\n\n/**\n * Parse an already-decoded config document. Never throws and never trusts the\n * input: anything unrecognisable is dropped field by field, so a hand-edited\n * or truncated file costs at most the fields it got wrong. Overrides of model\n * rows this document does not know are kept \u2014 the next sync may re-derive them.\n */\nexport function parseImageConfig(raw: unknown, now: () => Date = () => new Date()): ImageConfig {\n const base = emptyImageConfig(now)\n if (!isRecord(raw)) return base\n const defaultsRaw = isRecord(raw['defaults']) ? raw['defaults'] : {}\n const defaults: ImageDefaults = {\n size: isSize(defaultsRaw['size']) ? defaultsRaw['size'] : base.defaults.size,\n quality: typeof defaultsRaw['quality'] === 'string' && defaultsRaw['quality'].length > 0\n ? defaultsRaw['quality']\n : base.defaults.quality,\n n: typeof defaultsRaw['n'] === 'number' && Number.isInteger(defaultsRaw['n']) && defaultsRaw['n'] >= 1\n ? Math.min(defaultsRaw['n'], 16)\n : base.defaults.n,\n timeoutMs: typeof defaultsRaw['timeoutMs'] === 'number' && defaultsRaw['timeoutMs'] >= 60_000\n ? Math.min(defaultsRaw['timeoutMs'], 3_600_000)\n : base.defaults.timeoutMs,\n }\n // A leftover `mcp` block from the retired stdio server is dropped by the\n // field-by-field parse: only known keys are read, so the stale state on\n // disk costs nothing and is rewritten away on the next save.\n const models: ImageModel[] = []\n const seen = new Set<string>()\n if (Array.isArray(raw['models'])) {\n for (const entry of raw['models']) {\n if (!isRecord(entry)) continue\n const model = parseImageModel(entry)\n if (model === undefined || seen.has(model.id)) continue\n seen.add(model.id)\n models.push(model)\n }\n }\n return {\n version: 2,\n // A config written before the switch existed has no opinion on it: the\n // shipped behaviour was \"on\", so only an explicit false turns it off.\n enabled: raw['enabled'] !== false,\n syncedAt: typeof raw['syncedAt'] === 'string' ? raw['syncedAt'] : base.syncedAt,\n defaultModel: typeof raw['defaultModel'] === 'string' && raw['defaultModel'].length > 0 ? raw['defaultModel'] : null,\n defaults,\n outputDir: typeof raw['outputDir'] === 'string' && raw['outputDir'].length > 0 ? raw['outputDir'] : base.outputDir,\n models,\n }\n}\n\nfunction parseImageModel(raw: Record<string, unknown>): ImageModel | undefined {\n const id = typeof raw['id'] === 'string' && raw['id'].length > 0 ? raw['id'] : undefined\n const route = typeof raw['route'] === 'string' && raw['route'].length > 0 ? raw['route'] : undefined\n const modelId = typeof raw['modelId'] === 'string' && raw['modelId'].length > 0 ? raw['modelId'] : undefined\n if (id === undefined || route === undefined || modelId === undefined) return undefined\n const api: ImageApi = raw['api'] === 'images' ? 'images' : 'none'\n const endpointRaw = isRecord(raw['endpoint']) ? raw['endpoint'] : {}\n const status: EndpointStatus = endpointRaw['status'] === 'ok' || endpointRaw['status'] === 'unsupported'\n ? endpointRaw['status']\n : 'unverified'\n const params = parseParams(raw['params']) ?? { ...IMAGE_FALLBACK_PARAMS }\n return {\n id,\n route,\n modelId,\n label: typeof raw['label'] === 'string' && raw['label'].length > 0 ? raw['label'] : modelId,\n ...(typeof raw['providerLabel'] === 'string' && raw['providerLabel'].length > 0 ? { providerLabel: raw['providerLabel'] } : {}),\n api,\n baseURL: typeof raw['baseURL'] === 'string' ? raw['baseURL'] : '',\n ...(typeof raw['keyRef'] === 'string' && raw['keyRef'].length > 0 ? { keyRef: raw['keyRef'] } : {}),\n endpoint: {\n kind: 'images',\n status,\n checkedAt: typeof endpointRaw['checkedAt'] === 'string' ? endpointRaw['checkedAt'] : null,\n },\n params,\n lastGoodParams: parseParams(raw['lastGoodParams']) ?? null,\n }\n}\n\n/** Read the config; an absent or unreadable file means a fresh, empty one. */\nexport function readImageConfig(file: string = imageConfigFilePath()): ImageConfig {\n let text: string\n try {\n text = readFileSync(file, 'utf8')\n } catch {\n return emptyImageConfig()\n }\n try {\n return parseImageConfig(JSON.parse(text) as unknown)\n } catch {\n // A corrupt file must not take the config surface down: start over (the\n // next sync rewrites the file with the derived snapshot).\n return emptyImageConfig()\n }\n}\n\n/** Write the config at one path, atomically (sibling temp file, then rename). */\nexport function writeImageConfig(document: ImageConfig, file: string = imageConfigFilePath()): 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 * Derive the image-model seeds from a resolved `llm-pi-ai` providers map: every\n * route's `models[]` row carrying `inputImageGen === true`, with the route's\n * api/baseURL/credential reference (and its displayName, the provider name the\n * list shows) attached. This is the SAME marker the Models\n * page editor and the auto-fill write, so both writers feed this list.\n *\n * A route whose protocol cannot carry an OpenAI-compatible images call still\n * lists its rows \u2014 marked `api: 'none'` so the UI can badge \"no compatible\n * endpoint\" and refuse generation.\n */\nexport function deriveImageSeeds(providers: Record<string, Record<string, unknown>>): ImageModelSeed[] {\n const seeds: ImageModelSeed[] = []\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile) || !Array.isArray(profile['models'])) continue\n const apiRaw = typeof profile['api'] === 'string' ? profile['api'] : ''\n // OpenAI-compatible wires can carry an images call on the same base URL;\n // Anthropic's cannot (its wire has no images endpoint at all).\n const api: ImageApi = apiRaw === 'openai-completions' || apiRaw === 'openai-responses' || apiRaw === 'openai' || apiRaw === ''\n ? 'images'\n : 'none'\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'].trim() : ''\n const keyRef = typeof profile['apiKeyEnv'] === 'string' && profile['apiKeyEnv'].length > 0 ? profile['apiKeyEnv'] : undefined\n const providerLabel = typeof profile['displayName'] === 'string' ? profile['displayName'].trim() : ''\n for (const row of profile['models']) {\n if (!isRecord(row) || row['inputImageGen'] !== true) continue\n const modelId = typeof row['id'] === 'string' ? row['id'].trim() : ''\n if (modelId.length === 0) continue\n const label = typeof row['name'] === 'string' && row['name'].trim().length > 0 ? row['name'].trim() : modelId\n const seed: ImageModelSeed = {\n id: `${route}/${modelId}`,\n route,\n modelId,\n label,\n api,\n baseURL,\n ...(providerLabel.length === 0 ? {} : { providerLabel }),\n ...(keyRef === undefined ? {} : { keyRef }),\n }\n if (!seeds.some(existing => existing.id === seed.id)) seeds.push(seed)\n }\n }\n return seeds\n}\n\n/**\n * Re-derive `models[]` from the settings document while keeping every stored\n * override keyed by model id. A derived row starts from the conservative\n * ability table; a stored row of the same id hands its overrides (endpoint\n * verdict, params, lastGoodParams) forward. Rows the settings document no\n * longer declares are dropped; defaultModel that points at a dropped model is\n * cleared.\n *\n * The old per-row size/quality/n picks are gone on purpose: the pane's params\n * row is the single place those are chosen, so a leftover pick from an older\n * build must not quietly outrank it. They are simply not carried forward.\n */\nexport function syncImageConfig(\n stored: ImageConfig,\n providers: Record<string, Record<string, unknown>>,\n now: () => Date = () => new Date(),\n): ImageConfig {\n const seeds = deriveImageSeeds(providers)\n const previous = new Map(stored.models.map(model => [model.id, model]))\n const models: ImageModel[] = seeds.map(seed => {\n const kept = previous.get(seed.id)\n const params = kept !== undefined ? kept.params : { ...IMAGE_FALLBACK_PARAMS }\n return {\n ...seed,\n endpoint: kept?.endpoint ?? { kind: 'images' as const, status: 'unverified' as const, checkedAt: null },\n params,\n lastGoodParams: kept?.lastGoodParams ?? null,\n }\n })\n const ids = new Set(models.map(model => model.id))\n // A pass that derives no row at all carries no evidence about which ids exist:\n // that is also what an empty providers map looks like before the settings\n // document is readable, and what the document looks like in the middle of a\n // rows rewrite. Clearing the picked default there is how a configured default\n // model disappears for good \u2014 the next pass re-derives the rows, but the pick\n // is already gone and nothing tells the user. Keeping it is safe: a default\n // that matches no row is never used to generate (resolveImageModel refuses it\n // and falls back to the sole candidate rule), so a stale pick cannot quietly\n // fire with some other model.\n const keepDefault = stored.defaultModel !== null\n && (models.length === 0 || ids.has(stored.defaultModel))\n return {\n ...stored,\n syncedAt: now().toISOString(),\n defaultModel: keepDefault ? stored.defaultModel : null,\n models,\n }\n}\n\n/**\n * Resolve the model a generation should use, per the design's priority:\n * an explicit pick (the dialog's current model, or a call's `model` argument)\n * wins; then the config's defaultModel; then the sole candidate when exactly\n * one exists. `undefined` when nothing resolves.\n */\nexport function resolveImageModel(\n config: ImageConfig,\n explicit?: string | undefined,\n): ImageModel | undefined {\n if (explicit !== undefined && explicit.length > 0) {\n const direct = config.models.find(model => model.id === explicit)\n if (direct !== undefined) return direct\n const byModelId = config.models.filter(model => model.modelId === explicit)\n if (byModelId.length === 1) return byModelId[0]\n const byLabel = config.models.filter(model => model.label === explicit)\n if (byLabel.length === 1) return byLabel[0]\n return undefined\n }\n if (config.defaultModel !== null) {\n const named = config.models.find(model => model.id === config.defaultModel)\n if (named !== undefined) return named\n }\n return config.models.length === 1 ? config.models[0] : undefined\n}\n\n/**\n * The params one generation uses: the call's explicit values win, then the\n * config defaults (the pane's params row). `n` is additionally clamped to the\n * model's ability table (a row that says maxN 2 never fires 8 requests).\n * `referenceImages` never comes from config \u2014 it is per-call.\n */\nexport function effectiveParams(\n config: ImageConfig,\n model: ImageModel | undefined,\n request: { size?: string; quality?: string; n?: number },\n): { size: string; quality: string; n: number } {\n const n = Math.max(1, Math.min(16, request.n ?? config.defaults.n))\n return {\n size: request.size ?? config.defaults.size,\n quality: request.quality ?? config.defaults.quality,\n n: model === undefined ? n : Math.min(n, model.params.maxN),\n }\n}\n\n/** One synchronous read-modify-write of the config file. */\nexport function updateImageConfig(\n mutate: (document: ImageConfig) => ImageConfig,\n file: string = imageConfigFilePath(),\n): ImageConfig {\n const next = mutate(readImageConfig(file))\n writeImageConfig(next, file)\n return next\n}\n", "/**\n * The image-size ladder the config pane shows: three friendly tiers over the\n * pixel values the endpoint actually receives.\n *\n * The wire stays pixel-based (`1024x1024` \u2026) \u2014 the tiers are presentation only,\n * so relaying the picked value needs no translation. Legacy sizes a config may\n * still hold (`1536x1024`, `512x512`) map to the nearest tier by longest edge;\n * ties keep the smaller tier so the UI never claims more pixels than stored.\n *\n * @module dsh-model-think-level/image/sizes\n */\n\n/** One size tier: the label the picker shows and the value the wire gets. */\nexport interface ImageSizeTier {\n readonly label: '1K' | '2K' | '4K'\n readonly value: string\n /** The longest edge in pixels; also the sort order of the ladder. */\n readonly edge: number\n}\n\n/** The ladder, smallest first. The values are the wire's `size` strings. */\nexport const IMAGE_SIZE_TIERS: readonly ImageSizeTier[] = [\n { label: '1K', value: '1024x1024', edge: 1024 },\n { label: '2K', value: '2048x2048', edge: 2048 },\n { label: '4K', value: '4096x4096', edge: 4096 },\n]\n\n/** The longest edge of a `WxH` size, or undefined for anything else. */\nexport function longestEdge(size: string): number | undefined {\n const match = /^(\\d{2,5})x(\\d{2,5})$/.exec(size.trim())\n if (match === null) return undefined\n return Math.max(Number(match[1]), Number(match[2]))\n}\n\n/** The tier a stored size maps to (unparsable sizes read as the smallest). */\nexport function tierOfSize(size: string): ImageSizeTier {\n const edge = longestEdge(size)\n let best = IMAGE_SIZE_TIERS[0]!\n if (edge === undefined) return best\n let bestDistance = Number.POSITIVE_INFINITY\n for (const tier of IMAGE_SIZE_TIERS) {\n const distance = Math.abs(tier.edge - edge)\n if (distance < bestDistance) {\n best = tier\n bestDistance = distance\n }\n }\n return best\n}\n\n/** The picker text for a stored size (`1536x1024` \u2192 `1K`). */\nexport function sizeLabel(size: string): string {\n return tierOfSize(size).label\n}\n\n/** The canonical wire value for a stored size (`1536x1024` \u2192 `1024x1024`). */\nexport function canonicalSize(size: string): string {\n return tierOfSize(size).value\n}\n", "/**\n * The image-generation core: ONE implementation of the OpenAI-compatible\n * images API call + disk write, behind three entries (the `generate_image`\n * native tool, the `/image-generate` route, the `/\u751F\u56FE` host command).\n * Anything about request construction, param fallback, sanitization or file\n * naming lives here and nowhere else.\n *\n * Endpoint choice: no reference images \u2192 `POST {baseURL}/images/generations`\n * (JSON); with reference images \u2192 `POST {baseURL}/images/edits` with a\n * hand-built multipart/form-data body (zero dependencies \u2014 the boundary is\n * constructed here, not by a library the bundle cannot carry).\n *\n * Failure taxonomy (v3): the GUI used to show an image-only key's `403\n * permission_denied` as \"API \u5BC6\u94A5\u65E0\u6548\" because the CHAT wire produced it. This\n * core never talks the chat wire, and its errors are classified \u2014 auth vs\n * image-endpoint-only permission vs missing endpoint vs param \u2014 so every entry\n * can show the operative sentence instead of the misleading one. Error text is\n * sanitized: the key value can never appear in a message, whatever shape the\n * upstream echoes back.\n *\n * @module dsh-model-think-level/image/generate\n */\n\nimport { mkdirSync, readFileSync, writeFileSync, existsSync, statSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { harnessHome } from '../key-index.js'\nimport { createImageDeadline, type ImageDeadline } from './deadline.js'\nimport {\n effectiveParams,\n readImageConfig,\n resolveImageModel,\n type ImageConfig,\n type ImageModel,\n} from './config.js'\n\n/** What a caller asks for. Everything but `prompt` is optional. */\nexport interface GenerateRequest {\n /** `\"<route>/<modelId>\"`, a bare modelId, or the label; default when omitted. */\n readonly model?: string\n readonly prompt: string\n /**\n * Caller cancellation is propagated to cooperative dependencies and bounds\n * local waiting even when they ignore it. Aborting HTTP is best effort: it\n * cannot guarantee that a remote paid job or an already-started save stops.\n */\n readonly signal?: AbortSignal\n readonly size?: string\n readonly quality?: string\n readonly n?: number\n /** Local file paths; any non-empty list switches to the edits endpoint. */\n readonly referenceImages?: readonly string[]\n /**\n * Reference images as already-decoded bytes \u2014 the attachment-backed channel:\n * the native tool resolves conversation image IDs through the attachment\n * store and hands the bytes over, so no temp file ever hits the disk. Any\n * entry here (alone or beside `referenceImages`) switches to the edits\n * endpoint.\n */\n readonly referenceFiles?: readonly {\n readonly name: string\n readonly mime: string\n readonly bytes: Uint8Array\n }[]\n /**\n * Where to land the file: a path ending in `.png` is honored EXACTLY (an\n * existing one gains a `-2` suffix \u2014 never overwritten), anything else is\n * created as a directory and receives the slug-timestamp naming. Absent\n * means the config's `outputDir`.\n */\n readonly outputPath?: string\n}\n\n/** One generated image: the b64 payload the wire returned + where it landed. */\nexport interface GeneratedImage {\n readonly filePath: string\n readonly data: string\n}\n\n/** What a successful generation reports. */\nexport interface GenerateResult {\n /**\n * Every image the wire returned, in order, each already written to disk.\n * The upstream is asked for `paramsUsed.n` images; a relay that answers\n * fewer yields fewer entries \u2014 the result never invents one.\n */\n readonly images: readonly GeneratedImage[]\n readonly mime: string\n readonly model: string\n /** The prompt this run answered (the reply's markdown alt text derives from it). */\n readonly prompt: string\n readonly paramsUsed: { readonly size: string; readonly quality: string; readonly n: number }\n /**\n * What the fallback chain had to change, in order \u2014 the \"\u56DE\u9000\u8BF4\u660E\" the reply\n * text carries. Empty when the first attempt went through untouched.\n */\n readonly revisions: readonly string[]\n}\n\n/** The classified failure `generateImage` throws (as `GenerateError`). */\nexport type GenerateFailureKind = 'config' | 'auth' | 'permission' | 'endpoint' | 'param' | 'reference' | 'upstream' | 'timeout' | 'aborted'\n\nexport class GenerateError extends Error {\n readonly kind: GenerateFailureKind\n readonly status?: number\n constructor(kind: GenerateFailureKind, message: string, status?: number) {\n super(message)\n this.name = 'GenerateError'\n this.kind = kind\n if (status !== undefined) this.status = status\n }\n}\n\n/** The faces this core needs from its host. All injectable for tests. */\nexport interface GenerateDeps {\n /** The live config; read fresh per call (the MCP path re-reads the file). */\n readonly config?: () => ImageConfig\n /** Resolve one credential reference to its value. */\n readonly resolveKey: (ref: string, signal?: AbortSignal) => Promise<string | undefined>\n /** The fetch beneath any wrapper \u2014 the images call must not be re-intercepted. */\n readonly send: typeof globalThis.fetch\n /** Base dir for relative `outputDir`s (defaults to the harness home). */\n readonly home?: () => string\n /** Persist `lastGoodParams` after a successful fallback (host: config file). */\n readonly persistLastGood?: (modelId: string, params: ImageModel['lastGoodParams']) => void\n /** Now, for file stamps (defaults to Date.now). */\n readonly now?: () => number\n /** Per-call timeout override (ms). */\n readonly timeoutMs?: number\n}\n\n/** Error classification patterns: what the fallback chain may still fix. */\nconst PARAM_ERROR_PATTERNS: readonly { readonly pattern: RegExp; readonly revision: string }[] = [\n { pattern: /response_format/i, revision: 'removed response_format' },\n { pattern: /output_format/i, revision: 'removed output_format' },\n { pattern: /\\bquality\\b/i, revision: 'lowered quality' },\n { pattern: /\\bsize\\b/i, revision: 'reset size to 1024x1024' },\n { pattern: /\\bn\\b|num_images|too many images/i, revision: 'set n to 1' },\n]\n\nconst QUALITY_LADDER: readonly string[] = ['high', 'medium', 'low']\n\n/** Strip the credential and other obvious secrets out of any error text. */\nfunction sanitize(text: string, key: string | undefined): string {\n let out = text\n if (key !== undefined && key.length >= 4) {\n // Length-independent: even a partial echo must not survive.\n out = out.split(key).join('***')\n out = out.split(encodeURIComponent(key)).join('***')\n const head = key.slice(0, 6)\n const tail = key.slice(-4)\n if (key.length > 12) out = out.split(`${head}...${tail}`).join('***')\n }\n // A bearer token pasted back by an echo, whatever it reads as.\n out = out.replace(/(?:Bearer\\s+|sk-)[A-Za-z0-9_\\-=.]{8,}/g, '***')\n return out\n}\n\n/** Read under the call's deadline, cancelling even a non-cooperative body. */\nasync function responseBytes(response: Response, deadline: ImageDeadline, limit = Infinity): Promise<Uint8Array> {\n deadline.check()\n const reader = response.body?.getReader()\n if (reader === undefined) return new Uint8Array()\n const chunks: Uint8Array[] = []\n let length = 0\n let complete = false\n try {\n while (length < limit) {\n const { done, value } = await deadline.run(() => reader.read())\n if (done) { complete = true; break }\n const chunk = value.subarray(0, limit - length)\n chunks.push(chunk)\n length += chunk.length\n }\n deadline.check()\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length }\n return bytes\n } finally {\n // Cleanup must not become another unbounded await. A rejected/late cancel\n // is consumed, and releaseLock rejects any still-pending read safely.\n if (!complete) void reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n}\n\n/** Only error snippets are bounded; successful JSON must never be truncated. */\nasync function boundedText(response: Response, deadline: ImageDeadline, limit = 4096): Promise<string> {\n try {\n return new TextDecoder().decode(await responseBytes(response, deadline, limit))\n } catch {\n deadline.check()\n return ''\n }\n}\n\n/** The upstream JSON envelope of an error, flattened to one sentence. */\nfunction upstreamMessage(body: unknown): string | undefined {\n if (typeof body === 'object' && body !== null) {\n const record = body as Record<string, unknown>\n const error = record['error']\n if (typeof error === 'string') return error\n if (typeof error === 'object' && error !== null && typeof (error as Record<string, unknown>)['message'] === 'string') {\n return (error as Record<string, unknown>)['message'] as string\n }\n if (typeof record['message'] === 'string') return record['message']\n }\n return undefined\n}\n\n/**\n * Classify one failed attempt. The 403 case is the user's actual incident: a\n * key restricted to a site's IMAGE endpoints must never read as \"invalid key\".\n * `text` arrives SANITIZED (the caller strips the credential before this sees\n * it) \u2014 every message built here flows into user-visible copy.\n */\nfunction classifyFailure(status: number, text: string): { kind: GenerateFailureKind; message: string } {\n if (status === 401 || /invalid[_\\s-]?api[_\\s-]?key/i.test(text) || /incorrect api key/i.test(text)) {\n return { kind: 'auth', message: '\u5BC6\u94A5\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF08upstream 401\uFF09' }\n }\n if (status === 403 || /permission_denied/i.test(text) || /\u4EC5\u5F00\u653E\u56FE\u7247\u63A5\u53E3/i.test(text) || /only (?:the )?image/i.test(text)) {\n return {\n kind: 'permission',\n message: '\u8BE5\u5BC6\u94A5\u88AB\u9650\u5236\u4E3A\u8BE5\u7AD9\u70B9\u7684\u56FE\u7247\u63A5\u53E3\u4E13\u7528\uFF0C\u4E0D\u80FD\u7528\u4E8E\u804A\u5929\u63A5\u53E3\u3002\u5DF2\u6539\u8D70 images \u63A5\u53E3\uFF1B\u5982\u4ECD\u5931\u8D25\uFF0C\u8BF7\u5230\u914D\u7F6E\u9875\u5BF9\u8BE5\u6A21\u578B\u6267\u884C\u300C\u6D4B\u8BD5\u300D\u3002',\n }\n }\n if (status === 404) {\n return { kind: 'endpoint', message: '\u8BE5\u4F9B\u5E94\u5546\u5730\u5740\u4E0A\u4E0D\u5B58\u5728 images \u7AEF\u70B9\uFF08404\uFF09\u2014\u2014\u8BF7\u5230\u914D\u7F6E\u9875\u786E\u8BA4\u8BE5\u6A21\u578B\u7684\u7AEF\u70B9\u7C7B\u578B' }\n }\n if (status === 429) {\n return { kind: 'upstream', message: '\u4E0A\u6E38\u9650\u6D41\uFF08429\uFF09\u2014\u2014\u8BF7\u7A0D\u540E\u91CD\u8BD5' }\n }\n if (status >= 400 && status < 500) {\n return { kind: 'param', message: text.trim().length > 0 ? text.trim().slice(0, 400) : `\u4E0A\u6E38\u62D2\u7EDD\u4E86\u8BF7\u6C42\uFF08${status}\uFF09` }\n }\n return { kind: 'upstream', message: text.trim().length > 0 ? text.trim().slice(0, 400) : `\u4E0A\u6E38\u9519\u8BEF\uFF08${status}\uFF09` }\n}\n\n/** Whether this 4xx names a param the fallback chain can drop or downgrade. */\nfunction fallbackRevisionFor(status: number, bodyText: string): string | undefined {\n if (status < 400 || status >= 500) return undefined\n for (const { pattern, revision } of PARAM_ERROR_PATTERNS) {\n if (pattern.test(bodyText)) return revision\n }\n return undefined\n}\n\n/** The multipart body of an /images/edits call, hand-built (zero deps). */\nexport function buildMultipart(\n boundary: string,\n fields: Readonly<Record<string, string>>,\n images: readonly { readonly name: string; readonly bytes: Uint8Array; readonly mime: string }[],\n): { body: Uint8Array<ArrayBuffer>; contentType: string } {\n const encoder = new TextEncoder()\n const chunks: Uint8Array[] = []\n const push = (text: string): void => { chunks.push(encoder.encode(text)) }\n for (const [name, value] of Object.entries(fields)) {\n push(`--${boundary}\\r\\n`)\n push(`Content-Disposition: form-data; name=\"${name}\"\\r\\n\\r\\n`)\n push(`${value}\\r\\n`)\n }\n images.forEach(image => {\n push(`--${boundary}\\r\\n`)\n push(`Content-Disposition: form-data; name=\"image[]\"; filename=\"${image.name.replace(/\"/g, '')}\"\\r\\n`)\n push(`Content-Type: ${image.mime}\\r\\n\\r\\n`)\n chunks.push(image.bytes)\n push(`\\r\\n`)\n })\n push(`--${boundary}--\\r\\n`)\n const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0)\n const body = new Uint8Array(total)\n let at = 0\n for (const chunk of chunks) {\n body.set(chunk, at)\n at += chunk.length\n }\n return { body, contentType: `multipart/form-data; boundary=${boundary}` }\n}\n\n/** MIME type of a reference image, by the extension the path carries. */\nfunction mimeOfPath(path: string): string {\n const lower = path.toLowerCase()\n if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg'\n if (lower.endsWith('.webp')) return 'image/webp'\n if (lower.endsWith('.gif')) return 'image/gif'\n return 'image/png'\n}\n\n/** Filesystem slug of a prompt: CJK kept, everything unsafe folded to `-`. */\nexport function promptSlug(prompt: string): string {\n const slug = prompt\n .slice(0, 40)\n .replace(/[\\r\\n]+/g, ' ')\n .replace(/[\\\\/:*?\"<>|\\u0000-\\u001f]/g, '')\n .replace(/\\s+/g, '-')\n .replace(/^-+|-+$/g, '')\n return slug.length > 0 ? slug : 'image'\n}\n\n/** The output dir for one config: absolute when configured absolute, else under home. */\nfunction outputDirOf(deps: GenerateDeps, config: ImageConfig): string {\n const home = deps.home?.() ?? harnessHome()\n const dir = config.outputDir\n if (/^([A-Za-z]:[\\\\/]|\\/)/.test(dir)) return dir\n return join(home, 'dsh-model-think-level', dir)\n}\n\n/** A file path that never overwrites: `<slug>-<ts>.png`, plus -2, -3\u2026 when taken. */\nfunction destinationOf(dir: string, slug: string, now: () => number): string {\n const base = join(dir, `${slug}-${now()}.png`)\n if (!existsSync(base)) return base\n for (let index = 2; ; index += 1) {\n const candidate = join(dir, `${slug}-${now()}-${index}.png`)\n if (!existsSync(candidate)) return candidate\n }\n}\n\n/**\n * Where this run's file lands. An explicit `.png` path is honored exactly\n * (an existing one gains a numeric suffix \u2014 the never-overwrite rule);\n * anything else \u2014 an existing directory, a trailing separator, a non-png\n * name \u2014 is created as a directory and receives the slug-timestamp naming.\n */\nexport function resolveDestination(\n requested: string | undefined,\n fallbackDir: string,\n slug: string,\n now: () => number,\n): string {\n if (requested === undefined || requested.trim().length === 0) {\n mkdirSync(fallbackDir, { recursive: true })\n return destinationOf(fallbackDir, slug, now)\n }\n const target = resolve(requested.trim())\n let isDir = false\n try {\n isDir = statSync(target).isDirectory()\n } catch {\n // Absent: classify by spelling below.\n }\n if (isDir || /[\\\\/]$/.test(target) || !target.toLowerCase().endsWith('.png')) {\n mkdirSync(target, { recursive: true })\n return destinationOf(target, slug, now)\n }\n mkdirSync(dirname(target), { recursive: true })\n if (!existsSync(target)) return target\n for (let index = 2; ; index += 1) {\n const candidate = target.replace(/\\.png$/i, `-${index}.png`)\n if (!existsSync(candidate)) return candidate\n }\n}\n\n/** The b64 payloads of a successful images answer, in the order the wire returned them. */\nasync function imagesOfAnswer(answer: unknown, send: typeof globalThis.fetch, deadline: ImageDeadline, key: string | undefined): Promise<string[]> {\n if (typeof answer !== 'object' || answer === null) throw new GenerateError('upstream', '\u4E0A\u6E38\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u5E94\u7B54\u7ED3\u6784')\n const data = (answer as Record<string, unknown>)['data']\n if (!Array.isArray(data) || data.length === 0) {\n // Some relays wrap the answer one level deeper; try the common shapes once.\n for (const nestedKey of ['images', 'output', 'result'] as const) {\n const nested = (answer as Record<string, unknown>)[nestedKey]\n if (Array.isArray(nested) && nested.length > 0) return imagesOfAnswer({ data: nested }, send, deadline, key)\n }\n throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u7F3A\u5C11 data \u6570\u7EC4')\n }\n const images: string[] = []\n for (const entry of data) {\n if (typeof entry !== 'object' || entry === null) throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u7684 data \u6570\u7EC4\u91CC\u6709\u975E\u5BF9\u8C61\u9879')\n const record = entry as Record<string, unknown>\n if (typeof record['b64_json'] === 'string' && record['b64_json'].length > 0) {\n images.push(record['b64_json'])\n continue\n }\n deadline.check()\n if (typeof record['url'] === 'string' && record['url'].length > 0) {\n try {\n const response = await deadline.run(() => send(record['url'] as string, { redirect: 'follow', signal: deadline.signal }))\n if (!response.ok) throw new GenerateError('upstream', `\u4E0B\u8F7D\u4E0A\u6E38\u56FE\u7247\u5931\u8D25\uFF08${response.status}\uFF09`)\n const bytes = await responseBytes(response, deadline)\n let binary = ''\n for (let index = 0; index < bytes.length; index += 1) binary += String.fromCharCode(bytes[index]!)\n deadline.check()\n images.push(btoa(binary))\n } catch (error) {\n deadline.check()\n if (error instanceof GenerateError) throw error\n throw new GenerateError('upstream', `\u4E0B\u8F7D\u4E0A\u6E38\u56FE\u7247\u5931\u8D25\uFF1A${sanitize(error instanceof Error ? error.message : String(error), key)}`)\n }\n continue\n }\n throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u65E2\u65E0 b64_json \u4E5F\u65E0 url')\n }\n return images\n}\n\n/** The core and native tool use identical cancellation/timeout classification. */\nexport function createGenerateDeadline(timeoutMs: number, signal?: AbortSignal): ImageDeadline {\n return createImageDeadline(timeoutMs, signal, kind => new GenerateError(kind, kind === 'aborted'\n ? '\u751F\u6210\u5DF2\u53D6\u6D88'\n : `\u751F\u6210\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09\u2014\u2014\u53EF\u5728\u914D\u7F6E\u9875\u8C03\u5927\u8D85\u65F6`))\n}\n\n/**\n * Run one generation. Reads the config fresh, resolves the model per the\n * priority chain, merges params, calls the images endpoint (with one pass of\n * the param fallback chain), decodes and writes the file.\n */\nexport async function generateImage(deps: GenerateDeps, request: GenerateRequest, sharedDeadline?: ImageDeadline): Promise<GenerateResult> {\n const config = deps.config?.() ?? readImageConfig()\n const deadline = sharedDeadline ?? createGenerateDeadline(deps.timeoutMs ?? config.defaults.timeoutMs, request.signal)\n try {\n deadline.check()\n return await generateWithinDeadline(deps, request, config, deadline)\n } catch (error) {\n deadline.check()\n throw error\n } finally {\n if (sharedDeadline === undefined) deadline.dispose()\n }\n}\n\nasync function generateWithinDeadline(deps: GenerateDeps, request: GenerateRequest, config: ImageConfig, deadline: ImageDeadline): Promise<GenerateResult> {\n // The switch is authoritative for EVERY entry (tool, `/\u751F\u56FE`, any cached\n // execute): a generation that starts after the user turned the service off\n // must not spend a paid request on a model that is no longer offered.\n if (!config.enabled) throw new GenerateError('config', '\u751F\u56FE\u670D\u52A1\u5DF2\u5173\u95ED\u2014\u2014\u53EF\u5728\u300C\u9AD8\u7EA7\u8BBE\u7F6E \u2192 \u751F\u56FE\u300D\u91CC\u91CD\u65B0\u5F00\u542F')\n const prompt = request.prompt.trim()\n if (prompt.length === 0) throw new GenerateError('param', '\u63D0\u793A\u8BCD\u4E3A\u7A7A')\n const model = resolveImageModel(config, request.model)\n if (model === undefined) {\n throw new GenerateError('config', config.models.length === 0\n ? '\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684\u751F\u56FE\u6A21\u578B\u2014\u2014\u8BF7\u5230 \u6A21\u578B\u914D\u7F6E \u2192 \u8F93\u5165\u6A21\u6001 \u52FE\u9009\u300C\u751F\u56FE\u300D\uFF0C\u6216\u5728\u63D2\u4EF6\u914D\u7F6E\u9875\u6DFB\u52A0'\n : `\u751F\u56FE\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u552F\u4E00\u5B9A\u4F4D\uFF1A${request.model ?? config.defaultModel ?? `(\u672A\u8BBE\u9ED8\u8BA4\uFF0C\u5019\u9009 ${config.models.map(candidate => candidate.id).join('\u3001')})`}\u3002\u8BF7\u5E26\u4E0A model \u53C2\u6570\uFF0C\u6216\u5230\u63D2\u4EF6\u914D\u7F6E\u9875\u628A\u5176\u4E2D\u4E00\u4E2A\u8BBE\u4E3A\u9ED8\u8BA4\u6A21\u578B`)\n }\n if (model.api !== 'images') {\n throw new GenerateError('endpoint', `\u8BE5\u6A21\u578B\uFF08${model.id}\uFF09\u7684\u534F\u8BAE\u6CA1\u6709\u517C\u5BB9\u7684 images \u7AEF\u70B9\uFF0C\u751F\u6210\u5DF2\u7981\u7528`)\n }\n if (model.baseURL.length === 0) {\n throw new GenerateError('config', `\u6A21\u578B ${model.id} \u6240\u5728\u4F9B\u5E94\u5546\u672A\u914D\u7F6E baseURL`)\n }\n const params = effectiveParams(config, model, request)\n const key = model.keyRef === undefined ? undefined : await deadline.run(() => deps.resolveKey(model.keyRef!, deadline.signal))\n if (model.keyRef !== undefined && key === undefined) {\n throw new GenerateError('auth', `\u8BE5 route\uFF08${model.route}\uFF09\u672A\u914D\u7F6E\u5BC6\u94A5\uFF08\u5F15\u7528 ${model.keyRef}\uFF09\u2014\u2014\u8BF7\u5230\u6A21\u578B\u914D\u7F6E\u9875\u586B\u5199`)\n }\n\n const base = model.baseURL.replace(/\\/+$/, '')\n const now = deps.now ?? (() => Date.now())\n // Reference images never change across the fallback loop: both channels are\n // read once, before the first attempt (a missing file fails the call up\n // front instead of after a paid round-trip).\n const referenceReads: { name: string; bytes: Uint8Array; mime: string }[] = [\n ...(request.referenceFiles ?? []).map(file => ({ name: file.name, bytes: file.bytes, mime: file.mime })),\n ...(request.referenceImages ?? []).map(path => {\n deadline.check()\n const absolute = resolve(path)\n if (!existsSync(absolute)) throw new GenerateError('reference', `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`)\n try {\n return { name: absolute.split(/[\\\\/]/).pop() ?? 'image', bytes: readFileSync(absolute), mime: mimeOfPath(absolute) }\n } catch {\n throw new GenerateError('reference', `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`)\n }\n }),\n ]\n // One fallback pass, in the design's order: drop response_format \u2192 lower\n // quality \u2192 reset size \u2192 n=1. Each revision is recorded for the reply text.\n const revisions: string[] = []\n let format: 'b64_json' | 'output_format' | 'none' = model.lastGoodParams?.responseFormat ?? model.params.responseFormat\n let quality = params.quality\n let size = params.size\n let count = params.n\n let lastFailure: { kind: GenerateFailureKind; message: string; status?: number } | undefined\n\n for (let attempt = 0; attempt < 5; attempt += 1) {\n deadline.check()\n const signal = deadline.signal\n let response: Response\n try {\n if (referenceReads.length > 0) {\n const boundary = `dsh-image-${now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n const fields: Record<string, string> = {\n prompt,\n model: model.modelId,\n n: String(count),\n size,\n }\n if (format !== 'none') fields['output_format'] = 'png'\n const { body, contentType } = buildMultipart(boundary, fields, referenceReads)\n response = await deadline.run(() => deps.send(`${base}/images/edits`, {\n method: 'POST',\n headers: {\n 'content-type': contentType,\n ...(key === undefined ? {} : { authorization: `Bearer ${key}` }),\n },\n body,\n signal,\n }))\n } else {\n const payload: Record<string, unknown> = {\n model: model.modelId,\n prompt,\n n: count,\n size,\n quality,\n }\n if (format === 'b64_json') payload['response_format'] = 'b64_json'\n if (format === 'output_format') payload['output_format'] = 'png'\n response = await deadline.run(() => deps.send(`${base}/images/generations`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...(key === undefined ? {} : { authorization: `Bearer ${key}` }),\n },\n body: JSON.stringify(payload),\n signal,\n }))\n }\n } catch (error) {\n deadline.check()\n if (error instanceof GenerateError) throw error\n const message = error instanceof Error ? error.message : String(error)\n throw new GenerateError('upstream', `\u65E0\u6CD5\u8FDE\u63A5 ${base}\uFF1A${sanitize(message, key)}`)\n }\n\n if (response.ok) {\n let answer: unknown\n try {\n answer = JSON.parse(new TextDecoder().decode(await responseBytes(response, deadline)))\n } catch {\n deadline.check()\n throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u4E0D\u662F\u5408\u6CD5 JSON')\n }\n const payloads = await imagesOfAnswer(answer, deps.send, deadline, key)\n // One file per returned image. Each destination is resolved only after\n // the previous file is on disk, so the never-overwrite suffixes advance\n // (`a.png`, `a-2.png`, \u2026) whatever spelling the caller chose.\n const images: GeneratedImage[] = []\n for (const data of payloads) {\n deadline.check()\n const filePath = resolveDestination(request.outputPath, outputDirOf(deps, config), promptSlug(prompt), now)\n const bytes = Uint8Array.from(atob(data), ch => ch.charCodeAt(0))\n deadline.check()\n writeFileSync(filePath, bytes)\n images.push({ filePath, data })\n }\n deadline.check()\n if (revisions.length > 0 && deps.persistLastGood !== undefined) {\n deps.persistLastGood(model.id, {\n ...model.params,\n responseFormat: format,\n sizes: model.params.sizes,\n qualities: model.params.qualities,\n maxN: model.params.maxN,\n })\n }\n deadline.check()\n return {\n images,\n mime: 'image/png',\n model: model.id,\n prompt,\n paramsUsed: { size, quality, n: count },\n revisions: [...revisions],\n }\n }\n\n const bodyText = await boundedText(response, deadline)\n let body: unknown\n try {\n body = JSON.parse(bodyText)\n } catch {\n body = undefined\n }\n // The upstream sentence first (it is the operative one), the raw body as\n // backup context \u2014 both through the sanitizer before anything downstream\n // can see them.\n const combined = sanitize([upstreamMessage(body), bodyText].filter((part): part is string =>\n typeof part === 'string' && part.length > 0).join(' '), key)\n lastFailure = classifyFailure(response.status, combined)\n // Endpoint facts are worth persisting even on a terminal failure: a 404\n // means \"no images endpoint here\", and the badge should say so.\n if (lastFailure.kind === 'endpoint') deps.persistLastGood?.(model.id, null)\n const revision = fallbackRevisionFor(response.status, bodyText)\n if (revision !== undefined && revisions.length < 4) {\n // Apply the FIRST matching downgrade the error names; the loop retries\n // with the narrowed shape, so one 4xx costs one extra attempt at most\n // per dropped param.\n if (revision === 'removed response_format' || revision === 'removed output_format') {\n if (format === 'none') continue\n revisions.push(revision)\n format = 'none'\n } else if (revision === 'lowered quality') {\n const at = QUALITY_LADDER.indexOf(quality)\n if (at === -1 || at === QUALITY_LADDER.length - 1) continue\n revisions.push(revision)\n quality = QUALITY_LADDER[at + 1]!\n } else if (revision === 'reset size to 1024x1024') {\n if (size === '1024x1024') continue\n revisions.push(revision)\n size = '1024x1024'\n } else {\n if (count === 1) continue\n revisions.push(revision)\n count = 1\n }\n continue\n }\n break\n }\n\n const failure = lastFailure ?? { kind: 'upstream' as const, message: '\u751F\u6210\u5931\u8D25' }\n throw new GenerateError(failure.kind, `\u751F\u56FE\u5931\u8D25\uFF1A${failure.message}${revisions.length > 0 ? `\uFF08\u5DF2\u56DE\u9000\uFF1A${revisions.join('\u3001')}\uFF09` : ''}`, failure.status)\n}\n", "/** One cancellable budget shared by every asynchronous phase of an image call. */\nexport interface ImageDeadline {\n readonly signal: AbortSignal\n check(): void\n run<T>(work: () => T | PromiseLike<T>): Promise<T>\n dispose(): void\n}\n\n/**\n * Factories run only after the cancellation listener is installed. The race\n * bounds even a dependency that ignores signal; both late outcomes are consumed.\n * It cannot physically stop such a dependency or preempt synchronous work.\n */\nexport function createImageDeadline(\n timeoutMs: number,\n caller: AbortSignal | undefined,\n errorFor: (kind: 'aborted' | 'timeout') => Error,\n): ImageDeadline {\n const controller = new AbortController()\n const expiresAt = Date.now() + timeoutMs\n let timer: ReturnType<typeof setTimeout> | undefined\n const forwardAbort = (): void => { controller.abort(caller?.reason) }\n const cleanup = (): void => {\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n caller?.removeEventListener('abort', forwardAbort)\n }\n controller.signal.addEventListener('abort', cleanup, { once: true })\n if (caller?.aborted === true) forwardAbort()\n else {\n caller?.addEventListener('abort', forwardAbort, { once: true })\n timer = setTimeout(() => controller.abort(new DOMException('Image deadline exceeded', 'TimeoutError')), timeoutMs)\n }\n\n const check = (): void => {\n if (caller?.aborted === true) forwardAbort()\n // Also detect an expired budget after synchronous decoding/filesystem work,\n // before the event loop has had a chance to deliver the timer callback.\n if (!controller.signal.aborted && Date.now() >= expiresAt) {\n controller.abort(new DOMException('Image deadline exceeded', 'TimeoutError'))\n }\n if (controller.signal.aborted) throw errorFor(caller?.aborted === true ? 'aborted' : 'timeout')\n }\n\n return {\n signal: controller.signal,\n check,\n run: <T>(work: () => T | PromiseLike<T>): Promise<T> => new Promise<T>((resolve, reject) => {\n let settled = false\n const finish = (done: () => void): void => {\n if (settled) return\n settled = true\n controller.signal.removeEventListener('abort', onAbort)\n done()\n }\n const onAbort = (): void => {\n try { check() } catch (error) { finish(() => reject(error)) }\n }\n try {\n check()\n controller.signal.addEventListener('abort', onAbort, { once: true })\n check()\n Promise.resolve(work()).then(value => {\n try {\n check()\n finish(() => resolve(value))\n } catch (error) { finish(() => reject(error)) }\n }, error => {\n try { check() } catch (cancelled) { error = cancelled }\n finish(() => reject(error))\n })\n } catch (error) { finish(() => reject(error)) }\n }),\n dispose: () => {\n cleanup()\n controller.signal.removeEventListener('abort', cleanup)\n },\n }\n}\n", "/**\n * The `/\u751F\u56FE` host command (the explicit entry beside the wire dispatch).\n *\n * Registered on the HOST side on purpose: the client's `commandUi.register`\n * can only run a no-argument action \u2014 a command that reads parameters would\n * fall through to `remote.commands.execute` and answer \"unknown or malformed\n * command\". The host-side `ctx.commands.register` with an `input.hint` is the\n * shape the built-in command plugins use (the dsh-command-goal precedent).\n *\n * The handler is a thin argument parser over the SHARED generation core \u2014\n * the same `generateImage` the native `generate_image` tool calls.\n *\n * @module dsh-model-think-level/image/command\n */\n\nimport { GenerateError, generateImage, type GenerateDeps, type GenerateResult } from './generate.js'\n\n/** The host `commands` service, typed structurally (no new dependency). */\nexport interface CommandsServiceLike {\n register(contribution: {\n definitionId: string\n name: string\n description: string\n input?: { hint?: string; attachments?: boolean }\n handler: (invocation: unknown) => Promise<unknown>\n }): unknown\n}\n\n/** The plugin's command definition id (the built-ins' `@deepseek-ai/<pkg>:<name>` spelling). */\nexport const IMAGEGEN_DEFINITION_ID = '@deepseek-ai/dsh-model-think-level:imagegen'\n\n/** The hint the slash menu shows under the command. */\nexport const IMAGEGEN_HINT = '[<\u6A21\u578B>] [--size 1024x1024] [--quality high] [--n 1] [--\u53C2\u8003\u56FE <\u8DEF\u5F84>] <\u63D0\u793A\u8BCD>'\n\n/** One parsed invocation. */\nexport interface ImagegenArgs {\n readonly model?: string\n readonly size?: string\n readonly quality?: string\n readonly n?: number\n readonly referenceImages: readonly string[]\n readonly prompt: string\n}\n\n/**\n * Parse one `/\u751F\u56FE` argument string. Tolerant on purpose: the model may be\n * omitted (the config default applies), an unknown option is reported (with\n * the accepted spellings \u2014 never silently ignored), and everything that is\n * neither option nor model is the prompt.\n * @throws Error naming the mistake and the accepted options.\n */\nexport function parseImagegenArgs(text: string, knownModels: readonly string[] = []): ImagegenArgs {\n const options = new Set(['--size', '--quality', '--n', '--\u53C2\u8003\u56FE', '--ref'])\n const tokens = text.trim().split(/\\s+/).filter(token => token.length > 0)\n let model: string | undefined\n const size: string[] = []\n const quality: string[] = []\n const referenceImages: string[] = []\n let n: number | undefined\n const prompt: string[] = []\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]!\n if (token.startsWith('--')) {\n const lower = token.toLowerCase()\n if (!options.has(lower)) {\n throw new Error(`\u672A\u77E5\u9009\u9879 ${token}\u3002\u53EF\u7528\uFF1A--size <\u5BBDx\u9AD8> --quality <\u6863\u4F4D> --n <\u5F20\u6570> --\u53C2\u8003\u56FE <\u8DEF\u5F84>`)\n }\n const value = tokens[index + 1]\n if (value === undefined || value.startsWith('--')) {\n throw new Error(`\u9009\u9879 ${token} \u7F3A\u5C11\u53D6\u503C\u3002\u53EF\u7528\uFF1A--size <\u5BBDx\u9AD8> --quality <\u6863\u4F4D> --n <\u5F20\u6570> --\u53C2\u8003\u56FE <\u8DEF\u5F84>`)\n }\n index += 1\n if (lower === '--size') size.push(value)\n else if (lower === '--quality') quality.push(value)\n else if (lower === '--n') {\n const parsed = Number(value)\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > 16) {\n throw new Error(`--n \u9700\u8981 1\u201316 \u7684\u6574\u6570\uFF0C\u6536\u5230\uFF1A${value}`)\n }\n n = parsed\n } else {\n referenceImages.push(value)\n }\n continue\n }\n // The first bare token is the model when it names one in the list; a\n // bare token that names nothing falls into the prompt either way (a\n // mistyped model must not swallow the prompt into a command error).\n if (model === undefined && prompt.length === 0 && knownModels.includes(token)) {\n model = token\n continue\n }\n prompt.push(token)\n }\n const joined = prompt.join(' ').trim()\n if (joined.length === 0) {\n throw new Error('\u7F3A\u5C11\u63D0\u793A\u8BCD\u3002\u7528\u6CD5\uFF1A/\u751F\u56FE [<\u6A21\u578B>] [--size 1024x1024] [--quality high] [--n 1] [--\u53C2\u8003\u56FE <\u8DEF\u5F84>] <\u63D0\u793A\u8BCD>')\n }\n return {\n ...(model === undefined ? {} : { model }),\n ...(size.length > 0 ? { size: size[size.length - 1]! } : {}),\n ...(quality.length > 0 ? { quality: quality[quality.length - 1]! } : {}),\n ...(n === undefined ? {} : { n }),\n referenceImages,\n prompt: joined,\n }\n}\n\n/**\n * What the handler needs: the live model ids (for argument disambiguation),\n * the generation deps, and an optional echo face for the session the command\n * ran in. The echo is best-effort \u2014 the command's return value is the\n * contract the host consumes; a session write is attempted only when the\n * invocation carries a session that exposes one.\n */\nexport interface ImagegenDeps {\n readonly modelIds: () => readonly string[]\n readonly generate: typeof generateImage\n readonly generateDeps: GenerateDeps\n /** Best-effort session echo (guarded; never throws into the command). */\n readonly echo?: (invocation: unknown, text: string, filePath: string) => void\n}/** Run one parsed invocation through the shared core and shape the result. */\nexport async function executeImagegen(\n deps: ImagegenDeps,\n parsed: ImagegenArgs,\n): Promise<{ ok: true; filePaths: readonly string[]; mime: string; model: string; paramsUsed: GenerateResult['paramsUsed']; text: string; warning?: string } | { ok: false; error: string }> {\n try {\n const result = await deps.generate(deps.generateDeps, {\n ...(parsed.model === undefined ? {} : { model: parsed.model }),\n prompt: parsed.prompt,\n ...(parsed.size === undefined ? {} : { size: parsed.size }),\n ...(parsed.quality === undefined ? {} : { quality: parsed.quality }),\n ...(parsed.n === undefined ? {} : { n: parsed.n }),\n ...(parsed.referenceImages.length > 0 ? { referenceImages: parsed.referenceImages } : {}),\n })\n const filePaths = result.images.map(image => image.filePath)\n const text = [\n filePaths.length === 1 ? `\u5DF2\u751F\u6210\uFF1A${filePaths[0]}` : `\u5DF2\u751F\u6210 ${filePaths.length} \u5F20\uFF1A\\n${filePaths.map(path => `- ${path}`).join('\\n')}`,\n `\u6A21\u578B ${result.model} \u00B7 size ${result.paramsUsed.size} \u00B7 quality ${result.paramsUsed.quality} \u00B7 n ${result.paramsUsed.n}`,\n result.revisions.length > 0 ? `\u53C2\u6570\u56DE\u9000\uFF1A${result.revisions.join('\u3001')}` : '',\n ].filter(line => line.length > 0).join('\\n')\n return {\n ok: true,\n filePaths,\n mime: result.mime,\n model: result.model,\n paramsUsed: result.paramsUsed,\n text,\n ...(result.revisions.length > 0 ? { warning: `\u53C2\u6570\u56DE\u9000\uFF1A${result.revisions.join('\u3001')}` } : {}),\n }\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : String(error) }\n }\n}\n\n/**\n * The invocation face the host hands the handler, narrowed to what this\n * command reads. `text` carries the arguments after the command word; the\n * exact field is spelled several ways across host versions, so each common\n * one is tried (in order) and the first non-empty wins.\n */\nexport function invocationTextOf(invocation: unknown): string {\n if (typeof invocation === 'object' && invocation !== null) {\n for (const key of ['args', 'argument', 'input', 'text', 'value'] as const) {\n const value = (invocation as Record<string, unknown>)[key]\n if (typeof value === 'string' && value.trim().length > 0) return value\n }\n }\n return ''\n}\n\n/** Register the command. @returns undefined when the host has no commands service. */\nexport function registerImagegenCommand(\n commands: CommandsServiceLike | undefined,\n deps: ImagegenDeps,\n): void {\n if (commands === undefined || typeof commands.register !== 'function') return\n try {\n commands.register({\n definitionId: IMAGEGEN_DEFINITION_ID,\n name: '\u751F\u56FE',\n description: '\u7528\u751F\u56FE\u6A21\u578B\u751F\u6210\u56FE\u7247',\n input: { hint: IMAGEGEN_HINT, attachments: true },\n handler: async invocation => {\n const known = deps.modelIds()\n let parsed: ImagegenArgs\n try {\n parsed = parseImagegenArgs(invocationTextOf(invocation), known)\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : String(error) }\n }\n const answer = await executeImagegen(deps, parsed)\n if (answer.ok) {\n // Best-effort in-session echo; the return value stays authoritative.\n try {\n deps.echo?.(invocation, answer.text, answer.filePaths[0] ?? '')\n } catch {\n // An echo face that throws must never fail a finished generation.\n }\n }\n return answer\n },\n })\n } catch {\n // A host whose command registry rejects the contribution keeps working:\n // the dispatch and the route remain.\n }\n}\n", "/**\n * The native `generate_image` tool \u2014 the conversation model's entry to the\n * shared generation core, registered through the host's own `tools` service\n * (the same in-process shape dsh-image-gen uses). Replaces the retired stdio\n * MCP server: no subprocess, no patch-file entry, no env plumbing \u2014 the tool\n * runs inside this plugin and reaches the attachment store and the credential\n * service directly.\n *\n * Contract notes that are easy to get wrong:\n * - `ctx.tools.register` REQUIRES `output: { schema, render }` \u2014 the schema\n * is enforced against the canonical value `execute` returns, so the shape\n * here and the value built below must agree exactly.\n * - image blocks ride the result CONTENT (`{type:'image', attachment}`), and\n * the host projects them to a text handle for models without image input\n * (dsh-llm `projectImagesForTextModel`) \u2014 a text-only chat model calling\n * this tool never breaks.\n * - `exec.signal` MUST reach the core: a user stop must abort the paid\n * upstream request, not just abandon the tool call.\n *\n * @module dsh-model-think-level/image/tool\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { createGenerateDeadline, generateImage, type GenerateDeps } from './generate.js'\nimport { resolveImageModel, type ImageConfig } from './config.js'\n\n/** The attachment-store face this tool needs, typed structurally. */\nexport interface ImageAttachmentsLike {\n /** Optional adapter signal; one-argument host stores still require a local deadline race. */\n saveImage(input: { data: Uint8Array; mediaType: string; name?: string }, signal?: AbortSignal):\n Promise<{ attachmentId: string; mediaType: string; bytes: number; width: number; height: number; name?: string }>\n readImage(ref: { attachmentId: string }, signal?: AbortSignal):\n Promise<{ data: Uint8Array; ref?: { name?: string; mediaType?: string } }>\n}\n\n/** The host tools service face: register and enumerate (for collision checks). */\nexport interface ImageToolsLike {\n register(definition: unknown): unknown\n schemas?: () => readonly { name: string }[]\n}\n\n/** The image-block value shape the tool's canonical value carries per image. */\nexport interface ImageToolImage {\n readonly attachment: {\n readonly attachmentId: string\n readonly mediaType: string\n readonly bytes: number\n readonly width: number\n readonly height: number\n readonly name?: string\n }\n readonly filePath: string\n}\n\n/** The tool's canonical output value (enforced by `OUTPUT_SCHEMA`). */\nexport interface ImageToolValue {\n readonly images: readonly ImageToolImage[]\n readonly model: string\n readonly prompt: string\n readonly paramsUsed: { readonly size: string; readonly quality: string; readonly n: number }\n readonly revisions: readonly string[]\n}\n\n/** The faces the tool needs. All injectable for tests. */\nexport interface ImageToolDeps {\n readonly generateDeps: GenerateDeps\n readonly attachments: ImageAttachmentsLike\n /** The live config, for the params the hint and the defaults describe. */\n readonly readConfig: () => ImageConfig\n readonly logger?: { warn(message: string): void }\n}\n\n/** The primary tool name; the fallback keeps a dsh-image-gen install working. */\nexport const IMAGE_TOOL_NAME = 'generate_image'\nexport const IMAGE_TOOL_NAME_FALLBACK = 'dsh_image_generate'\n\n/** The attachment-id spellings both accepted: canonical `sha256:\u2026` or bare digest. */\nfunction attachmentRefOf(id: string): { attachmentId: string } {\n const trimmed = id.trim()\n return { attachmentId: trimmed.startsWith('sha256:') ? trimmed : `sha256:${trimmed}` }\n}\n\n/**\n * The model-facing JSON schema of the canonical value \u2014 RAW JSON Schema only.\n *\n * `tools.register` calls `assertSupportedJsonSchema(output.schema)` without any\n * author-dialect conversion (that is `defineTool`'s job, and this plugin\n * registers directly), so the accepted vocabulary is exactly\n * type/oneOf/properties/required/additionalProperties/items/enum/const plus the\n * annotations description/title/default/examples. In particular `required` is\n * an ARRAY OF PROPERTY NAMES on an OBJECT \u2014 never a per-node boolean. Writing\n * the harness author dialect here (`required: true` inside a property) throws\n * `JsonSchemaError` out of `register`, which fails the whole tools injection\n * and leaves the tool permanently unregistered.\n */\nconst OUTPUT_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['images', 'model', 'prompt', 'paramsUsed'],\n properties: {\n images: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['attachment', 'filePath'],\n properties: {\n attachment: {\n type: 'object',\n additionalProperties: false,\n required: ['attachmentId', 'mediaType', 'bytes', 'width', 'height'],\n properties: {\n attachmentId: { type: 'string' },\n mediaType: { type: 'string' },\n bytes: { type: 'integer' },\n width: { type: 'integer' },\n height: { type: 'integer' },\n name: { type: 'string' },\n },\n },\n filePath: { type: 'string' },\n },\n },\n },\n model: { type: 'string' },\n prompt: { type: 'string' },\n paramsUsed: {\n type: 'object',\n additionalProperties: false,\n required: ['size', 'quality', 'n'],\n properties: {\n size: { type: 'string' },\n quality: { type: 'string' },\n n: { type: 'integer' },\n },\n },\n revisions: { type: 'array', items: { type: 'string' } },\n },\n}\n\n/** The model-facing argument schema \u2014 object-rooted RAW JSON Schema, same rules. */\nconst TOOL_PARAMETERS = {\n type: 'object',\n additionalProperties: false,\n required: ['prompt'],\n properties: {\n prompt: { type: 'string', description: '\u5B8C\u6574\u753B\u9762\u63CF\u8FF0\uFF1A\u4E3B\u4F53\u3001\u6784\u56FE\u3001\u98CE\u683C\u3001\u5149\u7167\uFF0C\u4EE5\u53CA\u9700\u8981\u51FA\u73B0\u7684\u6587\u5B57\u3002' },\n model: { type: 'string', description: '\u751F\u56FE\u6A21\u578B\uFF08route/modelId \u6216\u663E\u793A\u540D\uFF09\uFF1B\u7F3A\u7701\u7528\u914D\u7F6E\u9875\u7684\u9ED8\u8BA4\u6A21\u578B\uFF0C\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002' },\n size: { type: 'string', description: '\u5982 1024x1024\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\u3002\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002' },\n quality: { type: 'string', description: '\u5982 high\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\u3002\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002' },\n n: { type: 'integer', description: '\u751F\u6210\u5F20\u6570\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\uFF0C\u8D85\u8FC7\u8BE5\u6A21\u578B\u4E0A\u9650\u65F6\u62A5\u9519\u5E76\u5217\u51FA\u5141\u8BB8\u503C\u3002' },\n reference_images: { type: 'array', items: { type: 'string' }, description: '\u672C\u5730\u53C2\u8003\u56FE\u8DEF\u5F84\uFF1B\u975E\u7A7A\u8D70 /images/edits\u3002' },\n reference_attachments: { type: 'array', items: { type: 'string' }, description: '\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID\uFF08sha256:\u2026 \u6216\u88F8\u6458\u8981\uFF09\uFF1B\u4E0E\u672C\u5730\u8DEF\u5F84\u53EF\u6DF7\u7528\u3002' },\n path: { type: 'string', description: '\u843D\u76D8\u6587\u4EF6\uFF08\u4EE5 .png \u7ED3\u5C3E\uFF0C\u5B58\u5728\u5219\u81EA\u52A8\u52A0 -2 \u540E\u7F00\uFF0C\u4E0D\u8986\u76D6\uFF09\u6216\u76EE\u5F55\uFF1B\u7F3A\u7701 generated-images/<slug>-<ts>.png\u3002' },\n },\n}\n\n/** One args record narrowed from the model's JSON. Everything but prompt is optional. */\ninterface ToolArgs {\n readonly prompt: string\n readonly model?: string\n readonly size?: string\n readonly quality?: string\n readonly n?: number\n readonly referenceImages?: readonly string[]\n readonly referenceAttachments?: readonly string[]\n readonly outputPath?: string\n}\n\n/** Defensive arg narrowing: the model's JSON is untrusted, drop bad fields. */\nfunction parseArgs(raw: unknown): ToolArgs | string {\n if (typeof raw !== 'object' || raw === null) return '\u53C2\u6570\u4E0D\u662F\u5BF9\u8C61\uFF1Bprompt \u4E3A\u5FC5\u586B\u5B57\u7B26\u4E32'\n const record = raw as Record<string, unknown>\n const prompt = typeof record['prompt'] === 'string' ? record['prompt'].trim() : ''\n if (prompt.length === 0) return 'prompt \u4E3A\u5FC5\u586B\u5B57\u7B26\u4E32\u4E14\u4E0D\u80FD\u4E3A\u7A7A'\n const list = (key: string): readonly string[] | undefined => {\n const value = record[key]\n if (!Array.isArray(value)) return undefined\n const out = value.filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0)\n return out.length > 0 ? out : undefined\n }\n const n = record['n']\n return {\n prompt,\n ...(typeof record['model'] === 'string' && record['model'].trim().length > 0 ? { model: (record['model'] as string).trim() } : {}),\n ...(typeof record['size'] === 'string' && record['size'].trim().length > 0 ? { size: (record['size'] as string).trim() } : {}),\n ...(typeof record['quality'] === 'string' && record['quality'].trim().length > 0 ? { quality: (record['quality'] as string).trim() } : {}),\n ...(typeof n === 'number' && Number.isInteger(n) && n >= 1 ? { n } : {}),\n ...(list('reference_images') === undefined ? {} : { referenceImages: list('reference_images') }),\n ...(list('reference_attachments') === undefined ? {} : { referenceAttachments: list('reference_attachments') }),\n ...(typeof record['path'] === 'string' && record['path'].trim().length > 0 ? { outputPath: (record['path'] as string).trim() } : {}),\n }\n}\n\n/** The plain-JSON attachment projection the canonical value carries. */\nfunction attachmentValueOf(ref: Awaited<ReturnType<ImageAttachmentsLike['saveImage']>>): ImageToolImage['attachment'] {\n return {\n attachmentId: String(ref.attachmentId),\n mediaType: ref.mediaType,\n bytes: ref.bytes,\n width: ref.width,\n height: ref.height,\n ...(ref.name === undefined ? {} : { name: ref.name }),\n }\n}\n\n/** Shared by the tool schema, success text and system hint: cards alone are not the final reply. */\nconst IMAGE_REPLY_HINT = '\u751F\u56FE\u6210\u529F\u540E\uFF0C\u6700\u7EC8\u56DE\u590D\u5FC5\u987B\u9010\u5F20\u76F4\u63A5\u5D4C\u5165\u6240\u6709\u751F\u6210\u7684\u56FE\u7247\uFF1A\u7528\u8FD4\u56DE\u7684\u771F\u5B9E filePath \u5199 ![\u56FE\u7247\u8BF4\u660E](<filePath>)\uFF0CWindows \u8DEF\u5F84\u7528 /\u3002\u4E0D\u80FD\u53EA\u8BF4\u201C\u56FE\u7247\u5DF2\u751F\u6210/\u5DF2\u9644\u5230\u5BF9\u8BDD\u201D\uFF0C\u4E0D\u80FD\u53EA\u653E\u6587\u4EF6\u94FE\u63A5\u6216\u4F9D\u8D56\u5DE5\u5177\u5361\u7247\u3002'\n\n/** The model-facing text beside the image blocks. */\nfunction summaryText(value: ImageToolValue): string {\n const paths = value.images.map(image => image.filePath)\n const lines = [\n value.images.length === 1\n ? `\u5DF2\u751F\u6210 1 \u5F20\u56FE\u7247\uFF08${value.model}\uFF09\uFF0C\u5DF2\u9644\u5230\u5BF9\u8BDD\u3002`\n : `\u5DF2\u751F\u6210 ${value.images.length} \u5F20\u56FE\u7247\uFF08${value.model}\uFF09\uFF0C\u5DF2\u5168\u90E8\u9644\u5230\u5BF9\u8BDD\u3002`,\n `size ${value.paramsUsed.size} \u00B7 quality ${value.paramsUsed.quality} \u00B7 n ${value.paramsUsed.n}`,\n `\u843D\u76D8\uFF1A${paths.join('\u3001')}`,\n value.revisions.length > 0 ? `\u53C2\u6570\u56DE\u9000\uFF1A${value.revisions.join('\u3001')}` : '',\n IMAGE_REPLY_HINT,\n '\u53EF\u76F4\u63A5\u590D\u5236\u5230\u6700\u7EC8\u56DE\u590D\u7684\u56FE\u7247 Markdown\uFF1A',\n ...paths.map((path, index) => `![\u751F\u6210\u7684\u56FE\u7247 ${index + 1}](<${path.replace(/\\\\/g, '/')}>)`),\n '\u4E0D\u8981\u865A\u6784\u56FE\u7247 URL\uFF0C\u4E5F\u4E0D\u8981\u8C03\u7528 read\u3001glob \u6216\u5176\u4ED6\u5DE5\u5177\u53BB\u627E\u6216\u9A8C\u8BC1\u56FE\u7247\uFF1B\u76F4\u63A5\u4F7F\u7528\u4E0A\u9762\u7684\u771F\u5B9E\u8DEF\u5F84\u5D4C\u56FE\u3002',\n ]\n return lines.filter(line => line.length > 0).join('\\n')\n}\n\n/**\n * Register the native tool. The registration goes through the host's\n * `tools.register` under the primary name; a name that is already taken\n * (a dsh-image-gen install owns `generate_image`) falls back to\n * `dsh_image_generate` with one warning \u2014 a hard failure here would take the\n * whole plugin down over a name.\n * @returns the registered name (the client's keyed image card reads it back\n * over the config route) and the disposer that unregisters the tool.\n */\nexport function registerGenerateImageTool(ctx: Context, deps: ImageToolDeps): { readonly name: string; readonly dispose: () => void } {\n const tools = (ctx as unknown as { tools: ImageToolsLike }).tools\n const definitionFor = (name: string): unknown => ({\n name,\n description: `\u7528\u5F53\u524D\u914D\u7F6E\u7684\u751F\u56FE\u6A21\u578B\u751F\u6210\u56FE\u7247\u5E76\u76F4\u63A5\u9644\u5230\u5BF9\u8BDD\u3002\u7528\u6237\u8981\u753B\u56FE\u3001\u751F\u6210\u3001\u51FA\u56FE\u65F6\u8C03\u7528\uFF1B\u6539\u56FE\u8BF7\u5E26\u53C2\u8003\u56FE\u3002\u53C2\u6570\u4E00\u5F8B\u7F3A\u7701\uFF08\u8BFB\u914D\u7F6E\u9ED8\u8BA4\uFF09\uFF0C\u9664\u975E\u7528\u6237\u660E\u786E\u70B9\u540D\u3002\u4E0D\u8981\u865A\u6784\u56FE\u7247 URL\u3002${IMAGE_REPLY_HINT}`,\n parameters: TOOL_PARAMETERS,\n output: {\n schema: OUTPUT_SCHEMA,\n render: (_args: unknown, value: ImageToolValue) => [\n { type: 'text' as const, text: summaryText(value) },\n ...value.images.map(image => ({ type: 'image' as const, attachment: image.attachment })),\n ],\n presentationMeta: (_args: unknown, value: ImageToolValue) => ({\n kind: 'dsh-model-think-level-image',\n model: value.model,\n prompt: value.prompt,\n paramsUsed: value.paramsUsed,\n revisions: [...value.revisions],\n images: value.images.map(image => ({ attachment: image.attachment, filePath: image.filePath })),\n }),\n },\n async execute(rawArgs: unknown, exec: { signal: AbortSignal }): Promise<ImageToolValue> {\n const parsed = parseArgs(rawArgs)\n if (typeof parsed === 'string') throw new Error(parsed)\n // Snapshot once so references, generation and saves share the SAME budget\n // and config, rather than starting another full timeout inside the core.\n const config = deps.generateDeps.config?.() ?? deps.readConfig()\n // A stale tool definition (or an in-flight call after the switch went\n // off) fails on the switch before touching the credentials or the wire.\n if (!config.enabled) throw new Error('\u751F\u56FE\u670D\u52A1\u5DF2\u5173\u95ED\u2014\u2014\u53EF\u5728\u300C\u9AD8\u7EA7\u8BBE\u7F6E \u2192 \u751F\u56FE\u300D\u91CC\u91CD\u65B0\u5F00\u542F')\n const deadline = createGenerateDeadline(deps.generateDeps.timeoutMs ?? config.defaults.timeoutMs, exec.signal)\n try {\n deadline.check()\n // Conversation attachments become bytes, never temporary files.\n const referenceFiles = []\n for (const [index, id] of (parsed.referenceAttachments ?? []).entries()) {\n try {\n const stored = await deadline.run(() => deps.attachments.readImage(attachmentRefOf(id), deadline.signal))\n const name = stored.ref?.name ?? `reference-${index + 1}.png`\n referenceFiles.push({ name, mime: stored.ref?.mediaType ?? 'image/png', bytes: stored.data })\n } catch (error) {\n deadline.check()\n throw new Error(`\u53C2\u8003\u56FE\uFF08\u9644\u4EF6 ${id}\uFF09\u4E0D\u53EF\u8BFB\uFF1A${error instanceof Error ? error.message : String(error)}`)\n }\n }\n const result = await generateImage({ ...deps.generateDeps, config: () => config }, {\n prompt: parsed.prompt,\n ...(parsed.model === undefined ? {} : { model: parsed.model }),\n ...(parsed.size === undefined ? {} : { size: parsed.size }),\n ...(parsed.quality === undefined ? {} : { quality: parsed.quality }),\n ...(parsed.n === undefined ? {} : { n: parsed.n }),\n ...(parsed.referenceImages === undefined ? {} : { referenceImages: parsed.referenceImages }),\n ...(referenceFiles.length > 0 ? { referenceFiles } : {}),\n ...(parsed.outputPath === undefined ? {} : { outputPath: parsed.outputPath }),\n signal: deadline.signal,\n }, deadline)\n const images: ImageToolImage[] = []\n for (const image of result.images) {\n deadline.check()\n const bytes = Uint8Array.from(atob(image.data), ch => ch.charCodeAt(0))\n const attachment = await deadline.run(() => deps.attachments.saveImage({ data: bytes, mediaType: result.mime, name: 'generated-image' }, deadline.signal))\n images.push({ attachment: attachmentValueOf(attachment), filePath: image.filePath })\n }\n deadline.check()\n return {\n images,\n model: result.model,\n prompt: result.prompt,\n paramsUsed: result.paramsUsed,\n revisions: result.revisions,\n }\n } catch (error) {\n deadline.check()\n throw error\n } finally {\n deadline.dispose()\n }\n },\n presentCall: (args: unknown) => {\n const record = typeof args === 'object' && args !== null ? (args as Record<string, unknown>) : {}\n return {\n card: 'generic' as const,\n title: '\u751F\u6210\u56FE\u7247',\n kind: 'other' as const,\n rawInput: {\n prompt: typeof record['prompt'] === 'string' ? record['prompt'] : '',\n ...(typeof record['model'] === 'string' ? { model: record['model'] } : {}),\n },\n }\n },\n presentResult: (_args: unknown, result: { meta?: unknown }) => {\n const meta = result.meta as { images?: readonly { attachment: ImageToolImage['attachment'] }[] } | undefined\n const attachments = (meta?.images ?? []).map(entry => entry.attachment)\n if (attachments.length === 0) return undefined\n return {\n card: 'generic' as const,\n title: attachments.length === 1 ? '\u751F\u6210\u7684\u56FE\u7247' : `\u751F\u6210\u7684\u56FE\u7247\uFF08${attachments.length} \u5F20\uFF09`,\n content: attachments.map(attachment => ({ type: 'image' as const, attachment })),\n }\n },\n })\n\n // Collision-safe naming: the primary name first, the prefixed fallback only\n // when the registry refuses (a dsh-image-gen install owns the plain name).\n let name = IMAGE_TOOL_NAME\n let disposer: unknown\n try {\n disposer = tools.register(definitionFor(name))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (!/already registered/i.test(message)) throw error\n name = IMAGE_TOOL_NAME_FALLBACK\n deps.logger?.warn(`dsh-model-think-level: tool name \"${IMAGE_TOOL_NAME}\" is taken \u2014 registering the image tool as \"${name}\"`)\n disposer = tools.register(definitionFor(name))\n }\n return {\n name,\n dispose: () => {\n if (typeof disposer === 'function') (disposer as () => void)()\n },\n }\n}\n\n/**\n * The system-prompt hint: which tool to call, what the defaults are.\n *\n * It must describe the SAME model `resolveImageModel` will pick, or the model\n * follows the hint, omits `model`, and gets a `config` error. So the hint asks\n * the resolver itself instead of guessing `models[0]`: with no default set and\n * several candidates the resolver refuses, and the hint then has to say so \u2014\n * naming a model there is a promise the call cannot keep.\n */\nexport function imageToolHint(config: ImageConfig): string {\n // Switched off: the tool is unregistered too, so the prompt must say nothing\n // about a callable it no longer has.\n if (!config.enabled) return ''\n if (config.models.length === 0) return ''\n const defaults = `size ${config.defaults.size}\uFF0Cquality ${config.defaults.quality}\uFF0Cn ${config.defaults.n}`\n const resolved = resolveImageModel(config)\n const opening = resolved === undefined\n ? `\u751F\u56FE\u8BF7\u8C03\u7528 generate_image \u5DE5\u5177\u3002\u5F53\u524D\u6CA1\u6709\u552F\u4E00\u7684\u9ED8\u8BA4\u751F\u56FE\u6A21\u578B\uFF08\u5171 ${config.models.length} \u4E2A\u5019\u9009\uFF09\uFF0C\u8C03\u7528\u65F6\u5FC5\u987B\u663E\u5F0F\u586B model\uFF0C\u53EF\u9009\u503C\uFF1A${config.models.map((model) => model.id).join('\u3001')}\uFF1Bsize/quality/n \u53EF\u7F3A\u7701\uFF08\u9ED8\u8BA4 ${defaults}\uFF09\u3002`\n : `\u751F\u56FE\u8BF7\u8C03\u7528 generate_image \u5DE5\u5177\uFF08\u7F3A\u7701\u53C2\u6570\u5373\u53EF\uFF1A\u9ED8\u8BA4\u6A21\u578B ${resolved.id}\uFF0C${defaults}\uFF09\u3002`\n const lines = [\n opening,\n resolved === undefined\n ? '\u7528\u6237\u6CA1\u6709\u70B9\u540D\u6A21\u578B\u65F6\uFF0C\u5148\u95EE\u6E05\u7528\u54EA\u4E2A\u6A21\u578B\uFF0C\u4E0D\u8981\u81EA\u5DF1\u6311\u4E00\u4E2A\u2014\u2014\u731C\u9519\u7684\u6A21\u578B\u4F1A\u76F4\u63A5\u751F\u6210\u5931\u8D25\u3002\u6539\u56FE\u7528\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID \u586B reference_attachments\uFF0C\u672C\u5730\u6587\u4EF6\u586B reference_images\u3002'\n : '\u7528\u6237\u6CA1\u6709\u70B9\u540D\u6A21\u578B\u6216\u53C2\u6570\u65F6\uFF0C\u4E0D\u8981\u586B model/size/quality/n\uFF1B\u6539\u56FE\u7528\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID \u586B reference_attachments\uFF0C\u672C\u5730\u6587\u4EF6\u586B reference_images\u3002',\n '\u4E0D\u8981\u81EA\u5DF1\u7F16\u9020\u56FE\u7247 URL\uFF0C\u4E5F\u4E0D\u8981\u7528\u522B\u7684\u5DE5\u5177\u627E\u751F\u6210\u7684\u56FE\u7247\u2014\u2014\u6210\u529F\u540E\u5DE5\u5177\u4F1A\u8FD4\u56DE\u9644\u4EF6\u548C\u771F\u5B9E filePath\u3002',\n IMAGE_REPLY_HINT,\n ]\n return lines.join('\\n')\n}\n", "/**\n * One-time migration: remove the retired image-MCP server's patch entry.\n *\n * The v2.0.3 image tool was an stdio MCP subprocess installed by splicing a\n * marker block into the current profile's `cordis.patch.yml`. That transport\n * is gone \u2014 `lib/image-mcp.mjs` is no longer built \u2014 so a leftover block would\n * make the loader spawn a missing file on every boot AND expose a duplicate\n * `mcp__dsh-image__generate_image` beside the native tool. The cleanup runs\n * unconditionally at apply(): absent block \u2192 no-op, present block \u2192 the exact\n * byte range is spliced out (never a re-serialization of the whole document,\n * because third-party marker blocks share this file), with a timestamped\n * `.bak`, an mtime-fenced retry, and a post-write re-read.\n *\n * The running process keeps whatever it loaded at boot; the removal takes\n * effect on the next start, which the caller's log line says.\n *\n * @module dsh-model-think-level/image/legacy-cleanup\n */\n\nimport { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { IMAGE_MCP_PATCH_ID, IMAGE_MCP_PATCH_MARK } from '../constants.js'\nimport { harnessHome } from '../key-index.js'\n\n/** Marker lines the retired installer owned inside the patch file. */\nexport const MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`\nexport const MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`\n\n/** How the current profile's patch file is located (the installer's own order). */\nexport function resolveLegacyPatchFile(home: string = harnessHome()): string {\n const explicit = process.env['DSH_PROFILE']\n if (explicit !== undefined && explicit.length > 0) return join(home, 'profiles', explicit, 'cordis.patch.yml')\n // Auto-detect: the profile whose patch file was touched most recently is the\n // live one in every single-profile deployment, and the honest guess otherwise.\n const profilesDir = join(home, 'profiles')\n try {\n if (existsSync(profilesDir)) {\n const candidates: { readonly file: string; readonly mtime: number }[] = []\n for (const name of readdirSync(profilesDir)) {\n const file = join(profilesDir, name, 'cordis.patch.yml')\n if (!existsSync(file)) continue\n candidates.push({ file, mtime: statSync(file).mtimeMs })\n }\n if (candidates.length === 1) return candidates[0]!.file\n if (candidates.length > 1) return candidates.sort((a, b) => b.mtime - a.mtime)[0]!.file\n }\n } catch {\n // Fall through to the default below.\n }\n // A home-level patch layer (headless compositions) when no profile carries one.\n if (existsSync(join(home, 'cordis.patch.yml'))) return join(home, 'cordis.patch.yml')\n return join(home, 'profiles', 'desktop', 'cordis.patch.yml')\n}\n\n/** Range of the marker block, or undefined when absent. */\nfunction markerRange(text: string): { start: number; end: number } | undefined {\n const start = text.indexOf(MARK_BEGIN)\n if (start === -1) return undefined\n const endMarker = text.indexOf(MARK_END, start)\n if (endMarker === -1) return undefined\n const lineEnd = text.indexOf('\\n', endMarker)\n return { start, end: lineEnd === -1 ? text.length : lineEnd + 1 }\n}\n\n/** One line of the patch document plus its byte offset. */\ninterface PatchLine {\n readonly text: string\n readonly start: number\n}\n\n/** Split into lines while keeping each line's own start offset. */\nfunction linesOf(text: string): readonly PatchLine[] {\n const out: PatchLine[] = []\n let start = 0\n for (const line of text.split('\\n')) {\n out.push({ text: line, start })\n start += line.length + 1\n }\n return out\n}\n\n/**\n * Range of a leftover entry the RETIRED installer wrote but whose marker\n * comment lines were lost \u2014 by a hand edit, or by a third-party panel that\n * re-serialized the file. The marker splice above cannot see those, yet they\n * still make the loader spawn the removed `lib/image-mcp.mjs` on every boot and\n * keep a dead `dsh-image` MCP server in the host's client list.\n *\n * Two shapes count, and both must be owned by our id alone:\n * - a top-level `- insert:` list whose `- id:` rows are all ours, and\n * - a bare top-level `- id: dsh-image-mcp` row (the \"silent non-install\"\n * shape the loader skips).\n * A block carrying anyone else's row is left untouched: a byte splice cannot\n * remove half of it, and guessing would delete a live plugin entry.\n * @returns the byte range to cut, or undefined when nothing of ours is there.\n */\nfunction staleEntryRange(text: string): { start: number; end: number } | undefined {\n const lines = linesOf(text)\n const ownId = new RegExp(`^\\\\s*-\\\\s+id:\\\\s*['\"]?${IMAGE_MCP_PATCH_ID}['\"]?\\\\s*$`)\n const anyId = /^\\s*-\\s+id:/\n for (const [index, line] of lines.entries()) {\n if (!/^-(\\s|$)/.test(line.text)) continue\n // A top-level item runs until the next top-level line (or EOF).\n let end = lines.length\n for (let probe = index + 1; probe < lines.length; probe += 1) {\n const candidate = lines[probe]!\n if (candidate.text.trim().length === 0) continue\n if (!/^\\s/.test(candidate.text)) {\n end = probe\n break\n }\n }\n const body = lines.slice(index + 1, end)\n const owned = /^-\\s*insert:\\s*$/.test(line.text)\n // Every row inside the list must be ours \u2014 never cut a mixed block.\n ? body.some(entry => ownId.test(entry.text)) && !body.some(entry => anyId.test(entry.text) && !ownId.test(entry.text))\n : ownId.test(line.text)\n if (!owned) continue\n return { start: line.start, end: end < lines.length ? lines[end]!.start : text.length }\n }\n return undefined\n}\n\n/** The range to cut: the marked block when the markers survived, else the bare entry. */\nfunction legacyRange(text: string): { start: number; end: number } | undefined {\n return markerRange(text) ?? staleEntryRange(text)\n}\n\n/** Whether a modified document still parses as \"our markers, balanced, once\". */\nfunction validateAfterSplice(text: string): string | undefined {\n const begins = text.split(MARK_BEGIN).length - 1\n const ends = text.split(MARK_END).length - 1\n if (begins !== 0 || ends !== 0) return `marker block still present after the splice (${begins} begin / ${ends} end)`\n if (text.includes('\\t')) return 'the patch file carries a tab character after the splice'\n return undefined\n}\n\n/** The file's mtime, or -1 when it does not exist (the fence's \"no file yet\"). */\nfunction mtimeOf(patchFile: string): number {\n try {\n return statSync(patchFile).mtimeMs\n } catch {\n return -1\n }\n}\n\nclass ModifiedError extends Error {}\n\n/** One attempt of the fenced splice. Throws on mtime movement. */\nfunction spliceOnce(patchFile: string, mtimeMs: number): void {\n const current = readFileSync(patchFile, 'utf8')\n const range = legacyRange(current)\n if (range === undefined) return // already gone: idempotent\n let next = current.slice(0, range.start) + current.slice(range.end)\n // The append seam's blank line goes with the block: when nothing but\n // whitespace follows, the file reads exactly as it did before the install.\n if (current.slice(range.end).trim().length === 0) next = next.replace(/\\n+$/, '\\n')\n const invalid = validateAfterSplice(next)\n if (invalid !== undefined) throw new Error(`refusing to write the patch file: ${invalid}`)\n if (mtimeOf(patchFile) !== mtimeMs) throw new ModifiedError()\n if (!existsSync(`${patchFile}.bak`)) {\n try {\n copyFileSync(patchFile, `${patchFile}.bak`)\n } catch {\n // The backup is a convenience; the write itself is the requirement.\n }\n }\n mkdirSync(dirname(patchFile), { recursive: true })\n writeFileSync(patchFile, next, 'utf8')\n const written = readFileSync(patchFile, 'utf8')\n if (written !== next) throw new Error('the patch file did not hold the written bytes after the write')\n}\n\n/**\n * Remove the retired MCP marker block if it is present.\n * @returns the patch file that was written, or undefined when there was\n * nothing to remove (absent block, absent file, or an unreadable home).\n */\nexport function removeLegacyImageMcpPatch(home?: string, patchFile?: string): string | undefined {\n let file: string\n try {\n file = patchFile ?? resolveLegacyPatchFile(home)\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(file, 'utf8')\n } catch {\n return undefined\n }\n if (legacyRange(text) === undefined) return undefined\n if (!text.includes(`- id: ${IMAGE_MCP_PATCH_ID}`)) {\n // Only a marker block that no longer names our entry: not ours to touch.\n return undefined\n }\n let lastError: unknown\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n spliceOnce(file, mtimeOf(file))\n return file\n } catch (error) {\n if (!(error instanceof ModifiedError)) throw error\n lastError = error\n }\n }\n throw lastError ?? new Error('the patch file kept changing during the cleanup')\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_IMAGE_GEN_MARKER, INPUT_UNSET_MARKER, UNSET_MARKER } from './constants.js'\nimport { isSelfHostedRelay, NEW_COMPAT_KEYS, stripForeignCompat, 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 answer the document already\n * holds: the chat-input declaration, its deliberate-unset marker, or the\n * image-generation marker (\u751F\u56FE) \u2014 all three record a decision the fill must\n * never read back as a gap. 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 if (Array.isArray(input) && input.length > 0) return true\n return model[INPUT_UNSET_MARKER] === true || model[INPUT_IMAGE_GEN_MARKER] === true\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 is carried through\n // row by row (see the loop below) \u2014 never silently deleted.\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 const models = rawModels\n const nextModels: JsonObject[] = []\n let changed = false\n for (const row of models) {\n // A row this builder cannot represent rides along verbatim: the old\n // all-or-nothing bail left EVERY undeclared model on the route unfilled\n // because one stray row existed, with nothing on screen saying why.\n if (!isRecord(row)) {\n nextModels.push(row as JsonObject)\n continue\n }\n const model: JsonObject = row\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 // declaresInput already reads the deliberate-unset and \u751F\u56FE markers as answers.\n const inputDeclared = declaresInput(model)\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 && suggestion.confidence !== 'low') {\n // `confidence: 'low'` is protocol inference on an id nothing in the\n // knowledge base names: a ladder written from it is a claim that the\n // model reasons, and on a self-hosted endpoint it ships a\n // `reasoning_effort` + `thinking_token_budget` the model never asked\n // for (llama-3.3-70b, phi-4, an image generator \u2014 the P0-3 shape).\n // The row stays undeclared; the user declares it by hand or via a\n // confirmed endpoint signal (which carries 'medium' or better).\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) {\n // An image-generation verdict replaces the chat-input declaration: the\n // marker is the whole answer, and an `input` array beside it would\n // read the row back as a vision chat model.\n if (suggestion.imageGen === true) {\n touched = true\n fill[INPUT_IMAGE_GEN_MARKER] = true\n } else if (suggestion.input !== undefined) {\n touched = true\n fill['input'] = [...suggestion.input]\n }\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/**\n * Build the protocol-mismatch cleanup patch (the compat guard): every model\n * row -- and the route-level compat block -- whose compat carries a switch its\n * route's wire protocol does not take loses exactly those keys.\n *\n * This is the repair for a protocol switched after the switches were written:\n * openai-completions \u2192 openai-responses leaves `supportsReasoningEffort` on\n * every model, and the kernel then refuses each of them at catalog resolution\n * (\"sets compat ..., but its api is ..., which does not take it\"), so the\n * route serves nothing until the keys are gone.\n *\n * Only routes that NAME a wire protocol are swept: a route without `api`\n * resolves each model's protocol from the installed catalog, which this\n * builder cannot see, so touching it could strip a key a catalog model\n * legitimately takes. Returns the partial providers patch, or undefined when\n * nothing is dirty -- the common case, so a caller never writes speculatively.\n * Pure data logic like {@link buildAutofillPatch}: shared by BOTH halves.\n */\nexport function buildCompatCleanupPatch(providers: unknown): JsonObject | undefined {\n if (!isRecord(providers)) return undefined\n const patchRoutes: JsonObject = {}\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile)) continue\n const api = typeof profile['api'] === 'string' ? profile['api'] : ''\n if (api.length === 0) continue\n const patchProfile: JsonObject = {}\n // Route-level switches: under an explicit api every model speaks that one\n // protocol, so a foreign key there is refused exactly as a model-level one.\n const routeCompat = isRecord(profile['compat'])\n ? stripForeignCompat(profile['compat'] as Record<string, unknown>, api)\n : undefined\n if (routeCompat !== undefined) patchProfile['compat'] = routeCompat\n const rawModels = Array.isArray(profile['models']) ? profile['models'] : undefined\n if (rawModels !== undefined && rawModels.length > 0) {\n const nextModels: unknown[] = []\n let changed = false\n for (const row of rawModels) {\n // A row this builder cannot represent rides along verbatim -- the\n // array is rebuilt whole, never silently shortened.\n if (!isRecord(row) || !isRecord(row['compat'])) {\n nextModels.push(row)\n continue\n }\n const cleaned = stripForeignCompat(row['compat'] as Record<string, unknown>, api)\n if (cleaned === undefined) {\n nextModels.push(row)\n continue\n }\n changed = true\n nextModels.push({ ...row, compat: cleaned })\n }\n if (changed) patchProfile['models'] = nextModels\n }\n if (Object.keys(patchProfile).length > 0) patchRoutes[route] = patchProfile\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). */export 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", "// ModelTrace \u6570\u5B57\u6307\u7EB9\uFF1A\u6307\u7EB9\u5E93\uFF08unified_bank.json\uFF09\u7684\u52A0\u8F7D\u4E0E\u6821\u9A8C\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u94F6\u884C\u662F\u6570\u636E\u96C6\u800C\u975E\u4EE3\u7801\uFF0C\u6309 MIT \u968F\u9644\uFF0C\u6765\u6E90\u4E0E\u6784\u5EFA\u65F6\u95F4\u89C1 assets/NOTICE.md\u3002\n//\n// \u8FD9\u4E2A\u6A21\u5757\u662F\u5BBF\u4E3B\u4FA7\uFF08Node\uFF09\u4E13\u7528\uFF1A\u5B83\u8981\u8BFB\u5305\u91CC\u7684 assets/unified_bank.json\u3002\n// \u524D\u7AEF\u53EA\u9700\u8981 summarizeBank() \u7684\u4EA7\u7269\uFF0C\u8D70 /fingerprint-state \u62FF\u3002\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\n\nimport { DIMENSION, type Bank, type BankModel } from './core.js';\n\nconst REQUIRED_CALIBRATION_KEYS = ['1', '2', '3'] as const;\n\nexport interface BankModelSummary {\n id: string;\n displayName: string;\n family: string;\n familyName: string;\n}\n\nexport interface BankSummary {\n builtAt: string;\n schema: string;\n models: BankModelSummary[];\n families: Array<{ family: string; name: string; models: number }>;\n recommendedQueries: number;\n}\n\nfunction isNumberArray(value: unknown, length?: number): value is number[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'number' && Number.isFinite(item))\n && (length === undefined || value.length === length);\n}\n\nfunction isNumberMatrix(value: unknown, rows?: number, columns?: number): value is number[][] {\n return Array.isArray(value) && value.every((row) => isNumberArray(row, columns))\n && (rows === undefined || value.length === rows);\n}\n\nfunction isNumberCube(value: unknown, depth1?: number, depth2?: number, depth3?: number): value is number[][][] {\n return Array.isArray(value) && value.every((plane) => isNumberMatrix(plane, depth2, depth3))\n && (depth1 === undefined || value.length === depth1);\n}\n\nfunction fail(message: string): never {\n throw new Error(`fingerprint bank: ${message}`);\n}\n\n/** \u53EA\u505A\u5F62\u72B6\u6821\u9A8C\u5E76\u6536\u7A84\u6210 `Bank`\uFF1B\u4E0D\u6539\u4EFB\u4F55\u6570\u503C\u3002 */\nexport function parseBank(raw: unknown): Bank {\n if (typeof raw !== 'object' || raw === null) fail('root must be an object');\n const source = raw as Record<string, unknown>;\n\n const models = source.models;\n if (!Array.isArray(models) || models.length === 0) fail('models must be a non-empty array');\n models.forEach((model, index) => {\n if (typeof model !== 'object' || model === null) fail(`models[${index}] must be an object`);\n const entry = model as Record<string, unknown>;\n if (typeof entry.id !== 'string' || entry.id.length === 0) fail(`models[${index}].id must be a non-empty string`);\n if (typeof entry.display_name !== 'string') fail(`models[${index}].display_name must be a string`);\n if (typeof entry.family !== 'string') fail(`models[${index}].family must be a string`);\n if (!isNumberArray(entry.counts, DIMENSION)) fail(`models[${index}].counts must be ${DIMENSION} numbers`);\n });\n\n const robust = source.robust;\n if (typeof robust !== 'object' || robust === null) fail('robust must be an object');\n const artifacts = robust as Record<string, unknown>;\n for (const key of ['hellinger', 'ordered_blocks'] as const) {\n const artifact = artifacts[key];\n if (typeof artifact !== 'object' || artifact === null) fail(`robust.${key} must be an object`);\n const fields = artifact as Record<string, unknown>;\n const columns = key === 'hellinger' ? DIMENSION : undefined;\n if (!isNumberArray(fields.feature_mean, columns)) fail(`robust.${key}.feature_mean has the wrong shape`);\n if (!isNumberArray(fields.feature_scale, columns)) fail(`robust.${key}.feature_scale has the wrong shape`);\n if (!isNumberMatrix(fields.nuisance_basis, undefined, columns)) fail(`robust.${key}.nuisance_basis has the wrong shape`);\n if (!isNumberMatrix(fields.centroids, models.length, columns)) {\n fail(`robust.${key}.centroids must be ${models.length} rows aligned with models`);\n }\n if (key === 'ordered_blocks' && !isNumberCube(fields.environment_centroids, undefined, models.length)) {\n fail('robust.ordered_blocks.environment_centroids has the wrong shape');\n }\n }\n\n const calibration = source.calibration;\n if (typeof calibration !== 'object' || calibration === null) fail('calibration must be an object');\n const groups = calibration as Record<string, unknown>;\n for (const key of REQUIRED_CALIBRATION_KEYS) {\n const group = groups[key];\n if (typeof group !== 'object' || group === null) fail(`calibration.${key} is missing`);\n const fields = group as Record<string, unknown>;\n if (typeof fields.beta !== 'number' || !Number.isFinite(fields.beta)) fail(`calibration.${key}.beta must be a number`);\n if (typeof fields.cv_accuracy !== 'number') fail(`calibration.${key}.cv_accuracy must be a number`);\n }\n\n return raw as Bank;\n}\n\n/**\n * Every place the bank can live, nearest first.\n *\n * The host bundles this module into `<pkg>/lib/index.js`, so `import.meta.url`\n * points at `lib/` \u2014 but the package also keeps the very same layout in the\n * source tree (`src/fingerprint/`). One fixed `../../assets` therefore only\n * works in one of the two layouts, and in the installed profile it resolved to\n * `<profile>/node_modules/assets/unified_bank.json` (the parent of the plugin\n * folder), which never exists. Walking up from the module and taking the first\n * `assets/unified_bank.json` that exists works for source, lib/, and any future\n * bundle depth without trusting `process.cwd()` (the host's cwd is the user's,\n * not the package's).\n */\nfunction bankCandidates(): string[] {\n const candidates: string[] = [];\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let depth = 0; depth < 5; depth += 1) {\n candidates.push(join(dir, 'assets', 'unified_bank.json'));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return candidates;\n}\n\nfunction bankPath(): string {\n const candidates = bankCandidates();\n const found = candidates.find(candidate => existsSync(candidate));\n if (found === undefined) {\n throw new Error(`\u6307\u7EB9\u5E93 assets/unified_bank.json \u672A\u627E\u5230\uFF08\u5DF2\u67E5\u627E\uFF1A${candidates.join('\u3001')}\uFF09`);\n }\n return found;\n}\n\nlet cached: Bank | undefined;\n\n/** \u540C\u6B65\u8BFB\u5305\u5185\u7684\u6307\u7EB9\u5E93\u3002\u7ED3\u679C\u53EA\u89E3\u6790\u4E00\u6B21\u3002 */\nexport function loadBankSync(): Bank {\n if (cached !== undefined) return cached;\n cached = parseBank(JSON.parse(readFileSync(bankPath(), 'utf8')));\n return cached;\n}\n\nexport function summarizeBank(bank: Bank): BankSummary {\n const families = new Map<string, { family: string; name: string; models: number }>();\n for (const model of bank.models) {\n const family = model.family || 'models';\n const known = families.get(family);\n if (known !== undefined) known.models += 1;\n else families.set(family, { family, name: model.family_name || family, models: 1 });\n }\n return {\n builtAt: String(bank.built_at ?? ''),\n schema: String(bank.schema ?? ''),\n models: bank.models.map((model: BankModel) => ({\n id: model.id,\n displayName: model.display_name,\n family: model.family || 'models',\n familyName: model.family_name || model.family || 'models',\n })),\n families: [...families.values()],\n recommendedQueries: Number(bank.recommended_queries ?? 3),\n };\n}\n\nexport function bankBuiltAt(bank: Bank): string {\n return String(bank.built_at ?? '');\n}\n", "// ModelTrace \u6570\u5B57\u6307\u7EB9\uFF1A\u5224\u5B9A\u6838\u5FC3\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u5BF9\u5E94\u6587\u4EF6\uFF1Astatic/fingerprint-core.js / codex-plugin/modeltrace-guard/scripts/fingerprint-core.mjs\n// \u79FB\u690D\u539F\u5219\uFF1A\u4E0E\u4E0A\u6E38\u9010\u884C\u5BF9\u9F50\uFF0C\u53EA\u5728\u7C7B\u578B\u4E0A\u6536\u7D27\uFF0C\u4E0D\u6539\u4EFB\u4F55\u6570\u503C\u8DEF\u5F84\u3002\n// \u672C\u6587\u4EF6\u5FC5\u987B\u4FDD\u6301\u300C\u96F6 import + \u7EAF\u51FD\u6570\u300D\uFF0C\u4EE5\u4FBF\u5355\u6D4B\u80FD\u72EC\u7ACB\u4E8E\u63D2\u4EF6\u5BBF\u4E3B\u8FD0\u884C\u3002\n//\n// \u8BB8\u53EF\u8BC1\uFF1AMIT\uFF0C\u89C1\u4ED3\u5E93\u6839 LICENSE \u7684\u7B2C\u4E09\u65B9\u58F0\u660E\u6BB5\u3002\n\nexport const VALUE_MIN = 1;\nexport const VALUE_MAX = 355;\nexport const DIMENSION = VALUE_MAX - VALUE_MIN + 1;\nexport const ALPHA = 0.5;\nexport const ORDERED_BLOCK_WEIGHT = 0.25;\n\n/** \u94F6\u884C\u91CC\u7684\u4E00\u4F4D\u5019\u9009\u6A21\u578B\u3002`counts` \u4E0E `DIMENSION` \u7B49\u957F\u3002 */\nexport interface BankModel {\n id: string;\n display_name: string;\n family: string;\n family_name?: string;\n counts: number[];\n}\n\nexport interface BankArtifact {\n feature_mean: number[];\n feature_scale: number[];\n nuisance_basis: number[][];\n centroids: number[][];\n weight?: number;\n environment_centroids?: number[][][];\n}\n\nexport interface Bank {\n schema?: string;\n built_at?: string;\n method?: string;\n recommended_queries?: number;\n minimum_valid_numbers?: number;\n models: BankModel[];\n robust: {\n model_order?: string[];\n hellinger: BankArtifact;\n ordered_blocks: BankArtifact;\n };\n calibration: Record<string, { beta: number; cv_accuracy: number }>;\n}\n\nexport interface Output {\n text: string;\n expected_count: number;\n}\n\nexport interface ResultRow {\n model: string;\n display_name: string;\n probability: number;\n profile_similarity: number;\n score: number;\n family: string;\n family_name: string;\n conditional_probability: number;\n}\n\nexport interface Diagnostic {\n index: number;\n parsed_numbers: number;\n minimum_numbers: number;\n accepted: boolean;\n}\n\nexport interface AttributionResult {\n prediction: string;\n prediction_name: string;\n probability: number;\n used_outputs: number;\n results: ResultRow[];\n diagnostics: Diagnostic[];\n calibration: { queries: number; beta: number; cv_accuracy: number };\n family_prediction: string;\n family_prediction_name: string;\n family_probability: number;\n family_probabilities: Array<{ family: string; display_name: string; probability: number }>;\n method: string;\n}\n\n/** \u4E09\u9898\u5168\u5E9F\u65F6\u629B\u51FA\uFF0C\u6587\u6848\u7167\u6284\u4E0A\u6E38\uFF0C\u522B\u6539\u5199\u3002 */\nexport const NO_USABLE_OUTPUT = '\u6CA1\u6709\u53EF\u7528\u56DE\u7B54\uFF1A\u8BF7\u7C98\u8D34\u5B8C\u6574\u6570\u5B57\u5E8F\u5217\uFF1B\u62D2\u7B54\u6216\u4E25\u91CD\u622A\u65AD\u7684\u56DE\u7B54\u4E0D\u4F1A\u8BA1\u5165\u3002';\n\nexport function parseNumbers(text: string): number[] {\n const runs: number[][] = [];\n let current: number[] = [];\n let previousEnd = 0;\n for (const match of String(text).matchAll(/\\d+/g)) {\n const separator = String(text).slice(previousEnd, match.index);\n const value = Number(match[0]);\n if (current.length > 0 && /\\p{L}/u.test(separator)) {\n runs.push(current);\n current = [];\n }\n if (value >= VALUE_MIN && value <= VALUE_MAX) current.push(value);\n previousEnd = (match.index ?? 0) + match[0].length;\n }\n if (current.length > 0) runs.push(current);\n return runs.reduce<number[]>((best, run) => (run.length > best.length ? run : best), []);\n}\n\nexport function countNumbers(numbers: number[]): number[] {\n const counts = Array<number>(DIMENSION).fill(0);\n numbers.forEach((number) => {\n counts[number - VALUE_MIN] += 1;\n });\n return counts;\n}\n\nfunction mean(values: number[]): number {\n return values.reduce((total, value) => total + value, 0) / values.length;\n}\n\nfunction standardize(values: number[]): number[] {\n const center = mean(values);\n const variance = mean(values.map((value) => (value - center) ** 2));\n const scale = Math.max(Math.sqrt(variance), 1e-12);\n return values.map((value) => (value - center) / scale);\n}\n\nfunction dot(left: number[], right: number[]): number {\n let value = 0;\n for (let index = 0; index < left.length; index += 1) value += left[index] * right[index];\n return value;\n}\n\nfunction norm(values: number[]): number {\n return Math.sqrt(dot(values, values));\n}\n\nfunction normalized(values: number[]): number[] {\n const scale = Math.max(norm(values), 1e-12);\n return values.map((value) => value / scale);\n}\n\nfunction subtractBasis(values: number[], basis: number[][] | undefined): number[] {\n const output = values.slice();\n for (const vector of basis ?? []) {\n const projection = dot(output, vector);\n for (let index = 0; index < output.length; index += 1) output[index] -= projection * vector[index];\n }\n return output;\n}\n\nfunction hellingerFeature(counts: number[]): number[] {\n const total = counts.reduce((sum, value) => sum + value, 0) + ALPHA * DIMENSION;\n return counts.map((value) => Math.sqrt((value + ALPHA) / total));\n}\n\nfunction splitIntoFour(values: number[]): number[][] {\n const base = Math.floor(values.length / 4);\n const remainder = values.length % 4;\n const chunks: number[][] = [];\n let start = 0;\n for (let index = 0; index < 4; index += 1) {\n const size = base + (index < remainder ? 1 : 0);\n chunks.push(values.slice(start, start + size));\n start += size;\n }\n return chunks;\n}\n\nfunction orderedBlockFeature(numbers: number[]): number[] {\n const pieces: number[] = [];\n for (const chunk of splitIntoFour(numbers)) {\n const bins = Array<number>(16).fill(0.5);\n for (const value of chunk) {\n const index = Math.min(15, Math.floor(((value - 1) / 355) * 16));\n bins[index] += 1;\n }\n const total = bins.reduce((sum, value) => sum + value, 0);\n pieces.push(...bins.map((value) => Math.sqrt(value / total)));\n }\n const lastDigits = Array<number>(10).fill(0.5);\n numbers.forEach((value) => {\n lastDigits[value % 10] += 1;\n });\n const lastTotal = lastDigits.reduce((sum, value) => sum + value, 0);\n pieces.push(...lastDigits.map((value) => Math.sqrt(value / lastTotal)));\n return pieces;\n}\n\nfunction robustScoreCounts(counts: number[], bank: Bank): number[] {\n const artifact = bank.robust.hellinger;\n const feature = hellingerFeature(counts);\n let projected = feature.map((value, index) => (value - artifact.feature_mean[index]) / artifact.feature_scale[index]);\n projected = subtractBasis(projected, artifact.nuisance_basis);\n projected = normalized(projected);\n const scores = artifact.centroids.map((centroid) => dot(projected, centroid));\n return standardize(scores);\n}\n\nfunction orderedBlockScores(numbers: number[], bank: Bank): number[] {\n const artifact = bank.robust.ordered_blocks;\n const feature = orderedBlockFeature(numbers);\n const standardizedFeature = feature.map(\n (value, index) => (value - artifact.feature_mean[index]) / artifact.feature_scale[index],\n );\n const unit = normalized(standardizedFeature);\n const environmentCentroids = artifact.environment_centroids ?? [];\n const environmentScores = environmentCentroids.map((centroids) => centroids.map((centroid) => dot(unit, centroid)));\n const template = standardize(\n artifact.centroids.map((_, modelIndex) =>\n Math.max(...environmentScores.map((scores) => scores[modelIndex])),\n ),\n );\n const projected = normalized(subtractBasis(standardizedFeature, artifact.nuisance_basis));\n const nuisance = standardize(artifact.centroids.map((centroid) => dot(projected, centroid)));\n return standardize(template.map((value, index) => 0.5 * value + 0.5 * nuisance[index]));\n}\n\nfunction robustScoreNumbers(numbers: number[], bank: Bank): number[] {\n const marginal = robustScoreCounts(countNumbers(numbers), bank);\n const artifact = bank.robust.ordered_blocks;\n const weight = artifact ? Number(artifact.weight ?? 0) : 0;\n if (!artifact || weight === 0) return marginal;\n const ordered = orderedBlockScores(numbers, bank);\n return marginal.map((value, index) => (1 - weight) * value + weight * ordered[index]);\n}\n\nfunction softmax(values: number[]): number[] {\n const maximum = Math.max(...values);\n const weights = values.map((value) => Math.exp(value - maximum));\n const total = weights.reduce((sum, value) => sum + value, 0);\n return weights.map((value) => value / total);\n}\n\nfunction jsSimilarity(left: number[], right: number[]): number {\n const leftTotal = left.reduce((sum, value) => sum + value, 0);\n const rightTotal = right.reduce((sum, value) => sum + value, 0) + ALPHA * DIMENSION;\n const p = left.map((value) => value / leftTotal);\n const q = right.map((value) => (value + ALPHA) / rightTotal);\n const midpoint = p.map((value, index) => (value + q[index]) / 2);\n const divergence = (values: number[]): number =>\n values.reduce((total, value, index) => total + (value ? value * Math.log(value / midpoint[index]) : 0), 0);\n const js = (divergence(p) + divergence(q)) / 2;\n return 1 - Math.sqrt(js / Math.log(2));\n}\n\nexport function analyzeGlobalOutputs(outputs: Output[], bank: Bank): AttributionResult {\n const modelIds = bank.models.map((model) => model.id);\n const valid: Array<{ numbers: number[]; counts: number[]; scores: number[] }> = [];\n const diagnostics: Diagnostic[] = [];\n outputs.forEach((item, index) => {\n const expected = Number(item.expected_count || 0);\n const numbers = parseNumbers(item.text || '');\n const minimum = expected ? Math.max(80, Math.ceil(expected * 0.55)) : 80;\n const accepted = numbers.length >= minimum;\n diagnostics.push({ index, parsed_numbers: numbers.length, minimum_numbers: minimum, accepted });\n if (accepted) valid.push({ numbers, counts: countNumbers(numbers), scores: robustScoreNumbers(numbers, bank) });\n });\n if (valid.length === 0) throw new Error(NO_USABLE_OUTPUT);\n\n const combinedScores = modelIds.map((_, modelIndex) => mean(valid.map((item) => item.scores[modelIndex])));\n const calibrationKey = String(Math.min(valid.length, 3));\n const calibration = bank.calibration[calibrationKey];\n const beta = Number(calibration?.beta ?? 1);\n const probabilities = softmax(combinedScores.map((value) => beta * value));\n const pooledCounts = Array.from({ length: DIMENSION }, (_, index) =>\n valid.reduce((sum, item) => sum + item.counts[index], 0),\n );\n const modelEntries = Object.fromEntries(bank.models.map((model) => [model.id, model]));\n const familyOrder = [...new Set(bank.models.map((model) => model.family || 'models'))];\n const familyNames = Object.fromEntries(\n familyOrder.map((family) => [\n family,\n bank.models.find((model) => (model.family || 'models') === family)?.family_name || family,\n ]),\n );\n const results: ResultRow[] = modelIds\n .map((model, index) => {\n const entry = modelEntries[model];\n return {\n model,\n display_name: entry.display_name,\n probability: probabilities[index],\n profile_similarity: jsSimilarity(pooledCounts, entry.counts),\n score: combinedScores[index],\n family: entry.family || 'models',\n family_name: familyNames[entry.family || 'models'],\n conditional_probability: 0,\n };\n })\n .sort((left, right) => right.probability - left.probability);\n const familyProbabilities = Object.fromEntries(\n familyOrder.map((family) => [\n family,\n results.filter((item) => item.family === family).reduce((sum, item) => sum + item.probability, 0),\n ]),\n );\n results.forEach((item) => {\n item.conditional_probability = item.probability / familyProbabilities[item.family];\n });\n const winningFamily = familyOrder.reduce((best, family) =>\n familyProbabilities[family] > familyProbabilities[best] ? family : best,\n );\n return {\n prediction: results[0].model,\n prediction_name: results[0].display_name,\n probability: results[0].probability,\n used_outputs: valid.length,\n results,\n diagnostics,\n calibration: {\n queries: Number(calibrationKey),\n beta,\n cv_accuracy: Number(calibration?.cv_accuracy ?? 0),\n },\n family_prediction: winningFamily,\n family_prediction_name: familyNames[winningFamily],\n family_probability: familyProbabilities[winningFamily],\n family_probabilities: familyOrder.map((family) => ({\n family,\n display_name: familyNames[family],\n probability: familyProbabilities[family],\n })),\n method: '\u7EDF\u4E00\u5168\u5C40\u7A33\u5065\u6570\u5B57\u6307\u7EB9',\n };\n}\n", "// \u53EF\u79FB\u690D\u7684\u5BC6\u7801\u5B66\u968F\u673A\u6E90\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u5BF9\u5E94 Python \u4FA7\u7684 random.SystemRandom \u4E0E secrets.token_hex\u3002\n// Node 22 \u4E0E\u6D4F\u89C8\u5668\u90FD\u63D0\u4F9B globalThis.crypto\uFF0C\u56E0\u6B64\u8FD9\u4E00\u4EFD\u4EE3\u7801\u5BBF\u4E3B\u4E0E\u524D\u7AEF\u5171\u7528\u3002\n\nfunction webCrypto(): Crypto {\n const source = (globalThis as { crypto?: Crypto }).crypto;\n if (source === undefined || typeof source.getRandomValues !== 'function') {\n throw new Error('fingerprint: no Web Crypto source available');\n }\n return source;\n}\n\nfunction fillRandomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n webCrypto().getRandomValues(bytes);\n return bytes;\n}\n\n/** `[0, maxExclusive)` \u4E0A\u7684\u65E0\u504F\u6574\u6570\uFF08\u62D2\u7EDD\u91C7\u6837\uFF0C\u4E0E Python `random.randrange` \u540C\u8BED\u4E49\uFF09\u3002 */\nexport function randomInt(maxExclusive: number): number {\n if (!Number.isInteger(maxExclusive) || maxExclusive <= 0) {\n throw new RangeError(`fingerprint: randomInt bound must be a positive integer, got ${maxExclusive}`);\n }\n if (maxExclusive > 0x100000000) throw new RangeError('fingerprint: randomInt bound exceeds 2^32');\n const limit = 0x100000000 - (0x100000000 % maxExclusive);\n for (;;) {\n const bytes = fillRandomBytes(4);\n const value = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0;\n if (value < limit) return value % maxExclusive;\n }\n}\n\n/** `secrets.token_hex(n)`\uFF1An \u4E2A\u968F\u673A\u5B57\u8282\u7684\u5341\u516D\u8FDB\u5236\u4E32\uFF0C\u957F\u5EA6 2n\u3002 */\nexport function randomToken(bytes: number): string {\n let out = '';\n for (const byte of fillRandomBytes(bytes)) out += byte.toString(16).padStart(2, '0');\n return out;\n}\n", "// ModelTrace \u6570\u5B57\u6307\u7EB9\uFF1A\u4E09\u9053\u9898\u7684\u751F\u6210\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u5BF9\u5E94\u6587\u4EF6\uFF1Afingerprint.py:generate_challenges\n// \u79FB\u690D\u539F\u5219\uFF1A\u6587\u6848\u6C60\u9010\u5B57\u7167\u6284\uFF0C\u4E0D\u6539\u5199\uFF1B\u53EA\u628A random.SystemRandom / secrets.token_hex\n// \u6362\u6210 Web Crypto\uFF08Node 22 \u4E0E\u6D4F\u89C8\u5668\u90FD\u6709 globalThis.crypto\uFF09\u3002\n//\n// \u9898\u5E72\u91CC\u7684\u4E24\u6761\u786C\u7EA6\u675F\uFF08\u7981\u6B62\u5DE5\u5177 / \u7981\u6B62\u89C4\u5F8B\u5316\u6A21\u5F0F\uFF09\u662F\u4E0A\u6E38\u660E\u786E\u8981\u6C42\u300C\u7167\u6284\uFF0C\u522B\u6539\u5199\u300D\u7684\uFF0C\n// \u6539\u4E00\u4E2A\u5B57\u90FD\u4F1A\u8BA9\u6307\u7EB9\u5206\u5E03\u504F\u79BB\u94F6\u884C\u3002\n\nimport { randomInt, randomToken } from './random.js';\n\nexport interface Challenge {\n id: string;\n expected_count: number;\n prompt: string;\n}\n\nconst LENGTH_MIN = 292;\nconst LENGTH_MAX_EXCLUSIVE = 333;\n\nconst OPENINGS = [\n '\u8FD9\u662F\u4E00\u6B21\u72EC\u7ACB\u7684\u6570\u503C\u9009\u62E9\u8BB0\u5F55',\n '\u8BF7\u5B8C\u6210\u4E0B\u9762\u7684\u65E0\u8BED\u4E49\u6574\u6570\u9009\u62E9\u4EFB\u52A1',\n '\u6267\u884C\u4E00\u6B21\u7B2C\u4E00\u53CD\u5E94\u53D6\u503C\u8BB0\u5F55',\n '\u751F\u6210\u4E00\u7EC4\u4E0D\u627F\u8F7D\u8BED\u4E49\u7684\u6574\u6570\u9009\u62E9',\n '\u8FDB\u884C\u4E00\u8F6E\u5FEB\u901F\u9010\u9879\u53D6\u503C',\n];\n\nconst ACTIONS = [\n '\u4E3A\u5404\u4E2A\u4F4D\u7F6E\u5206\u522B\u51ED\u7B2C\u4E00\u53CD\u5E94\u9009\u62E9',\n '\u9010\u9879\u9009\u62E9',\n '\u6BCF\u6B21\u53EA\u51B3\u5B9A\u5F53\u524D\u4E00\u9879\uFF0C\u5171\u7ED9\u51FA',\n '\u5206\u522B\u51ED\u7B2C\u4E00\u53CD\u5E94\u7ED9\u51FA',\n '\u9010\u4E2A\u76F4\u63A5\u9009\u62E9',\n];\n\nconst ENDINGS = [\n '\u5141\u8BB8\u67D0\u4E2A\u6570\u5B57\u518D\u6B21\u51FA\u73B0\uFF1B\u6BCF\u9879\u5199\u51FA\u540E\u4E0D\u8981\u56DE\u5934\u6392\u5E8F\u3001\u53BB\u91CD\u6216\u66FF\u6362\u3002',\n '\u5076\u7136\u91CD\u590D\u662F\u6709\u6548\u7684\uFF1B\u4E0D\u8981\u91CD\u65B0\u6392\u5217\u6216\u4FEE\u6B63\u5DF2\u7ECF\u5199\u51FA\u7684\u9879\u76EE\u3002',\n '\u76F8\u540C\u503C\u53EF\u4EE5\u518D\u6B21\u51FA\u73B0\uFF1B\u8F93\u51FA\u8FC7\u7A0B\u4E2D\u4E0D\u8981\u6574\u7406\u6216\u6539\u5199\u524D\u9762\u7684\u9879\u76EE\u3002',\n '\u91CD\u590D\u503C\u65E0\u9700\u5220\u9664\uFF1B\u4E0D\u8981\u7B5B\u9009\u3001\u91CD\u6392\u6216\u8865\u6210\u67D0\u79CD\u89C4\u5F8B\u3002',\n '\u4E0D\u5FC5\u8D4B\u4E88\u6570\u5B57\u4EFB\u4F55\u542B\u4E49\uFF1B\u5DF2\u7ECF\u7ED9\u51FA\u7684\u503C\u4FDD\u6301\u4E0D\u53D8\u3002',\n];\n\nconst SEPARATOR_HINTS = [\n '\u6570\u5B57\u4E4B\u95F4\u7528\u9017\u53F7\u6216\u7A7A\u683C\u5206\u9694\u5747\u53EF\u3002',\n '\u4F7F\u7528\u4E00\u79CD\u4E00\u81F4\u7684\u5E38\u89C1\u5206\u9694\u7B26\u5373\u53EF\u3002',\n '\u53EF\u4EE5\u7528\u9017\u53F7\u3001\u7A7A\u683C\u6216\u6362\u884C\u5206\u9694\u3002',\n '\u53EA\u8981\u6BCF\u4E2A\u6574\u6570\u8FB9\u754C\u6E05\u695A\uFF0C\u683C\u5F0F\u53EF\u81EA\u884C\u9009\u62E9\u3002',\n];\n\nfunction pick(pool: readonly string[]): string {\n return pool[randomInt(pool.length)];\n}\n\n/** \u65E0\u653E\u56DE\u62BD\u6837\uFF1A\u4E0E Python `rng.sample(population, count)` \u540C\u8BED\u4E49\u3002 */\nfunction sampleRange(min: number, maxExclusive: number, count: number): number[] {\n const population = Array.from({ length: maxExclusive - min }, (_, index) => min + index);\n for (let index = 0; index < count; index += 1) {\n const swapWith = index + randomInt(population.length - index);\n const held = population[index];\n population[index] = population[swapWith];\n population[swapWith] = held;\n }\n return population.slice(0, count);\n}\n\nexport function generateChallenges(count = 3): Challenge[] {\n const lengths = sampleRange(LENGTH_MIN, LENGTH_MAX_EXCLUSIVE, count);\n return lengths.map((length, index) => {\n const prompt =\n `${pick(OPENINGS)}\u3002${pick(ACTIONS)} ${length} \u4E2A 1 \u5230 355\uFF08\u542B\u7AEF\u70B9\uFF09\u7684\u6574\u6570\u3002` +\n '\u6BCF\u4E2A\u4F4D\u7F6E\u90FD\u8981\u5355\u72EC\u9009\u62E9\uFF1B\u4E0D\u8981\u4ECE 1 \u5F00\u59CB\u8BA1\u6570\uFF0C\u4E0D\u8981\u8FDE\u7EED\u9012\u589E\u6216\u9012\u51CF\uFF0C\u4E5F\u4E0D\u8981\u91C7\u7528\u7B49\u5DEE\u3001\u5FAA\u73AF\u3001\u91CD\u590D\u533A\u5757\u6216\u5176\u4ED6\u89C4\u5219\u5316\u6A21\u5F0F\u3002' +\n '\u672C\u4EFB\u52A1\u5FC5\u987B\u7531\u5F53\u524D\u8BED\u8A00\u6A21\u578B\u76F4\u63A5\u5B8C\u6210\uFF1A\u7981\u6B62\u8C03\u7528\u6216\u501F\u52A9\u4EFB\u4F55\u5DE5\u5177\uFF0C\u5305\u62EC Python\u3001\u4EE3\u7801\u6267\u884C\u5668\u3001' +\n '\u8BA1\u7B97\u5668\u3001\u641C\u7D22\u3001API \u548C\u5916\u90E8\u968F\u673A\u6570\u751F\u6210\u5668\uFF1B\u4E5F\u4E0D\u8981\u5148\u7F16\u5199\u6216\u8FD0\u884C\u4EE3\u7801\u3002' +\n `${pick(ENDINGS)}${pick(SEPARATOR_HINTS)}` +\n '\u76F4\u63A5\u4ECE\u7B2C\u4E00\u4E2A\u53D6\u503C\u5F00\u59CB\u8F93\u51FA\uFF0C\u4E0D\u8981\u5728\u5E8F\u5217\u524D\u91CD\u590D\u6570\u91CF\u3001\u8303\u56F4\u6216\u4EFB\u52A1\u8BF4\u660E\u3002';\n return {\n id: `probe-${index + 1}-${randomToken(7)}`,\n expected_count: length,\n prompt,\n };\n });\n}\n\n/** \u4E09\u9898\u5E94\u7B54\u7684\u6700\u5C0F\u6709\u6548\u6570\u5B57\u4E2A\u6570\uFF1A`max(80, ceil(expected * 0.55))`\u3002 */\nexport function minimumNumbers(expectedCount: number): number {\n return expectedCount ? Math.max(80, Math.ceil(expectedCount * 0.55)) : 80;\n}\n\nexport const CHALLENGE_TEXT = {\n openings: OPENINGS,\n actions: ACTIONS,\n endings: ENDINGS,\n separatorHints: SEPARATOR_HINTS,\n} as const;\n", "// \u6307\u7EB9\u68C0\u6D4B\u7684\u300C\u8D44\u683C\u300D\u5224\u5B9A\uFF1A\u54EA\u4E9B\u6A21\u578B\u5141\u8BB8\u8FDB\u8FD9\u4E00\u9875\u3002\n//\n// \u6307\u7EB9\u5E93\u53EA\u6709\u4E24\u4E2A\u5BB6\u65CF\uFF08GPT / Claude\uFF09\u5171 18 \u4E2A\u5019\u9009\uFF0C\u522B\u7684\u6A21\u578B\u6839\u672C\u65E0\u4ECE\u5224\u5B9A\u3002\n// \u6240\u4EE5\u8D44\u683C\u5224\u65AD\u662F**\u9875\u9762\u7EA7\u7684\u5B58\u5728\u5224\u65AD**\uFF1A\u4E0D\u5728\u540D\u5355\u91CC\u7684\u6A21\u578B\u8FDE\u5165\u53E3\u90FD\u4E0D\u51FA\u73B0\uFF0C\n// \u800C\u4E0D\u662F\u663E\u793A\u4E00\u884C\u300C\u4E0D\u652F\u6301\u300D\u3002\u7406\u7531\u89C1 docs/fingerprint-design.md \u00A74.3\u3002\n\nconst ELIGIBLE = /^(gpt-|chatgpt-|o[134](-|$)|claude-)/;\n\n/** \u53D6\u6A21\u578B id \u91CC\u6700\u540E\u4E00\u4E2A `/` \u4E4B\u540E\u7684\u90E8\u5206\uFF0C\u517C\u5BB9 `anthropic/claude-\u2026` \u8FD9\u7C7B\u5E26\u524D\u7F00\u7684\u5199\u6CD5\u3002 */\nexport function bareModelId(modelId: string): string {\n const trimmed = String(modelId ?? '').trim();\n const slash = trimmed.lastIndexOf('/');\n return slash === -1 ? trimmed : trimmed.slice(slash + 1);\n}\n\n/** \u8BE5\u6A21\u578B\u662F\u5426\u80FD\u88AB\u5F53\u524D\u6307\u7EB9\u5E93\u5224\u5B9A\u3002 */\nexport function isEligibleModel(modelId: string): boolean {\n const bare = bareModelId(modelId).toLowerCase();\n return bare.length > 0 && ELIGIBLE.test(bare);\n}\n\n/** \u4ECE\u4E00\u4E32\u6A21\u578B id \u91CC\u6311\u51FA\u53EF\u68C0\u6D4B\u7684\u90A3\u51E0\u4E2A\uFF0C\u4FDD\u6301\u539F\u987A\u5E8F\u3002 */\nexport function eligibleModels<T extends string>(modelIds: readonly T[]): T[] {\n return modelIds.filter((id) => isEligibleModel(id));\n}\n\n/** \u9762\u5411\u7528\u6237\u7684\u5BB6\u65CF\u540D\uFF0C\u7528\u4E8E\u6587\u6848\uFF08\u300CGPT \u7CFB\u5217\u300D/\u300CClaude \u7CFB\u5217\u300D\uFF09\u3002 */\nexport function familyLabelOf(modelId: string): string {\n const bare = bareModelId(modelId).toLowerCase();\n if (bare.startsWith('claude-')) return 'Claude';\n return 'GPT';\n}\n", "/**\n * One fingerprint probe: ask one model one challenge, keep its visible answer.\n *\n * This is the only module that touches the harness `llm` service. Everything\n * else in `src/fingerprint/` is pure or filesystem-only, so the whole\n * attribution math stays testable without a live provider.\n *\n * The request shape is deliberately ModelTrace's: one bare user message, no\n * system prompt, no tools. Two deviations are worth naming.\n *\n * - `reasoningEffort` is LEFT UNSET on purpose. ModelTrace calls a plain chat\n * completion, so the measured behaviour is the model under its own default.\n * Setting an explicit effort would ask a *different* model behaviour than the\n * one the fingerprint bank was built from, and the wire vocabulary for \"off\"\n * differs per provider (`none`, `minimal`, `null`, or a 400). The plugin's\n * own default-guard may still materialize one, exactly as it would for a\n * normal user message -- so the probe measures the model under the plugin's\n * normal conditions.\n * - Only `text-delta` chunks are collected. `reasoning-delta` is thinking, not\n * the answer the challenge asks for, and feeding it to {@link parseNumbers}\n * would pollute the distribution with whatever the model happened to reason\n * about.\n *\n * @module dsh-model-think-level/fingerprint/run\n */\n\nimport { isRecord } from '../shared.js'\nimport type { Output } from './core.js'\n\n/** The llm surface this probe drives: prepare, then dispatch once. */\nexport interface ProbeDispatch {\n prepareCall(config: Record<string, unknown>, signal?: unknown): Promise<unknown>\n /**\n * Runtime-level dispatch, used only when a prepared call carries no dispatch\n * of its own. The harness's `PreparedLlmCall` owns `.stream`, which is the\n * preferred half because it is the one that already holds the prepared call's\n * auth and routing.\n */\n stream?(options: Record<string, unknown>): AsyncIterable<unknown>\n}\n\n/** What one challenge produced, accepted or not. */\nexport interface ProbeOutcome {\n /** Zero-based challenge index, matching `generateChallenges` order. */\n index: number\n /** Challenge id, e.g. `probe-1-9f2c41a7b03d12`. */\n challengeId: string\n /** How many integers the challenge asked for. */\n expectedCount: number\n /** Whether a model call completed and produced any visible text. */\n ok: boolean\n /** Visible answer text; empty when `ok` is false. */\n text: string\n /** Failure description, present only when `ok` is false. */\n error?: string\n /** Why the stream stopped, when one was reported. */\n finish?: string\n /**\n * Milliseconds from dispatch start to the first visible text chunk. Absent\n * when no text arrived (rejected, cancelled, empty answer).\n */\n firstTokenMs?: number\n /** Total wall time of the challenge, milliseconds. */\n durationMs?: number\n /**\n * Aborted BY the early exit: two confident answers already closed the run, so\n * this challenge was never needed. Without the bit a caller cannot tell a\n * deliberate skip from a user cancellation \u2014 both come back `cancelled`.\n */\n skipped?: boolean\n}\n\n/** Everything one model's fingerprint run learned, ready for the bank. */\nexport interface ProbeRunResult {\n /** Per challenge, in order. */\n outcomes: ProbeOutcome[]\n /** The accepted subset, ready for `analyzeGlobalOutputs`. */\n outputs: Output[]\n}\n\n/** One challenge to put to the model. */\nexport interface ProbeChallenge {\n id: string\n expected_count: number\n prompt: string\n}\n\n/** Options for {@link runProbe}. */\nexport interface RunProbeOptions {\n /** Registered provider route selecting the adapter. */\n provider: string\n /** Exact model id. */\n model: string\n /** Challenges to run, in order. */\n challenges: readonly ProbeChallenge[]\n /** The harness llm service. */\n llm: ProbeDispatch\n /** Caller cancellation; combined with the per-probe timeout. */\n signal?: AbortSignal\n /** Per-challenge timeout in milliseconds. Defaults to 120000. */\n timeoutMs?: number\n /** Sampling cap for one answer. Defaults to 4000. */\n maxTokens?: number\n /**\n * Called as each challenge settles, so a caller can stream progress. Fire\n * order is completion order, which for parallel runs is not `index` order.\n * Challenges aborted by {@link shouldStop} do NOT fire this: they never\n * answered, so they are not progress.\n */\n onOutcome?: (outcome: ProbeOutcome) => void\n /**\n * Early-exit hook, called after each challenge settles with every outcome\n * so far. Returning true aborts every challenge still in flight; their\n * outcomes come back cancelled and stay out of `onOutcome` and of any\n * caller-side progress accounting. This is what lets two confident answers\n * close the run before the slowest challenge lands \u2014 aborting the tail is\n * the whole point of firing all three at once.\n */\n shouldStop?: (outcomes: readonly ProbeOutcome[]) => boolean\n}\n\n/** Default per-challenge timeout: two minutes is generous for 300 integers. */\nexport const DEFAULT_PROBE_TIMEOUT_MS = 120000\n\n/**\n * Enough room for 292-332 integers plus whatever preamble the model refuses to\n * drop. Parsed-count tolerance (55% of expected) means a truncated answer can\n * still score, but a full run is strictly better.\n */\nexport const DEFAULT_PROBE_MAX_TOKENS = 4000\n\n/** Call-config fields that must be echoed back to `PreparedLlmCall.stream`. */\nconst FROZEN_CONFIG_FIELDS = ['reasoningEffort', 'temperature', 'maxTokens', 'stop'] as const\n\nfunction firstString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Describe a terminal finish chunk for the UI.\n * @param reason - the `finish` chunk's `reason`.\n * @returns a short human phrase, or undefined for a clean stop.\n */\nfunction finishProblem(reason: unknown): { kind: string; message?: string } | undefined {\n if (!isRecord(reason)) return undefined\n const kind = typeof reason['kind'] === 'string' ? reason['kind'] : 'unknown'\n if (kind === 'stop') return undefined\n const failure = reason['failure']\n const message = isRecord(failure) ? firstString(failure, 'message') : undefined\n return message === undefined ? { kind } : { kind, message }\n}\n\n/**\n * Read one already-prepared call's frozen config so the dispatch echoes it.\n *\n * `PreparedLlmCall.stream` rejects any request whose call-config fields differ\n * from the prepared config (`INVALID_PREPARED_CALL`). The default-guard may\n * have materialized a `reasoningEffort` during preparation, so echoing the\n * request we *proposed* is not good enough -- echo what was *prepared*.\n *\n * @param prepared - the value `prepareCall` resolved to.\n * @param fallback - the config we proposed, used when no frozen copy exists.\n * @returns the call-config fields to send back.\n */\nfunction frozenConfigOf(prepared: unknown, fallback: Record<string, unknown>): Record<string, unknown> {\n if (!isRecord(prepared)) return fallback\n const config = prepared['config']\n return isRecord(config) ? config : fallback\n}\n\n/**\n * Ask one model one challenge and keep its visible answer.\n *\n * Never throws for a provider-side failure: a rejected or empty answer comes\n * back as an outcome with `ok: false`, because one dead challenge must not\n * discard the two that worked. Throws only for programmer errors (no\n * challenges) and for an `AbortSignal` that the *caller* cancelled -- an abort\n * is a decision, not a result.\n *\n * @param options - the run.\n * @returns every outcome in order, plus the accepted subset.\n */\nexport async function runProbe(options: RunProbeOptions): Promise<ProbeRunResult> {\n const { provider, model, challenges, llm, signal } = options\n if (challenges.length === 0) throw new Error('fingerprint probe: no challenges to run')\n const timeoutMs = options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS\n const maxTokens = options.maxTokens ?? DEFAULT_PROBE_MAX_TOKENS\n\n // The three challenges go out together (design \u00A75.3): they are independent\n // samples of the same behaviour, so serializing them only triples the wall\n // clock. The per-challenge deadline is what bounds a hung provider. Each\n // challenge also carries its own stop controller so an early-exit decision\n // can abort only the ones still running.\n const stopControllers = new Map<number, AbortController>()\n const settled: ProbeOutcome[] = []\n let stopping = false\n /** Indices aborted BY the early exit \u2014 their silence is deliberate, not a loss. */\n const suppressed = new Set<number>()\n\n const settledAll = await Promise.all(\n challenges.map(async (challenge, index): Promise<ProbeOutcome> => {\n const stop = new AbortController()\n stopControllers.set(index, stop)\n const stopSignal = signal === undefined ? stop.signal : AbortSignal.any([signal, stop.signal])\n const outcome = signal?.aborted === true\n ? {\n index,\n challengeId: challenge.id,\n expectedCount: challenge.expected_count,\n ok: false,\n text: '',\n error: 'cancelled',\n } satisfies ProbeOutcome\n : await runChallenge({ ...options, index, challenge, timeoutMs, maxTokens, signal: stopSignal })\n stopControllers.delete(index)\n settled.push(outcome)\n\n if (!stopping && signal?.aborted !== true && options.shouldStop?.([...settled]) === true) {\n stopping = true\n for (const [pending, controller] of stopControllers) {\n suppressed.add(pending)\n controller.abort()\n }\n }\n if (suppressed.has(index)) return { ...outcome, skipped: true }\n options.onOutcome?.(outcome)\n return outcome\n }),\n )\n const outcomes = [...settledAll]\n\n const outputs: Output[] = []\n for (const outcome of outcomes) {\n if (outcome.ok) outputs.push({ text: outcome.text, expected_count: outcome.expectedCount })\n }\n return { outcomes, outputs }\n}\n\ninterface RunChallengeOptions extends RunProbeOptions {\n index: number\n challenge: ProbeChallenge\n timeoutMs: number\n maxTokens: number\n}\n\nasync function runChallenge(options: RunChallengeOptions): Promise<ProbeOutcome> {\n const { provider, model, challenge, llm, signal, timeoutMs, maxTokens } = options\n const base = {\n index: options.index,\n challengeId: challenge.id,\n expectedCount: challenge.expected_count,\n }\n\n const startedAt = Date.now()\n let firstTokenMs: number | undefined\n /** Timing folded into every exit path: the outcome should always carry it. */\n const timing = (): { firstTokenMs?: number; durationMs: number } => ({\n ...(firstTokenMs === undefined ? {} : { firstTokenMs }),\n durationMs: Date.now() - startedAt,\n })\n\n const deadline = AbortSignal.timeout(timeoutMs)\n const combined = signal === undefined ? deadline : AbortSignal.any([signal, deadline])\n\n try {\n const config: Record<string, unknown> = { provider, model, maxTokens }\n const prepared = await llm.prepareCall(config, combined)\n const frozen = frozenConfigOf(prepared, config)\n\n const request: Record<string, unknown> = {\n provider: frozen['provider'] ?? provider,\n model: frozen['model'] ?? model,\n messages: [{ role: 'user', content: [{ type: 'text', text: challenge.prompt }] }],\n // ModelTrace offers no tools, and the prompt forbids them. Empty is the\n // explicit \"none\" rather than an omission, so no adapter can project a\n // default toolset into the request.\n tools: [],\n signal: combined,\n }\n for (const field of FROZEN_CONFIG_FIELDS) {\n const value = frozen[field]\n if (typeof value !== 'undefined') request[field] = value\n }\n\n const onPrepared = (prepared as { stream?: (o: Record<string, unknown>) => AsyncIterable<unknown> }).stream\n const stream = typeof onPrepared === 'function'\n ? onPrepared.bind(prepared)\n : typeof llm.stream === 'function'\n ? llm.stream.bind(llm)\n : undefined\n if (stream === undefined) {\n return { ...base, ok: false, text: '', error: 'the llm service returned no dispatch' }\n }\n\n let text = ''\n let finish: { kind: string; message?: string } | undefined = { kind: 'stream-ended' }\n for await (const chunk of stream(request)) {\n if (!isRecord(chunk)) continue\n const type = chunk['type']\n if (type === 'text-delta') {\n const delta = chunk['text']\n if (typeof delta === 'string') {\n if (delta.length > 0 && firstTokenMs === undefined) firstTokenMs = Date.now() - startedAt\n text += delta\n }\n } else if (type === 'finish') {\n finish = finishProblem(chunk['reason'])\n }\n }\n\n if (signal?.aborted === true) {\n return { ...base, ...timing(), ok: false, text: '', error: 'cancelled' }\n }\n if (finish !== undefined) {\n const detail = finish.message === undefined ? finish.kind : `${finish.kind}: ${finish.message}`\n return { ...base, ...timing(), ok: false, text: '', error: detail, finish: finish.kind }\n }\n if (text.trim().length === 0) {\n return { ...base, ...timing(), ok: false, text: '', error: 'the model answered with no visible text' }\n }\n return { ...base, ...timing(), ok: true, text }\n } catch (error) {\n if (signal?.aborted === true) {\n return { ...base, ...timing(), ok: false, text: '', error: 'cancelled' }\n }\n return {\n ...base,\n ...timing(),\n ok: false,\n text: '',\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n", "// \u6307\u7EB9\u68C0\u6D4B\u7ED3\u679C\u7684\u843D\u76D8\uFF1A`<DSH home>/dsh-model-think-level/fingerprint.json`\u3002\n//\n// \u4E0E key-index.json \u540C\u76EE\u5F55\u3001\u540C\u5199\u6CD5\uFF08\u5148\u5199\u540C\u7EA7\u4E34\u65F6\u6587\u4EF6\u518D rename\uFF0C\u4FDD\u8BC1\u539F\u5B50\uFF09\u3002\n// \u53EA\u5B58\u7EDF\u8BA1\u91CF\uFF0C\u4E0D\u5B58\u539F\u59CB\u4F5C\u7B54\u6587\u672C \u2014\u2014 \u89C1 docs/fingerprint-design.md \u00A74.2\u3002\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nimport { harnessHome } from '../key-index.js'\n\n// \u5224\u636E\u672C\u8EAB\u5728 `verdict.ts`\uFF08\u7EAF\u51FD\u6570\u3001\u5BA2\u6237\u7AEF\u5171\u7528\uFF09\uFF1B\u8FD9\u91CC re-export \u53EA\u662F\u4E3A\u4E86\n// \u843D\u76D8\u4E00\u4FA7\u7684\u5F15\u7528\u4E0D\u5FC5\u591A\u4E00\u4E2A import\u3002\u8BB0\u5F55\u5F62\u72B6\u4E5F\u5728\u90A3\u8FB9\uFF1A\u6D4F\u89C8\u5668\u8981\u62FF\u5B83\u753B\u5FBD\u7AE0\uFF0C\n// \u800C\u8FD9\u4E2A\u6A21\u5757\u662F Node-only \u7684\u3002\nimport {\n type FingerprintChallenge,\n type FingerprintRecord,\n type FingerprintStatus,\n type FingerprintTiming,\n type FingerprintTopEntry,\n} from './verdict.js'\n\nexport {\n type FingerprintChallenge,\n type FingerprintRecord,\n type FingerprintStatus,\n type FingerprintTiming,\n type FingerprintTopEntry,\n}\n\nexport interface FingerprintDocument {\n version: 1\n /** \u94F6\u884C\u7684 built_at\uFF1B\u6362\u94F6\u884C\u5C31\u6574\u4F53\u5931\u6548\u3002 */\n bankBuiltAt: string\n records: Record<string, FingerprintRecord>\n}\n\nconst STATUSES = new Set<string>(['identified', 'doubtful', 'failed'])\n\nexport function emptyFingerprintStore(bankBuiltAt = ''): FingerprintDocument {\n return { version: 1, bankBuiltAt, records: {} }\n}\n\n/** \u8BB0\u5F55\u952E\u3002`\\u0000` \u5728\u6A21\u578B id \u4E0E\u4F9B\u5E94\u5546 id \u91CC\u90FD\u4E0D\u53EF\u80FD\u51FA\u73B0\u3002 */\nexport function recordKeyOf(provider: string, model: string): string {\n return `${provider}\\u0000${model}`\n}\n\nexport function fingerprintFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', 'fingerprint.json')\n}\n\nfunction finiteNumber(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback\n}\n\nfunction parseTop(raw: unknown): FingerprintTopEntry[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const out: FingerprintTopEntry[] = []\n for (const item of raw) {\n if (typeof item !== 'object' || item === null) continue\n const record = item as Record<string, unknown>\n const model = record['model']\n if (typeof model !== 'string' || model.length === 0) continue\n out.push({\n model,\n probability: finiteNumber(record['probability'], 0),\n similarity: finiteNumber(record['similarity'], 0),\n })\n if (out.length === 3) break\n }\n return out.length === 0 ? undefined : out\n}\n\n/**\n * Parse the per-question ledger. Never throws and never invents a question:\n * a malformed entry is dropped, and an array that ends up empty becomes\n * `undefined` (an old record with no ledger must not render as \"no questions\n * counted\"). `expected` and `parsed` are counts, so negatives are clamped to 0.\n */\nfunction parseChallenges(raw: unknown): FingerprintChallenge[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const out: FingerprintChallenge[] = []\n for (const item of raw) {\n if (typeof item !== 'object' || item === null) continue\n const entry = item as Record<string, unknown>\n const parsed: FingerprintChallenge = {\n index: Math.max(1, Math.trunc(finiteNumber(entry['index'], out.length + 1))),\n expected: Math.max(0, Math.trunc(finiteNumber(entry['expected'], 0))),\n parsed: Math.max(0, Math.trunc(finiteNumber(entry['parsed'], 0))),\n accepted: entry['accepted'] === true,\n }\n if (entry['skipped'] === true) parsed.skipped = true\n out.push(parsed)\n if (out.length === 3) break\n }\n return out.length === 0 ? undefined : out\n}\n\nfunction parseRecord(provider: string, model: string, raw: unknown): FingerprintRecord | undefined {\n if (typeof raw !== 'object' || raw === null) return undefined\n const record = raw as Record<string, unknown>\n const status = record['status']\n if (typeof status !== 'string' || !STATUSES.has(status)) return undefined\n const out: FingerprintRecord = {\n provider,\n model,\n status: status as FingerprintStatus,\n checkedAt: finiteNumber(record['checkedAt'], 0),\n usedOutputs: Math.max(0, Math.trunc(finiteNumber(record['usedOutputs'], 0))),\n }\n for (const key of ['prediction', 'predictionName', 'familyPrediction', 'error'] as const) {\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) out[key] = value\n }\n for (const key of ['probability', 'familyProbability'] as const) {\n const value = record[key]\n if (typeof value === 'number' && Number.isFinite(value)) out[key] = value\n }\n const top = parseTop(record['top'])\n if (top !== undefined) out.top = top\n const challenges = parseChallenges(record['challenges'])\n if (challenges !== undefined) out.challenges = challenges\n const calibration = record['calibration']\n if (typeof calibration === 'object' && calibration !== null) {\n const fields = calibration as Record<string, unknown>\n out.calibration = {\n queries: Math.trunc(finiteNumber(fields['queries'], 0)),\n cvAccuracy: finiteNumber(fields['cvAccuracy'], 0),\n }\n }\n const timing = record['timing']\n if (typeof timing === 'object' && timing !== null && !Array.isArray(timing)) {\n const fields = timing as Record<string, unknown>\n const parsed: FingerprintTiming = {}\n for (const key of ['firstTokenMs', 'durationMs', 'charsPerSecond'] as const) {\n const value = fields[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) parsed[key] = value\n }\n if (Object.keys(parsed).length > 0) out.timing = parsed\n }\n // \u5931\u8D25\u7684\u90A3\u6B21\u6CA1\u6709\u5F52\u5C5E\u7ED3\u8BBA\u53EF\u8C08\uFF1A`prediction` \u7B49\u5B57\u6BB5\u53EA\u5C5E\u4E8E identified / doubtful\u3002\n if (status === 'failed') {\n delete out.prediction\n delete out.predictionName\n delete out.probability\n delete out.familyPrediction\n delete out.familyProbability\n delete out.top\n delete out.calibration\n delete out.timing\n }\n return out\n}\n\n/**\n * \u89E3\u6790\u5DF2\u89E3\u7801\u7684\u6587\u6863\u3002\u6C38\u8FDC\u4E0D\u629B\u9519\uFF1A\u94F6\u884C\u6362\u4E86\u3001\u6587\u4EF6\u88AB\u624B\u6539\u574F\u3001\u6761\u76EE\u5F62\u72B6\u4E0D\u5BF9\uFF0C\n * \u4EE3\u4EF7\u6700\u591A\u662F\u90A3\u4E00\u6761\u88AB\u4E22\u6389\uFF0C\u4E0D\u4F1A\u8BA9\u7528\u6237\u4E22\u6389\u5168\u90E8\u5386\u53F2\u3002\n * @param raw - \u89E3\u7801\u540E\u7684 JSON \u503C\u3002\n * @param bankBuiltAt - \u5F53\u524D\u6307\u7EB9\u5E93\u7684 built_at\uFF1B\u5BF9\u4E0D\u4E0A\u5C31\u6574\u4F53\u89C6\u4E3A\u65E0\u5386\u53F2\u3002\n */\nexport function parseFingerprintStore(raw: unknown, bankBuiltAt = ''): FingerprintDocument {\n if (typeof raw !== 'object' || raw === null) return emptyFingerprintStore(bankBuiltAt)\n const root = raw as Record<string, unknown>\n if (root['bankBuiltAt'] !== undefined && root['bankBuiltAt'] !== bankBuiltAt) {\n return emptyFingerprintStore(bankBuiltAt)\n }\n const records = root['records']\n if (typeof records !== 'object' || records === null || Array.isArray(records)) {\n return emptyFingerprintStore(bankBuiltAt)\n }\n const out: Record<string, FingerprintRecord> = {}\n for (const [key, value] of Object.entries(records as Record<string, unknown>)) {\n const separator = key.indexOf('\\u0000')\n if (separator <= 0 || separator === key.length - 1) continue\n const provider = key.slice(0, separator)\n const model = key.slice(separator + 1)\n const record = parseRecord(provider, model, value)\n if (record !== undefined) out[key] = record\n }\n return { version: 1, bankBuiltAt, records: out }\n}\n\n/** \u8BFB\u7ED3\u679C\u5E93\uFF1B\u53EA\u6709\u6587\u4EF6\u4E0D\u5B58\u5728\u624D\u8FD4\u56DE\u7A7A\u5E93\u3002 */\nexport function readFingerprintStore(\n bankBuiltAt = '',\n file: string = fingerprintFilePath(),\n): FingerprintDocument {\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 emptyFingerprintStore(bankBuiltAt)\n }\n throw error\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n return emptyFingerprintStore(bankBuiltAt)\n }\n return parseFingerprintStore(raw, bankBuiltAt)\n}\n\n/** \u539F\u5B50\u5199\u5E93\u3002 */\nexport function writeFingerprintStore(\n document: FingerprintDocument,\n file: string = fingerprintFilePath(),\n): 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 // \u4E34\u65F6\u6587\u4EF6\u5C3D\u529B\u6E05\u7406\uFF1Brename \u7684\u5931\u8D25\u624D\u662F\u6B63\u4E8B\u3002\n }\n throw error\n }\n}\n\n/** \u4E00\u6B21\u8BFB-\u6539-\u5199\u3002\u8FD4\u56DE\u7684\u5C31\u662F\u843D\u76D8\u540E\u7684\u6587\u6863\u3002 */\nexport function updateFingerprintStore(\n mutate: (document: FingerprintDocument) => FingerprintDocument,\n bankBuiltAt = '',\n file: string = fingerprintFilePath(),\n): FingerprintDocument {\n const current = readFingerprintStore(bankBuiltAt, file)\n const next = mutate(current)\n writeFingerprintStore(next, file)\n return next\n}\n\n/** \u8986\u76D6\u6216\u65B0\u589E\u4E00\u6761\u8BB0\u5F55\u3002 */\nexport function withRecord(\n document: FingerprintDocument,\n record: FingerprintRecord,\n): FingerprintDocument {\n return {\n ...document,\n records: { ...document.records, [recordKeyOf(record.provider, record.model)]: record },\n }\n}\n\n/** \u5220\u6389\u4E00\u6761\u8BB0\u5F55\uFF08\u4F9B\u5E94\u5546\u6216\u6A21\u578B\u88AB\u5220\u6389\u65F6\u7528\uFF09\u3002 */\nexport function withoutRecord(\n document: FingerprintDocument,\n provider: string,\n model: string,\n): FingerprintDocument {\n const key = recordKeyOf(provider, model)\n if (document.records[key] === undefined) return document\n const records = { ...document.records }\n delete records[key]\n return { ...document, records }\n}\n\n/** \u4E00\u4E2A\u4F9B\u5E94\u5546\u4E0B\u7684\u5168\u90E8\u8BB0\u5F55\u3002 */\nexport function providerRecords(\n document: FingerprintDocument,\n provider: string,\n): FingerprintRecord[] {\n return Object.values(document.records).filter((record) => record.provider === provider)\n}\n", "// \u5224\u5B9A\u4E00\u6B21\u5F52\u5C5E\u7ED3\u8BBA\u7684\u7B49\u7EA7\uFF1A`identified` / `doubtful` / `failed`\u3002\n//\n// \u7EAF\u51FD\u6570\u3001\u96F6\u4F9D\u8D56\uFF0C\u5BA2\u6237\u7AEF\uFF08\u753B\u5FBD\u7AE0\uFF09\u548C\u5BBF\u4E3B\uFF08\u5199\u843D\u76D8\uFF09\u5171\u7528\u540C\u4E00\u4E2A\u5224\u636E \u2014\u2014\n// \u4E0D\u80FD\u8BA9\u300C\u663E\u793A\u7684\u7B49\u7EA7\u300D\u548C\u300C\u5B58\u4E0B\u6765\u7684\u7B49\u7EA7\u300D\u5404\u7B97\u4E00\u5957\u3002\n// \u89C1 docs/fingerprint-design.md \u00A74.3\u3002\n\nimport type { AttributionResult, ResultRow } from './core.js'\n\n/** \u843D\u76D8\u7684\u4E09\u79CD\u72B6\u6001\u3002`running` \u4E0D\u843D\u76D8\uFF0C\u53EA\u6D3B\u5728\u5BA2\u6237\u7AEF runner \u91CC\u3002 */\nexport type FingerprintStatus = 'identified' | 'doubtful' | 'failed'\n\n/**\n * \u68C0\u6D4B\u7684\u8017\u65F6\u753B\u50CF\uFF08\u53EF\u9009\uFF09\uFF1A\u7ED9\u7ED3\u679C\u5361\u4E00\u53E5\u300C\u6162\u5728\u54EA\u300D\u3002\u53EA\u6536\u7EDF\u8BA1\u91CF \u2014\u2014 \u9996 token\n * \u7B49\u5F85\u3001\u6574\u6B21\u5899\u949F\u3001\u6309\u300C\u603B\u65F6\u957F \u2212 \u9996 token \u7B49\u5F85\u300D\u6298\u51FA\u7684\u5410\u5B57\u901F\u5EA6\uFF1B\u539F\u59CB\u6587\u672C\n * \u4ECE\u4E0D\u843D\u76D8\uFF08design \u00A74.2\uFF09\u3002\n */\nexport interface FingerprintTiming {\n /** \u6709\u6548\u56DE\u7B54\u91CC\u6700\u6162\u7684\u9996 token \u7B49\u5F85\uFF0C\u6BEB\u79D2\u3002 */\n firstTokenMs?: number\n /** \u6709\u6548\u56DE\u7B54\u91CC\u6700\u6162\u7684\u6574\u9898\u8017\u65F6\uFF08\u5899\u949F \u2248 \u7528\u6237\u7B49\u7684\u65F6\u95F4\uFF09\uFF0C\u6BEB\u79D2\u3002 */\n durationMs?: number\n /** \u6709\u6548\u56DE\u7B54\u5408\u8BA1\u7684\u53EF\u89C1\u5B57\u7B26 \u00F7 \u5408\u8BA1\u7EAF\u5410\u5B57\u65F6\u957F\uFF0C\u5B57\u7B26/\u79D2\u3002 */\n charsPerSecond?: number\n}\n\n/** \u7ED3\u679C\u5361\u300C\u524D\u4E09\u5019\u9009\u300D\u91CC\u7684\u4E00\u6761\u3002 */\nexport interface FingerprintTopEntry {\n model: string\n probability: number\n similarity: number\n}\n\n/**\n * \u7ED3\u679C\u5361\u300C\u9010\u9898\u300D\u90A3\u4E00\u884C\u91CC\u7684\u4E00\u9897\u836F\u4E38\uFF1A\u4E00\u9053\u9898\u95EE\u4E86\u591A\u5C11\u3001\u7B54\u56DE\u6765\u591A\u5C11\u3001\u7B97\u4E0D\u7B97\u6570\u3002\n *\n * \u4E3A\u4EC0\u4E48\u843D\u76D8\uFF1A`usedOutputs` \u53EA\u8BF4\u300C\u4E09\u9898\u91CC\u7B97\u4E86\u51E0\u9898\u300D\uFF0C\u8BF4\u4E0D\u51FA\u662F\u54EA\u4E00\u9898\u4E0D\u7B97 \u2014\u2014\n * \u800C\u300C\u4E3A\u4EC0\u4E48\u53EA\u56DE\u7B54\u4E86\u90E8\u5206\u9898\u76EE\u300D\u6B63\u662F\u7528\u6237\u770B\u7740 `2 / 3 \u9898` \u60F3\u95EE\u7684\u90A3\u53E5\u8BDD\u3002\u9010\u9898\u7684\n * \u671F\u671B\u6570\u4E0E\u89E3\u6790\u6570\u90FD\u662F\u7EDF\u8BA1\u91CF\uFF0C\u4E0D\u6D89\u53CA\u4F5C\u7B54\u6587\u672C\uFF08design \u00A74.2\uFF09\u3002\n */\nexport interface FingerprintChallenge {\n /** \u9898\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB\uFF0C\u4E0E\u9898\u5E72\u53D1\u51FA\u987A\u5E8F\u4E00\u81F4\u3002 */\n index: number\n /** \u8FD9\u9053\u9898\u8981\u6C42\u51E0\u4E2A\u6574\u6570\uFF08292\u2013332\uFF09\u3002 */\n expected: number\n /** \u89E3\u6790\u51FA\u6765\u7684\u6574\u6570\u4E2A\u6570\uFF1B\u62D2\u7B54\u3001\u62A5\u9519\u3001\u88AB\u6390\u65AD\u90FD\u662F 0\u3002 */\n parsed: number\n /** \u662F\u5426\u8FBE\u5230\u4E86\u8BA1\u5165\u95E8\u69DB\uFF08`max(80, ceil(expected * 0.55))`\uFF09\u3002 */\n accepted: boolean\n /**\n * \u4E24\u9898\u65E9\u505C\u65F6\u88AB\u4E3B\u52A8\u6390\u6389\u7684\u90A3\u9053\u9898\u3002\u5B83\u6CA1\u7B54\u4E0D\u662F\u56E0\u4E3A\u7B54\u574F\u4E86 \u2014\u2014 \u836F\u4E38\u4E0A\u8981\u8BF4\u7684\n * \u662F\u300C\u65E9\u505C\u8DF3\u8FC7\u300D\uFF0C\u4E0D\u662F\u300C\u672A\u8BA1\u5165\u300D\uFF0C\u5426\u5219\u7528\u6237\u4F1A\u53BB\u8FFD\u4E00\u4E2A\u4E0D\u5B58\u5728\u7684\u5931\u8D25\u3002\n */\n skipped?: boolean\n}\n\n/**\n * \u4E00\u4E2A\u6A21\u578B\u7684\u4E00\u6B21\u68C0\u6D4B\u7ED3\u8BBA\uFF0C\u4E5F\u662F\u843D\u76D8\u7684\u90A3\u4E00\u884C\u3002\n *\n * \u8FD9\u4E2A\u5F62\u72B6\u653E\u5728\u8FD9\u91CC\u800C\u4E0D\u662F store \u91CC\uFF0C\u662F\u56E0\u4E3A**\u524D\u7AEF\u753B\u5FBD\u7AE0\u8981\u7528\u5B83**\uFF1Astore \u662F\n * Node-only\uFF08`node:fs`\uFF09\uFF0C\u6D4F\u89C8\u5668\u53EA\u80FD\u4ECE\u7EAF\u6A21\u5757\u53D6\u5F62\u72B6\u3002\u5224\u636E\u3001\u7ED3\u679C\u6761\u76EE\u3001\u7ED3\u679C\u884C\n * \u4E09\u8005\u5C5E\u4E8E\u540C\u4E00\u4EF6\u4E8B\u7684\u4E09\u4E2A\u9762\uFF0C\u62C6\u5F00\u4F1A\u5404\u957F\u5404\u7684\u3002\n */\nexport interface FingerprintRecord {\n provider: string\n model: string\n status: FingerprintStatus\n checkedAt: number\n usedOutputs: number\n /** \u4EC5 identified / doubtful \u6709\u503C\u3002 */\n prediction?: string\n predictionName?: string\n probability?: number\n familyPrediction?: string\n familyProbability?: number\n top?: FingerprintTopEntry[]\n /** \u9010\u9898\u8BB0\u8D26\uFF1A\u54EA\u51E0\u9898\u7B97\u8FDB\u53BB\u4E86\u3001\u54EA\u9898\u6CA1\u7B97\u3002\u65E7\u8BB0\u5F55\u6CA1\u6709\u8FD9\u4E2A\u5B57\u6BB5\u3002 */\n challenges?: FingerprintChallenge[]\n calibration?: { queries: number; cvAccuracy: number }\n /** \u672C\u6B21\u68C0\u6D4B\u7684\u8017\u65F6\u753B\u50CF\uFF0C\u68C0\u6D4B\u5931\u8D25\u65F6\u6CA1\u6709\u610F\u4E49\uFF0C\u4E0D\u843D\u76D8\u3002 */\n timing?: FingerprintTiming\n /** \u4EC5 failed \u6709\u503C\uFF0C\u9762\u5411\u7528\u6237\u7684\u5931\u8D25\u539F\u56E0\u3002 */\n error?: string\n}\n\n/**\n * `identified` \u7684\u6982\u7387\u4E0B\u754C\u3002\n *\n * \u5E93\u91CC 18 \u4E2A\u5019\u9009\u7684\u5747\u5300\u5148\u9A8C\u662F 5.6%\uFF0C0.6 \u5DF2\u7ECF\u662F\u538B\u5012\u6027\u7684\uFF1B\u4F4E\u4E8E\u5B83\u5C31\u8BF4\u660E\u51E0\u4E2A\u5019\u9009\n * \u54AC\u5F97\u5F88\u8FD1\uFF0C\u8BF4\u300C\u50CF\u300D\u4E0D\u8D1F\u8D23\u4EFB\u3002\n */\nexport const IDENTIFIED_THRESHOLD = 0.6\n\n/** \u51FA\u4E00\u4E2A\u786E\u5B9A\u7ED3\u8BBA\u9700\u8981\u7684\u5B8C\u6574\u9898\u6570\u3002 */\nexport const FULL_RUN_QUERIES = 3\n\n/**\n * \u4E24\u9898\u65E9\u505C\u5224 `identified` \u7684\u6982\u7387\u4E0B\u754C\u3002\n *\n * \u94F6\u884C\u81EA\u5E26 2 \u9898\u6821\u51C6\uFF1A\u4EA4\u53C9\u9A8C\u8BC1\u51C6\u786E\u7387 99.7%\uFF08646/648\uFF09\uFF0Cbeta\u224812 \u8BA9\u6982\u7387\u5206\u5E03\n * \u975E\u5E38\u5C16\u30020.9 \u5728\u90A3\u5957\u6821\u51C6\u4E0B\u4ECD\u662F\u4FDD\u5B88\u95E8\u69DB \u2014\u2014 \u6C60\u5316\u6982\u7387\u5230\u4E0D\u4E86 0.9 \u5C31\u7EE7\u7EED\u7B49\u7B2C\u4E09\n * \u9898\uFF0C\u8D70\u4E09\u9898\u7684\u5B8C\u6574\u5224\u636E\uFF0C\u6240\u4EE5\u65E9\u505C\u53EA\u4F1A\u63D0\u524D\u3001\u4E0D\u4F1A\u653E\u5BBD\u3002\n */\nexport const EARLY_IDENTIFIED_PROBABILITY = 0.9\n\n/** \u65E9\u505C\u6700\u5C11\u9700\u8981\u7684\u6709\u6548\u9898\u6570\uFF08\u4E24\u9898\uFF09\u3002 */\nexport const EARLY_IDENTIFIED_QUERIES = 2\n\n/**\n * \u53D6\u6982\u7387\u6700\u9AD8\u7684\u524D\u51E0\u540D\u5019\u9009\uFF0C\u4F9B\u7ED3\u679C\u5361\u753B\u6761\u5F62\u3002\n * @param rows - \u5DF2\u6309\u6982\u7387\u964D\u5E8F\u6392\u597D\u7684\u5019\u9009\u3002\n * @param limit - \u53D6\u51E0\u540D\uFF0C\u9ED8\u8BA4 3\u3002\n * @returns \u524D `limit` \u6761\u7684\u6A21\u578B id\u3001\u6982\u7387\u3001\u76F8\u4F3C\u5EA6\u3002\n */\nexport function topEntriesOf(rows: readonly ResultRow[], limit = 3): FingerprintTopEntry[] {\n return rows.slice(0, limit).map(row => ({\n model: row.model,\n probability: row.probability,\n similarity: row.profile_similarity,\n }))\n}\n\n/**\n * \u628A\u4E00\u6B21\u5F52\u5C5E\u7ED3\u8BBA\u5B9A\u7EA7\u3002\n *\n * \u4E09\u9053\u95F8\uFF1A\u6982\u7387\u5FC5\u987B\u591F\u9AD8\uFF0C\u9898\u6570\u5FC5\u987B\u591F\u591A\uFF0C\u591A\u5230\u54EA\u4E00\u6863\u5C31\u7528\u54EA\u4E00\u6863\u7684\u95E8\u69DB\u3002\u4E09\u9898\u5168\u6709\n * \u6548\u8D70 0.6\uFF1B\u4E24\u9898\u6709\u6548\u8D70 0.9\uFF08\u65E9\u505C\u6216\u7B2C\u4E09\u9898\u610F\u5916\u4F5C\u5E9F\u65F6\uFF0C\u94F6\u884C 2 \u9898\u6821\u51C6\u7684\u4EA4\u53C9\u9A8C\u8BC1\n * \u51C6\u786E\u7387 99.7% \u6491\u5F97\u8D77\uFF0C\u4F46\u95E8\u69DB\u76F8\u5E94\u6536\u7D27\uFF09\uFF1B1 \u9898\u7684\u4EA4\u53C9\u9A8C\u8BC1\u51C6\u786E\u7387\u53EA\u6709 96.3%\uFF0C\n * \u6491\u4E0D\u8D77\u4EFB\u4F55\u786E\u5B9A\u7ED3\u8BBA \u2014\u2014 \u4E00\u5F8B `doubtful`\uFF0C\u54EA\u6015\u90A3\u4E00\u9898\u7684\u6982\u7387\u662F 0.99\u3002\n *\n * @param attribution - `analyzeGlobalOutputs` \u7684\u7ED3\u679C\uFF1B\u5931\u8D25\u65F6\u4F20 null\u3002\n * @param usedOutputs - \u6709\u6548\u9898\u6570\u3002\n * @returns \u843D\u76D8\u4E0E\u753B\u5FBD\u7AE0\u5171\u7528\u7684\u72B6\u6001\u3002\n */\nexport function statusOf(\n attribution: AttributionResult | null,\n usedOutputs: number,\n): FingerprintStatus {\n if (attribution === null) return 'failed'\n if (usedOutputs >= FULL_RUN_QUERIES) {\n return attribution.probability >= IDENTIFIED_THRESHOLD ? 'identified' : 'doubtful'\n }\n if (usedOutputs >= EARLY_IDENTIFIED_QUERIES) {\n return attribution.probability >= EARLY_IDENTIFIED_PROBABILITY ? 'identified' : 'doubtful'\n }\n return 'doubtful'\n}\n"],
5
- "mappings": ";AA0BA,OAAO,YAAY;;;ACnBZ,IAAM,YAAY;AAGlB,IAAM,aAAa;AAEnB,IAAM,YAAY;AAelB,IAAM,oBAAoB;AAmB1B,IAAM,iBAAiB;AAavB,IAAM,eAAe;AASrB,IAAM,uBAAuB;AAS7B,IAAM,sBAAsB;AAY5B,IAAM,mBAAmB;AAUzB,IAAM,aAAa;AAOnB,IAAM,aAAa;AAGnB,IAAM,WAAW;AASjB,IAAM,eAAe;AAOrB,IAAM,qB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kBAAI,SAAS,KAAK,UAAU,CAAC,GAAG;AAC9B,sBAAM,MAAM,KAAK,UAAU;AAC3B,uBAAO;AAAA,kBACL,GAAG;AAAA,kBACH,UAAU;AAAA,oBACR,MAAM,OAAO,IAAI,MAAM,MAAM,YAAY,IAAI,MAAM,EAAE,SAAS,IAAI,IAAI,MAAM,IAAI,KAAK,SAAS;AAAA,oBAC9F,SAAS,OAAO,IAAI,SAAS,MAAM,YAAY,IAAI,SAAS,EAAE,SAAS,IAAI,IAAI,SAAS,IAAI,KAAK,SAAS;AAAA,oBAC1G,GAAG,OAAO,IAAI,GAAG,MAAM,YAAY,OAAO,UAAU,IAAI,GAAG,CAAC,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,IAAI,IAAI,GAAG,GAAG,EAAE,IAAI,KAAK,SAAS;AAAA,oBACxH,WAAW,OAAO,IAAI,WAAW,MAAM,YAAY,IAAI,WAAW,KAAK,MACnE,KAAK,IAAI,IAAI,WAAW,GAAG,IAAS,IACpC,KAAK,SAAS;AAAA,kBACpB;AAAA,gBACF;AAAA,cACF;AAKA,qBAAO;AAAA,YACT,CAAC;AACD,+BAAmB;AAGnB,gBAAI;AACF,mCAAqB;AAAA,YACvB,QAAQ;AAAA,YAER;AACA,qBAAS,KAAK,KAAK,EAAE,IAAI,KAAK,CAAC;AAAA,UACjC,SAAS,OAAO;AACd,qBAAS,KAAK,KAAK,EAAE,IAAI,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;AAAA,UACjG;AAAA,QACF;AAAA,MACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
6
- "names": ["name", "label", "state", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "join", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "join", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "name", "normalized", "name", "name", "norm", "compat", "normalized", "registry", "name", "registry", "normalize", "normalized", "active", "name", "readFileSync", "dirname", "join", "resolve", "require", "name", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "join", "isRecord", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "label", "mkdirSync", "readFileSync", "writeFileSync", "existsSync", "dirname", "join", "resolve", "resolve", "classifyFailure", "name", "join", "existsSync", "mkdirSync", "resolve", "dirname", "readFileSync", "body", "writeFileSync", "name", "existsSync", "mkdirSync", "readFileSync", "readdirSync", "statSync", "writeFileSync", "dirname", "join", "join", "existsSync", "name", "readdirSync", "statSync", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "name", "existsSync", "readFileSync", "dirname", "join", "dirname", "join", "existsSync", "readFileSync", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "bankBuiltAt", "join", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "resolve", "name", "resolved", "cached", "records", "ref", "model", "config"]
3
+ "sources": ["../src/index.ts", "../src/constants.ts", "../src/key-refs.ts", "../src/key-index.ts", "../src/key-mutation-queue.ts", "../src/key-route-core.ts", "../src/key-serves.ts", "../src/order-store.ts", "../src/camouflage-store.ts", "../src/camouflage.ts", "../src/multi-key-listing.ts", "../src/shared.ts", "../src/headers-core.ts", "../src/listing.ts", "../src/key-probe.ts", "../src/discovery-merge.ts", "../src/knowledge.ts", "../src/guard.ts", "../src/balance.ts", "../src/headers-fetch.ts", "../src/headers-pi-ai.ts", "../src/headers-conflict.ts", "../src/image/config.ts", "../src/image/sizes.ts", "../src/image/generate.ts", "../src/image/deadline.ts", "../src/image/command.ts", "../src/image/tool.ts", "../src/image/legacy-cleanup.ts", "../src/autofill.ts", "../src/fingerprint/bank.ts", "../src/fingerprint/core.ts", "../src/fingerprint/random.ts", "../src/fingerprint/challenges.ts", "../src/fingerprint/eligibility.ts", "../src/fingerprint/run.ts", "../src/fingerprint/store.ts", "../src/fingerprint/verdict.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 BALANCE_PATH,\n CAMOUFLAGE_PATH,\n DIAG_PATH,\n FINGERPRINT_PATH,\n HEADERS_CONFIG_PATH,\n IMAGE_CONFIG_PATH,\n KEY_INDEX_PATH,\n ORDER_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 routeBalanceOf,\n routeEndpointsOf,\n updateKeyIndex,\n withKeyAlias,\n withKeyAutoScope,\n withKeyDisabled,\n withKeyEntry,\n withKeyModels,\n withKeyProtocol,\n withRouteBalance,\n withRouteEndpoints,\n withoutKeyEntry,\n writeKeyIndex,\n type KeyIndexEntry,\n} from './key-index.js'\nimport { acquireKeyMutation } from './key-mutation-queue.js'\nimport { keyRest, keysForModel, restKeyOf, type KeyCandidate, type ServingKnowledge } from './key-route-core.js'\nimport { keyServesFilePath, readKeyServes, servesOfRoute, withServes, withoutServes, writeKeyServes, type KeyServesDocument } from './key-serves.js'\nimport { commitUiOrderGuarded, readUiOrder, uiOrderFilePath } from './order-store.js'\nimport { readCamouflage, setRouteCamouflage } from './camouflage-store.js'\nimport { CAMOUFLAGE_PRESETS, isCamouflagePreset } from './camouflage.js'\nimport { collectKeyListings, mergeKeyListings } from './multi-key-listing.js'\nimport { listingTargetsOf, type ProbeTarget } from './key-probe.js'\nimport { probeListing } from './discovery-merge.js'\nimport { suggestEfforts } from './knowledge.js'\nimport type { ReasoningEfforts } from './knowledge.js'\nimport { resolveGuardEffort } from './guard.js'\nimport { parseBalancePayload } from './balance.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 redactUrlSecrets,\n type ListedModel,\n} from './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// Image generation (\u751F\u56FE): one config file, one generation core behind two\n// entries \u2014 the `generate_image` native tool (\u4E3B\u901A\u9053) and the /\u751F\u56FE host\n// command \u2014 plus the boot-time removal of the retired MCP patch entry.\nimport {\n deriveImageSeeds,\n emptyImageConfig,\n readImageConfig,\n syncImageConfig,\n updateImageConfig,\n type ImageConfig,\n} from './image/config.js'\nimport { generateImage, type GenerateDeps } from './image/generate.js'\nimport { registerImagegenCommand, type CommandsServiceLike } from './image/command.js'\nimport { imageToolHint, registerGenerateImageTool } from './image/tool.js'\nimport { removeLegacyImageMcpPatch } from './image/legacy-cleanup.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, buildCompatCleanupPatch, stripNewCompatKeysDeep } from './autofill.js'\n// Model fingerprint attribution (ModelTrace). The math is a pure port of\n// upstream `fingerprint-core.js` over a vendored bank; only the routing below\n// touches the llm service, so the whole attribution path stays unit-testable.\nimport { bankBuiltAt, loadBankSync, summarizeBank } from './fingerprint/bank.js'\nimport { generateChallenges } from './fingerprint/challenges.js'\nimport { analyzeGlobalOutputs, NO_USABLE_OUTPUT, type AttributionResult } from './fingerprint/core.js'\nimport { isEligibleModel } from './fingerprint/eligibility.js'\nimport { runProbe, type ProbeOutcome, type ProbeRunResult } from './fingerprint/run.js'\nimport {\n fingerprintFilePath,\n providerRecords,\n readFingerprintStore,\n updateFingerprintStore,\n withRecord,\n withoutRecord,\n type FingerprintRecord,\n type FingerprintChallenge,\n type FingerprintTiming,\n} from './fingerprint/store.js'\nimport { statusOf, topEntriesOf, EARLY_IDENTIFIED_PROBABILITY } from './fingerprint/verdict.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/** Legacy schema default only; absence no longer authorizes key deletion. */\nconst ROUTE_SWEEP_GRACE_MS = 30_000\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 * Balance fetch budget. One read per provider per page opening \u2014 but the read\n * runs on the host's web server, and a dead balance endpoint must not hold a\n * socket (and the page's chip, which spins until the answer) for the better\n * part of half a minute. A billing API that needs more than 8s will not get\n * faster on a retry either; the chip keeps the last reading meanwhile.\n */\nconst BALANCE_TIMEOUT_MS = 8_000\n\n/**\n * Bound on one credential-store IPC a KEY MUTATION waits on. The store is\n * local, so an answer normally lands in milliseconds \u2014 but a stalled store\n * (a hung keychain daemon, a wedged host service) must not hang the manager's\n * own route for ever: a mutation that cannot be pre-checked within this\n * budget refuses with a clear message the user can retry, and a forget that\n * outlives it rolls the metadata back the same way a refused forget does.\n */\nconst CREDENTIAL_IPC_BUDGET_MS = 10_000\n\n/**\n * Per-challenge budget for one fingerprint probe. Deliberately NOT derived from\n * `probeTimeoutMs`: that one bounds a tiny /models read (15s default), while a\n * challenge asks for ~300 integers and the answer alone is several hundred\n * tokens. A provider that cannot answer in two minutes is a `failed` row, not a\n * reason to widen the listing probe.\n */\nconst FINGERPRINT_CHALLENGE_TIMEOUT_MS = 120_000\n\n/**\n * Fold the accepted challenges' timings into one picture for the result card:\n * the wall clock and first-token wait of the SLOWEST accepted challenge (that\n * is what the user actually waited for), plus the characters-per-second the\n * provider pushed once text started flowing. Throughput counts only the\n * generation window (total minus the first-token wait) so a long thinking\n * preamble shows up as a first-token wait, not as slow streaming. Pure\n * statistics only \u2014 the answer text itself is never stored (design \u00A74.2).\n */\nfunction fingerprintTimingOf(outcomes: readonly ProbeOutcome[]): FingerprintTiming | undefined {\n const accepted = outcomes.filter(outcome => outcome.ok && typeof outcome.durationMs === 'number')\n if (accepted.length === 0) return undefined\n const durationMs = Math.max(...accepted.map(outcome => outcome.durationMs ?? 0))\n const firstTokenMs = Math.max(...accepted.map(outcome => outcome.firstTokenMs ?? outcome.durationMs ?? 0))\n let characters = 0\n let generatingMs = 0\n for (const outcome of accepted) {\n const total = outcome.durationMs ?? 0\n const first = Math.min(outcome.firstTokenMs ?? total, total)\n const generating = total - first\n if (generating > 0) {\n characters += outcome.text.length\n generatingMs += generating\n }\n }\n return {\n durationMs,\n ...(firstTokenMs > 0 ? { firstTokenMs } : {}),\n ...(generatingMs > 0 ? { charsPerSecond: characters / (generatingMs / 1000) } : {}),\n }\n}\n\n/**\n * Fold each challenge's outcome into the per-question ledger the result card\n * draws as pills: how many integers this one asked for, how many came back,\n * and whether that counted. The accepted flag is NOT recomputed here \u2014 it is\n * read from the attribution's own diagnostics when there is one, so the pill\n * and the verdict can never disagree about which answers were pooled. Only the\n * floor rule is duplicated, and only for the no-attribution case (every call\n * died), where there is nothing to read.\n *\n * `diagnostics` is indexed by position in `run.outputs`, which holds ONLY the\n * challenges that answered \u2014 so a dead challenge shifts every later entry by\n * one. The running `pooled` counter is what keeps a pill from borrowing its\n * neighbour's number.\n *\n * `skipped` marks the challenge an early exit aborted: it never answered, and\n * calling that \"\u672A\u8BA1\u5165\" would send the user chasing a failure that did not\n * happen. Statistics only \u2014 no answer text (design \u00A74.2).\n */\nfunction fingerprintChallengesOf(\n outcomes: readonly ProbeOutcome[],\n attribution: AttributionResult | null,\n): FingerprintChallenge[] {\n const diagnostics = attribution?.diagnostics\n let pooled = -1\n return outcomes.map((outcome, position) => {\n if (outcome.ok) pooled += 1\n const diagnostic = outcome.ok ? diagnostics?.[pooled] : undefined\n const parsed = diagnostic?.parsed_numbers ?? 0\n return {\n index: position + 1,\n expected: outcome.expectedCount,\n parsed,\n accepted: diagnostic?.accepted ?? false,\n ...(outcome.skipped === true ? { skipped: true } : {}),\n }\n })\n}\n\n/**\n * How long ONE raw listing probe may take while Auto-adapt is waiting on it.\n * The wire read it bounds is one tiny `/models` read per endpoint family; a\n * gateway slower than this still answers the next attempt, and the cached\n * answer keeps a whole pass from re-reading it per model.\n */\nconst LISTING_PROBE_BUDGET_MS = 6_000\n\n/**\n * How long a raw probe answer is reused before the next request re-reads it.\n * Auto-adapt asks per model; a bounded window keeps those repeats off the wire\n * without ever pinning a stale listing on the user.\n */\nconst LISTING_CACHE_MS = 30_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 /** Deprecated compatibility field; absent providers retain their keys. */\n routeSweepGraceMs?: 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 routeSweepGraceMs: Schema.natural().default(ROUTE_SWEEP_GRACE_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 /** Manual assignment, restricted to the models this route has added. */\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 = Object.hasOwn(providers, route) ? providers[route] : undefined\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 manual assignments, 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 const scopes = Object.create(null) as Record<string, readonly RouteKeyScope[]>\n let document: ReturnType<typeof readKeyIndex>\n try {\n document = readKeyIndex(keyIndexFilePath())\n } catch {\n return scopes\n }\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 = routeEndpointsOf(document, 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 and Anthropic), 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/** A request may answer before IPC settles, but its index lease must not. */\nclass PendingCredentialMutations {\n private readonly pending = new Set<Promise<void>>()\n\n track<T>(operation: Promise<T>): Promise<T> {\n // Handle both outcomes here too: a late rejection after an HTTP timeout is\n // observed, and a never-settling store deliberately keeps the lease closed.\n const settled: Promise<void> = operation.then(\n () => { this.pending.delete(settled) },\n () => { this.pending.delete(settled) },\n )\n this.pending.add(settled)\n return operation\n }\n\n releaseAfterSettled(release: () => void): void {\n if (this.pending.size === 0) release()\n else void Promise.all([...this.pending]).then(release, release)\n }\n}\n\n/** The HTTP budget is not cancellation of the tracked credential mutation. */\nasync function awaitCredentialMutation<T>(\n operation: Promise<T>,\n pending: PendingCredentialMutations,\n budgetMs: number,\n): Promise<T> {\n pending.track(operation)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(\n `the credential store did not answer within ${Math.round(budgetMs / 1000)}s; the write result is unknown until it settles`,\n )), budgetMs)\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\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 pending: PendingCredentialMutations,\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 invalidateCredentialDisplay(credentials, ref)\n try {\n const operation = Promise.resolve().then(() => set.call(credentials, ref, value))\n .finally(() => { invalidateCredentialDisplay(credentials, ref) })\n const answer = await awaitCredentialMutation(operation, pending, CREDENTIAL_IPC_BUDGET_MS)\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 } finally {\n invalidateCredentialDisplay(credentials, ref)\n }\n}\n\n/**\n * Forget one reference's value; the refusal text, or undefined. A timeout is\n * uncertain, not a cancelled unset: rollback retains metadata, while the\n * request's lease stays held until the underlying operation actually settles.\n */\nasync function forgetCredential(\n credentials: CredentialsService | undefined,\n ref: string,\n pending: PendingCredentialMutations,\n budgetMs: number = CREDENTIAL_IPC_BUDGET_MS,\n): 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 invalidateCredentialDisplay(credentials, ref)\n try {\n const operation = Promise.resolve().then(() => unset.call(credentials, ref))\n .finally(() => { invalidateCredentialDisplay(credentials, ref) })\n const answer = await awaitCredentialMutation(operation, pending, budgetMs)\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 } finally {\n invalidateCredentialDisplay(credentials, ref)\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/**\n * Whether the store positively holds NOTHING under one reference.\n *\n * Both faces must agree: `describe` says unconfigured AND no value could be\n * read. A `configured: false` contradicted by a readable value is a stale\n * metadata face, not an empty credential, and an absent entry means the store\n * could not answer at all \u2014 unknown, never empty. Callers that must not\n * overwrite a key lean on exactly this distinction.\n * @param fact - what {@link credentialFacts} answered for the reference.\n * @returns true only for a confirmed empty reference.\n */\nfunction holdsNothing(fact: CredentialFacts | undefined): boolean {\n return fact !== undefined && fact.configured === false && fact.masked === 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\nconst CREDENTIAL_DISPLAY_TTL_MS = 5_000\nconst CREDENTIAL_DISPLAY_MAX_REFS = 512\n\n/** Only display facts live here; secrets and mutation preconditions never do. */\ninterface CredentialDisplayRead {\n expiresAt: number\n resolved?: CredentialFacts\n described?: boolean\n settled: Promise<void>\n}\nconst credentialDisplayReads = new WeakMap<CredentialsService, Map<string, CredentialDisplayRead>>()\n\nfunction invalidateCredentialDisplay(credentials: CredentialsService | undefined, ref: string): void {\n if (credentials !== undefined) credentialDisplayReads.get(credentials)?.delete(ref)\n}\n\n/** Short-lived per-ref singleflight for list previews, not authoritative reads. */\nasync function displayCredentialFacts(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n budgetMs: number,\n): Promise<Record<string, CredentialFacts>> {\n if (credentials === undefined || refs.length === 0) return {}\n let cache = credentialDisplayReads.get(credentials)\n if (cache === undefined) {\n cache = new Map()\n credentialDisplayReads.set(credentials, cache)\n }\n const now = Date.now()\n // Expire stalled flights too: a broken IPC read must not pin a ref forever.\n for (const [ref, read] of cache) if (read.expiresAt <= now) cache.delete(ref)\n const selected = new Map<string, CredentialDisplayRead>()\n const missing: string[] = []\n for (const ref of new Set(refs)) {\n let read = cache.get(ref)\n if (read === undefined) {\n read = { expiresAt: now + CREDENTIAL_DISPLAY_TTL_MS, settled: Promise.resolve() }\n cache.set(ref, read)\n missing.push(ref)\n }\n selected.set(ref, read)\n }\n // Keep describe batched while overlapping lists share each reference's flight.\n const described = missing.length === 0 || typeof credentials.describe !== 'function'\n ? Promise.resolve(undefined)\n : (async () => {\n try {\n const answer = await credentials.describe?.(missing)\n return isRefusal(answer) ? undefined : describeRecords(answer)\n } catch {\n return undefined\n }\n })()\n for (const ref of missing) {\n const read = selected.get(ref)!\n const resolved = (async (): Promise<boolean> => {\n try {\n const value = await resolveCredential(credentials, ref)\n const masked = value === undefined ? undefined : maskKeyValue(value)\n read.resolved = masked === undefined || masked.length === 0\n ? { configured: value !== undefined }\n : { configured: true, masked }\n return true\n } catch {\n return false\n }\n })()\n const metadata = described.then(records => {\n const info = records?.[ref]\n if (isRecord(info) && typeof info['configured'] === 'boolean') read.described = info['configured']\n return typeof credentials.describe !== 'function' || read.described !== undefined\n })\n read.settled = Promise.all([resolved, metadata]).then(([resolvedOK, describedOK]) => {\n // Delete/replacement invalidates the identity, so an old flight cannot\n // repopulate a ref after a credential write (including a rollback).\n if (cache.get(ref) !== read) return\n // Partial answers can paint this response but failures are never cached.\n read.expiresAt = resolvedOK && describedOK ? Date.now() + CREDENTIAL_DISPLAY_TTL_MS : 0\n })\n }\n while (cache.size > CREDENTIAL_DISPLAY_MAX_REFS) {\n const oldest = cache.keys().next().value\n if (oldest === undefined) break\n cache.delete(oldest)\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.all([...selected.values()].map(read => read.settled)),\n new Promise<void>(resolve => { timer = setTimeout(resolve, budgetMs) }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n const out: Record<string, CredentialFacts> = {}\n for (const [ref, read] of selected) {\n if (cache.get(ref) !== read) continue\n const configured = read.described ?? read.resolved?.configured\n if (configured === undefined) continue\n out[ref] = read.resolved?.masked === undefined ? { configured } : { configured, masked: read.resolved.masked }\n }\n return out\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 budgetMs?: number,\n): Promise<Record<string, CredentialFacts>> {\n const described: Record<string, boolean> = {}\n const resolvedFacts: Record<string, CredentialFacts> = {}\n if (credentials === undefined || refs.length === 0) return {}\n // Metadata and preview reads are independent IPC calls. Neither a slow\n // describe nor an earlier reference should hold every remaining row up.\n const reads: Promise<void>[] = refs.map(async ref => {\n try {\n const value = await resolveCredential(credentials, ref)\n const masked = value === undefined ? undefined : maskKeyValue(value)\n resolvedFacts[ref] = masked === undefined || masked.length === 0\n ? { configured: value !== undefined }\n : { configured: true, masked }\n } catch {\n // Unavailable is unknown, never an empty credential.\n }\n })\n if (typeof credentials.describe === 'function') {\n reads.push((async () => {\n try {\n const answer = await credentials.describe?.([...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') described[ref] = info['configured']\n }\n } catch {\n // Resolved previews can still answer without describe.\n }\n })())\n }\n const settled = Promise.all(reads)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n // Only display callers use this bound; mutation preconditions still wait\n // for an authoritative answer and fail closed when the store cannot read.\n if (budgetMs === undefined) await settled\n else await Promise.race([settled, new Promise<void>(resolve => { timer = setTimeout(resolve, budgetMs) })])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n const out: Record<string, CredentialFacts> = {}\n for (const ref of refs) {\n const fact = resolvedFacts[ref]\n const configured = described[ref] ?? fact?.configured\n if (configured === undefined) continue\n out[ref] = fact?.masked === undefined ? { configured } : { configured, masked: fact.masked }\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. A mutation\n * precondition passes a budget: a store that cannot answer within it leaves\n * the reference out of the map, which every mutation reads as \"unknown\" and\n * refuses \u2014 fail closed, but bounded, instead of hanging the manager route.\n */\nasync function credentialConfigured(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n budgetMs?: number,\n): Promise<Record<string, boolean>> {\n const facts = await credentialFacts(credentials, refs, budgetMs)\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/** What a masked credential header value reads as in diagnostics responses. */\nconst SENSITIVE_HEADER_MASK = '[stored, not echoed]'\n\n/** Whether a header name is credential-shaped (auth keys, tokens, cookies). */\nfunction sensitiveHeader(name: string): boolean {\n return /authorization|api-?key|token|secret|cookie|session/i.test(name)\n}\n\n/** Copy a headers dict with credential-shaped values masked. */\nfunction maskSensitiveHeaders(headers: Record<string, string>): Record<string, string> {\n const masked: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers)) {\n masked[name] = sensitiveHeader(name) ? SENSITIVE_HEADER_MASK : value\n }\n return masked\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\n // the last resolved section until the settings document reports that it\n // moved. The descriptor (resolved value + raw user layer + revision) is\n // what is cached, so every boot-time consumer \u2014 the dispatch guard's\n // section, the autofill's fill, and the compat guard's sweep \u2014 shares ONE\n // describe per document generation.\n let piDescriptorCache: ReturnType<typeof settings.describe>[number] | undefined\n let piDescriptorCached = false\n const piDescriptor = (required = false): ReturnType<typeof settings.describe>[number] | undefined => {\n if (piDescriptorCached) return piDescriptorCache\n let descriptor: ReturnType<typeof settings.describe>[number] | undefined\n try {\n descriptor = settings.describe().find(entry => entry.ns === PI_NS)\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 -- so a\n // not-ready read is never cached: the retry must reach the wire again.\n if (descriptor === undefined || !isRecord(descriptor.value)) {\n if (required) throw new HostReadError('the llm-pi-ai settings entry is unavailable')\n return undefined\n }\n piDescriptorCache = descriptor\n piDescriptorCached = true\n return descriptor\n }\n const piSection = (required = false): unknown => piDescriptor(required)?.value\n ctx.on('settings/document-updated', (ns) => {\n if (ns === PI_NS) piDescriptorCached = 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 = piDescriptor()\n if (descriptor === undefined) 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 // Compat guard (boot sweep): a wire protocol switched after compat switches\n // were written leaves the old keys behind on the route's models, and the\n // kernel then refuses every model that still carries one -- the route serves\n // nothing until the keys are gone. This pass heals what is already stored\n // (and covers headless compositions, which have no browser half); the\n // browser half repairs what a session changes on its idle pass. Also\n // deliberately NEVER on `settings/document-updated`: the issue #7 rule\n // holds here too.\n {\n const logGuardFailure = (error: unknown): void => {\n console.error(`[dsh-model-think-level] compat cleanup failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n const guardTimers = new Set<ReturnType<typeof setTimeout>>()\n ctx.effect(() => () => {\n for (const timer of guardTimers) clearTimeout(timer)\n guardTimers.clear()\n }, 'dsh-model-think-level: compat-guard boot retries')\n\n /** One sweep; resolves false while the pi-ai namespace is unregistered. */\n const sweepOnce = async (): Promise<boolean> => {\n const descriptor = piDescriptor()\n if (descriptor === undefined) return false\n const user = descriptor.user\n const userProviders = isRecord(user) && isRecord((user as Record<string, unknown>)['providers'])\n ? (user as Record<string, unknown>)['providers'] as Record<string, unknown>\n : undefined\n if (userProviders === undefined) return true\n const patch = buildCompatCleanupPatch(userProviders)\n if (patch === undefined) return true\n try {\n await settings.update(PI_NS, patch, descriptor.revision)\n } catch (error) {\n // A conflict with the boot fill's own write (both read the shared\n // descriptor) retries on the boot backoff \u2014 against a FRESH read, so\n // the cache that just lost the race is dropped. Anything else is\n // logged and left to the next boot or the browser half's idle pass.\n logGuardFailure(error)\n piDescriptorCached = false\n return false\n }\n return true\n }\n const bootSweep = (attempt: number): void => {\n void sweepOnce().then((ready) => {\n if (ready || attempt >= resolved.bootRetryDelaysMs.length) return\n const timer = setTimeout(() => {\n guardTimers.delete(timer)\n bootSweep(attempt + 1)\n }, resolved.bootRetryDelaysMs[attempt])\n guardTimers.add(timer)\n }, logGuardFailure)\n }\n bootSweep(0)\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 metadata (references and manual assignments; 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 // The most recent per-key listing this process obtained, by reference. It is\n // the fallback that keeps a key's models in the catalogue when its next probe\n // fails (a timeout, a 429, a gateway hiccup): without it one slow request\n // silently shrinks a two-key route to one key's models until the next\n // successful pass, which is exactly the \"one key's models disappeared\"\n // symptom. `mergeKeyListings` reports such keys as `retained`.\n const lastKnownScopes = new Map<string, readonly string[]>()\n // The full listing records behind those ids (display name, limits, effort\n // ladder). A retained id must still resolve to its record when the catalogue\n // is rebuilt, or the merge would drop the very models it just kept.\n const lastKnownRecords = new Map<string, ListedModel[]>()\n // Merged catalogues, shortest-lived first: the harness re-requests `/models`\n // on refresh and on every reconnect, and the probe behind it can take\n // seconds per key. A short window turns those repeats into memory reads\n // without ever serving a catalogue the user cannot refresh.\n const listingCache = new Map<string, { at: number; body: string }>()\n // What each key's last successful listing advertised, persisted across restarts\n // (key-serves.ts). The overlay reads it to order keys by \"lists this model\" and\n // to guard an explicit model scope; the write is debounced because the hot path\n // that fills it runs inside a `/models` answer.\n const keyServes: { current: KeyServesDocument | undefined } = { current: undefined }\n const servesDocument = (): KeyServesDocument => (keyServes.current ??= readKeyServes(keyServesFilePath()))\n let servesTimer: ReturnType<typeof setTimeout> | undefined\n const flushServes = (): void => {\n servesTimer = undefined\n try {\n writeKeyServes(servesDocument(), keyServesFilePath())\n } catch {\n // Observations are a cache: a failed write costs one round of retries after\n // a restart, never an answer.\n }\n }\n const recordServes = (route: string, ref: string, models: readonly string[]): void => {\n // A listing with no ids asserts \"serves nothing\"; keep what was known instead.\n // The same rule as `withServes`, applied before the document is touched.\n const live = servesDocument()\n if (models.length === 0) return\n keyServes.current = withServes(live, route, ref, models, Date.now())\n if (servesTimer === undefined) servesTimer = setTimeout(flushServes, 200)\n }\n /** The serving knowledge of one route, or undefined when nothing is known yet. */\n const servingKnowledgeOf = (route: string): ServingKnowledge | undefined => {\n const listed = servesOfRoute(servesDocument(), route)\n return listed.size === 0 ? undefined : { listed }\n }\n /**\n * Forget what a key's listing said. Called when the key's VALUE changes (a\n * different credential is a different upstream account, so the old catalogue\n * describes nothing) and when it is removed. Written through immediately: these\n * are rare, user-initiated operations, and a stale observation outliving a\n * replaced key would send the next request to the wrong account.\n */\n const forgetServes = (route: string, ref: string): void => {\n keyServes.current = withoutServes(servesDocument(), route, ref)\n try {\n writeKeyServes(keyServes.current, keyServesFilePath())\n } catch {\n // Observations are a cache; the in-memory copy is already correct.\n }\n }\n // Raw listing answers for the probe route, by target. Auto-adapt asks for the\n // same route once per model, so this is what turns a whole pass into one\n // wire read; `?refresh=1` (and the TTL above) keeps it from going stale.\n const probeRouteCache = new Map<string, { at: number; data: Record<string, unknown>[] }>()\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 // Names and declared model edits do not change the upstream catalogue. A\n // Save followed by adapter refresh can reuse it without remote detection.\n // A half-written document can park `null` on a provider slot; skipped here,\n // or the boot read would throw before the routes even register.\n const catalogueSource = (): string => JSON.stringify(Object.entries(providersOf())\n .filter(([, profile]) => isRecord(profile))\n .map(([route, profile]) => [\n route, profile['api'], profile['baseURL'], profile['apiKeyEnv'], profile['headers'],\n ]).sort(([a], [b]) => String(a).localeCompare(String(b))))\n let catalogueSourceStamp = catalogueSource()\n /**\n * Drop the cached upstream catalogues.\n *\n * With a route: only that route's overlay answers go \u2014 its key list (or wire)\n * changed, and every OTHER route's keys and wires did not, so their answers\n * are still true. Clearing everything here made one provider's key edit\n * re-probe every provider on the next `/models`, seconds per key inside an\n * answer the caller is waiting on.\n *\n * Without a route (the settings catalogue itself changed \u2014 providers added,\n * re-pointed, re-credentialed): the whole cache, because which routes exist\n * and what they point at is no longer the one it was cached under.\n */\n const invalidateListings = (route?: string): void => {\n if (route === undefined) {\n probeRouteCache.clear()\n listingCache.clear()\n return\n }\n const prefix = `${route}\\u0000`\n for (const key of Array.from(listingCache.keys())) {\n if (key.startsWith(prefix)) listingCache.delete(key)\n }\n }\n\n // A missing provider is not a credential-deletion instruction. Boot,\n // reload and sync can all publish an incomplete (even valid empty) profile.\n // Keep its key metadata, endpoints and balance URL until an explicit key\n // operation removes them; never infer permission to unset a secret here.\n\n // ---- Scope probe: what each key serves, kept true automatically ----\n //\n // A relay resolves each key to a different upstream account with its own\n // catalogue, so the models a route declares are not the models every key\n // serves \u2014 requests discover the difference the hard way, one refusal per\n // model per key, unless each key's scope is kept to what it actually serves.\n // The probe does that: every switched-on key of a MULTI-KEY route is asked\n // for its own listing on the wires it could serve on, the answers are\n // recorded as observations (key-serves.ts), and each key's model scope is\n // then checked to the models it listed WITHIN the set the route declares:\n //\n // - it lists all of them \u2192 the catch-all it already reads as IS the\n // assignment, so no scope is written and the key keeps serving models\n // added later;\n // - it lists some of them \u2192 that intersection is written as the key's\n // scope (marked `auto`, so the panel can say whose assignment it is);\n // - it lists none of them \u2192 the key cannot serve this provider at all, so\n // the key's own row is switched off. The provider is left alone: one\n // unusable upstream account must not take the whole route down. A key\n // the user switched off by hand is never probed, and a key the probe\n // switched off stays off until the user switches it back on \u2014 the probe\n // has no separate \"was this me?\" bit to re-enable from.\n //\n // Every sweep rewrites whatever it finds, manual assignments included: with\n // two triggers (the key panel's \u81EA\u52A8\u63A2\u6D4B button, and a save that moves a\n // provider's address, protocol, key reference or model list) nobody has to\n // keep the split up to date by hand.\n\n /** In-flight probe runs, by route; the list payload reports this as `probing`. */\n const keyProbeRuns = new Map<string, Promise<void>>()\n let probeStopped = false\n ctx.effect(() => () => { probeStopped = true })\n\n /**\n * Probe one route now: resolve every switched-on key (and the profile's own\n * seat, when the index has never listed it), ask each on the wires a request\n * could take, record the observations, and write what each key serves within\n * the route's declared set \u2014 a scope when it carries part of the catalogue, a\n * switched-off row when it carries none of it, nothing when it carries all of\n * it. A route with fewer than two switched-on keys has nothing to divide \u2014\n * one key serves whatever it serves \u2014 so the sweep stops before the wire.\n */\n const probeRouteKeys = async (route: string): Promise<void> => {\n if (probeStopped) return\n const indexFile = keyIndexFilePath()\n let profile: Record<string, unknown> | undefined\n try {\n profile = providerProfileOf(piSection(true), route)\n } catch {\n return\n }\n if (profile === undefined) return\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\n // The route's own model list is the universe a scope is written in, so a\n // route without one has nothing to check any key against \u2014 and no reason to\n // spend a listing request finding that out.\n const declaredIds = Array.isArray(profile['models'])\n ? profile['models'].filter(isRecord).map(model => typeof model['id'] === 'string' ? model['id'].trim() : '').filter(Boolean)\n : []\n if (declaredIds.length === 0) return\n let document: ReturnType<typeof readKeyIndex>\n try {\n document = readKeyIndex(indexFile)\n } catch {\n // A malformed index is the key route's complaint to make, not the probe's.\n return\n }\n const endpoints = routeEndpointsOf(document, route)\n // A switched-off key is out of the pool already: the probe neither asks it\n // nor keeps asking a row it switched off itself.\n const listed = keyEntriesOf(document, route)\n const active = listed.filter(entry => entry.disabled !== true)\n const seat = enabledRefOf(profile)\n const keys: { ref: string; entry: KeyIndexEntry | undefined }[] = active.map(entry => ({ ref: entry.ref, entry }))\n if (seat !== undefined && !listed.some(entry => entry.ref === seat)) keys.push({ ref: seat, entry: undefined })\n // One key serves whatever it serves: the scope check exists to divide a\n // route's models across keys, and a single-key route has no division.\n if (keys.length < 2) return\n const credentials = ctx.get('credentials') as CredentialsService | undefined\n const values = await Promise.all(keys.map(async key => {\n try {\n return await resolveCredential(credentials, key.ref)\n } catch {\n return undefined\n }\n }))\n if (probeStopped) return\n const askable = keys.flatMap((key, index) => {\n const value = values[index]\n return value === undefined || value.length === 0 ? [] : [{ ...key, value }]\n })\n if (askable.length === 0) return\n // Background work nobody waits on: each listing gets the FULL probe budget\n // (the catalogue overlay caps at LISTING_PROBE_BUDGET_MS because it runs\n // inside the host's own /models answer; this probe has no such caller, so\n // a slow gateway just takes longer to be observed, never blocks anyone).\n const timeoutMs = resolved.probeTimeoutMs\n const send = headerOverlayBypass()\n const targetsOf = (entry: KeyIndexEntry | undefined): ProbeTarget[] =>\n entry?.protocol !== undefined\n ? listingTargetsOf({ protocol: entry.protocol, endpoint: endpoints?.[endpointFamilyOf(entry.protocol)] }, api, baseURL)\n : listingTargetsOf({ endpoints }, api, baseURL)\n const served = new Map<string, readonly string[]>()\n await collectKeyListings({\n keys: askable,\n refOf: key => key.ref,\n probe: async key => {\n if (probeStopped) return { ref: key.ref, models: undefined }\n // A key's targets are independent listings; they run together and fold\n // in target order, exactly as the catalogue overlay folds them.\n const listings = await Promise.all(targetsOf(key.entry).map(target => probeListing({\n baseURL: target.baseURL,\n api: target.api,\n apiKey: key.value,\n headers: profile?.['headers'],\n timeoutMs,\n send,\n })))\n if (probeStopped) return { ref: key.ref, models: undefined }\n const ids: string[] = []\n for (const listing of listings) {\n if (listing === undefined) continue\n for (const model of listing) {\n if (!ids.includes(model.id)) ids.push(model.id)\n }\n }\n if (ids.length === 0) return { ref: key.ref, models: undefined }\n // Keep wire results local until the live commit owns the shared lease.\n served.set(key.ref, ids)\n return { ref: key.ref, models: ids }\n },\n })\n if (probeStopped || served.size === 0) return\n // The POST only queues this probe; it never awaits it while holding a\n // mutation lease. Network work stays outside the shared commit lease.\n const releaseMutation = await acquireKeyMutation(indexFile)\n try {\n if (probeStopped) return\n const currentProfile = providerProfileOf(settings.describe().find(entry => entry.ns === PI_NS)?.value, route)\n if (currentProfile === undefined) return\n // Scope only the models still declared after acquiring the lease.\n const declared = Array.isArray(currentProfile['models'])\n ? currentProfile['models'].filter(isRecord).map(model => typeof model['id'] === 'string' ? model['id'].trim() : '').filter(Boolean)\n : []\n if (declared.length === 0) return\n // Keys, aliases, endpoints and manual claims may have changed on the wire\n // or while this commit waited for another writer. Read only now.\n let next = readKeyIndex(indexFile)\n let mutated = false\n const emptied: string[] = []\n for (const [ref, ids] of served) {\n // Publish observations only while this live commit owns the lease.\n lastKnownScopes.set(`${route}\\u0000${ref}`, ids)\n recordServes(route, ref, ids)\n const entry = keyEntriesOf(next, route).find(candidate => candidate.ref === ref)\n // An unlisted seat keeps its catch-all and recorded observations.\n if (entry === undefined) continue\n const target = declared.filter(id => ids.includes(id))\n if (target.length === 0) {\n // Nothing this key lists belongs to this provider: it cannot serve a\n // single model here, so its own row is switched off (never the\n // provider \u2014 one unusable upstream account must not take the route\n // down). Applied below, where the route's last key is protected.\n if (entry.disabled !== true) emptied.push(ref)\n continue\n }\n // Every declared model: the catch-all the entry already reads as IS the\n // assignment, so adding models later keeps working without another pass.\n const scope = target.length === declared.length ? undefined : target\n const unchanged = scope === undefined\n ? entry.models === undefined\n : entry.models !== undefined && entry.models.length === scope.length && scope.every(id => entry.models?.includes(id))\n if (unchanged) continue\n next = withKeyAutoScope(next, route, ref, scope)\n mutated = true\n }\n if (emptied.length > 0) {\n // A route must keep a key: switching off the last one would leave the\n // model list pointing at a provider nothing can sign for, which is a\n // bigger claim than \"these keys serve none of these models\" \u2014 most\n // often it means the ids simply do not line up, so the rows stay as\n // they are and the user keeps a pool to fix.\n const after = keyEntriesOf(next, route)\n const activeLeft = after.filter(entry => entry.disabled !== true && !emptied.includes(entry.ref)).length\n const seatLeft = seat !== undefined && !after.some(entry => entry.ref === seat) ? 1 : 0\n if (activeLeft + seatLeft > 0) {\n for (const ref of emptied) next = withKeyDisabled(next, route, ref, true)\n mutated = true\n }\n }\n if (!mutated) return\n try {\n writeKeyIndex(next, indexFile)\n } catch {\n // A failed write costs one round of re-probing after the next save.\n return\n }\n refreshKeyScopes()\n } finally {\n releaseMutation()\n }\n }\n\n /** Probe one route, queueing behind the run already in flight, if any. */\n const runKeyProbe = (route: string): Promise<void> => {\n if (probeStopped) return Promise.resolve()\n const previous = keyProbeRuns.get(route) ?? Promise.resolve()\n const run = previous\n .then(() => probeStopped ? undefined : probeRouteKeys(route))\n .catch(() => {\n // A probe never surfaces: the panel's next button press is the retry.\n })\n .finally(() => {\n if (keyProbeRuns.get(route) === run) keyProbeRuns.delete(route)\n })\n keyProbeRuns.set(route, run)\n return run\n }\n\n // ---- The second trigger: a save that moves a route ----\n //\n // The button is the deliberate trigger; a save is the automatic one. Only the\n // parts of a profile that decide what the sweep would ask (the wire, the key\n // reference, the declared models) count as a move \u2014 renaming a provider,\n // changing a display name or a balance URL leaves every scope true and must\n // not put a listing request on the wire. Saves also cluster (the official\n // card writes the whole profile, the autofill pass writes again), so one\n // timer collects them: a sweep per save would ask the same questions three\n // times in a row.\n const PROBE_SAVE_DELAY_MS = 1_000\n const probeSignatures = new Map<string, string>()\n const probeSavePending = new Set<string>()\n let probeSaveTimer: ReturnType<typeof setTimeout> | undefined\n /** What a sweep would ask about: a change here means the scopes may be stale. */\n const probeSignatureOf = (profile: Record<string, unknown>): string => JSON.stringify([\n profile['api'],\n profile['baseURL'],\n profile['apiKeyEnv'],\n profile['headers'],\n Array.isArray(profile['models'])\n ? profile['models']\n .filter(isRecord)\n .map(model => typeof model['id'] === 'string' ? model['id'].trim() : '')\n .filter(Boolean)\n .sort()\n : [],\n ])\n const armProbeTimer = (): void => {\n if (probeStopped || probeSavePending.size === 0 || probeSaveTimer !== undefined) return\n probeSaveTimer = setTimeout(() => {\n probeSaveTimer = undefined\n const routes = Array.from(probeSavePending)\n probeSavePending.clear()\n for (const route of routes) void runKeyProbe(route)\n }, PROBE_SAVE_DELAY_MS)\n }\n /**\n * Saves arrive through the settings listener; key edits (a new credential, a\n * switched-off row, a protocol pin) arrive through the POST below and name\n * their route outright. Both end in the same debounce.\n */\n const scheduleKeyProbes = (changed?: string): void => {\n if (probeStopped) return\n const providers = providersOf()\n for (const route of Array.from(probeSignatures.keys())) {\n if (!Object.hasOwn(providers, route)) probeSignatures.delete(route)\n }\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile)) continue\n const signature = probeSignatureOf(profile)\n if (probeSignatures.get(route) === signature) continue\n probeSignatures.set(route, signature)\n probeSavePending.add(route)\n }\n // A key edit changes the index, not the profile: the signature cannot see\n // it, so the caller names the route that must be asked again anyway.\n if (changed !== undefined && Object.hasOwn(providers, changed)) probeSavePending.add(changed)\n armProbeTimer()\n }\n // Boot seeds the signatures without sweeping: what is declared at boot was\n // declared before this process started, so nothing about it is news.\n for (const [route, profile] of Object.entries(providersOf())) {\n if (isRecord(profile)) probeSignatures.set(route, probeSignatureOf(profile))\n }\n ctx.effect(() => () => {\n if (probeSaveTimer !== undefined) clearTimeout(probeSaveTimer)\n probeSaveTimer = undefined\n probeSavePending.clear()\n })\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 // Camouflage is an independent switch: a route may ask for an identity\n // while the generic header override feature stays off, and vice versa.\n const camouflage = readCamouflage().providers\n if (!resolved.uaOverride && Object.keys(camouflage).length === 0) {\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, camouflage)\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 // Refresh routing, but retain metadata and secrets for absent providers.\n // A settings snapshot is not an explicit key-removal request.\n // The image side rides the same events: the config file's derived\n // models[] re-derives from this document (config page, MCP, command).\n syncImageConfigNow()\n const source = catalogueSource()\n if (source !== catalogueSourceStamp) {\n catalogueSourceStamp = source\n invalidateListings()\n }\n // A save that moved a provider's wire, key reference or model list makes\n // the scopes it left behind a guess: sweep the affected routes once the\n // cluster of saves settles.\n scheduleKeyProbes()\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 servingKnowledgeOf(route),\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 // Which keys a catalogue was merged from decides what the cache may answer:\n // adding, removing or reordering a key changes the answer, so it changes\n // the key too. A hit skips the wire entirely \u2014 the same refresh (and the\n // many Auto-adapt probes) then costs nothing.\n const cacheKey = `${route}\\u0000${keys.map(key => key.ref).join(',')}`\n const cached = listingCache.get(cacheKey)\n if (cached !== undefined && Date.now() - cached.at < LISTING_CACHE_MS) {\n return new Response(cached.body, { status: 200, headers: { 'content-type': 'application/json' } })\n }\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 across keys, and one key's refusal never drops\n // the others \u2014 a key that cannot answer keeps the models it was last seen\n // serving (`lastKnownScopes`), so one slow request cannot shrink a two-key\n // route to one key's models until the next pass.\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 // One budget for the whole catalogue, not one per target: this runs INSIDE\n // the host's own `/models` GET, so the caller is waiting on it.\n const probeTimeoutMs = Math.min(resolved.probeTimeoutMs, LISTING_PROBE_BUDGET_MS)\n // The memory is stored per ROUTE and reference (two routes may name the same\n // `apiKeyEnv`), while the merge speaks one reference space. Narrow it here.\n const here = (ref: string): string => `${route}\\u0000${ref}`\n const knownHere = new Map<string, readonly string[]>()\n for (const key of keys) {\n const remembered = lastKnownScopes.get(here(key.ref))\n if (remembered !== undefined) knownHere.set(key.ref, remembered)\n }\n const { results } = await collectKeyListings({\n keys,\n refOf: key => key.ref,\n lastKnown: knownHere,\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 the post-save scope probe records.\n const distinct = listingTargetsOf(key, api, baseURL)\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 // The targets of ONE key are independent listings: asking them one after\n // another made a key with two addresses cost two timeouts in series\n // while the host's `/models` GET waited. They run together, and the\n // answers are folded in target order so the catalogue stays stable.\n const answered = await Promise.all(distinct.map(target => probeListing({\n baseURL: target.baseURL,\n api: target.api,\n apiKey: key.value,\n headers: profile?.['headers'],\n timeoutMs: probeTimeoutMs,\n send: sendListing,\n })))\n const records: ListedModel[] = []\n for (const listing of answered) {\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 }\n recordsByRef.set(key.ref, records)\n const ids = records.map(model => model.id)\n // Remember what this key serves, so a later failed probe retains it.\n lastKnownScopes.set(here(key.ref), ids)\n lastKnownRecords.set(here(key.ref), records)\n // And record it across restarts: routing prefers the key whose group\n // listed a model over one that did not (key-serves.ts).\n recordServes(route, key.ref, ids)\n return {\n ref: key.ref,\n models: ids,\n }\n },\n })\n const records = new Map<string, ListedModel>()\n for (const result of results) {\n // A key that could not answer contributes the records it was last seen\n // serving: the merge kept its ids, so their full records must be kept too.\n const owned = recordsByRef.get(result.ref) ?? lastKnownRecords.get(here(result.ref)) ?? []\n for (const model of owned) {\n if (!records.has(model.id)) records.set(model.id, model)\n }\n }\n const census = servesOfRoute(servesDocument(), route)\n // Only a COMPLETE census may hide a model: every key answered its listing, so\n // a model none of them advertises is one no key's upstream group carries \u2014\n // offering it would offer a request the provider answers with \"not supported\n // by any configured account in this group\" on every key. A key that could not\n // be listed is unknown, not empty: with one unknown, nothing is hidden.\n const censusComplete = keys.length > 0 && keys.every(key => census.has(key.ref))\n const models = mergeKeyListings(results, knownHere).ids\n .filter(id => !censusComplete || [...census.values()].some(served => served.includes(id)))\n .map(id => records.get(id))\n .filter((model): model is ListedModel => model !== undefined)\n if (models.length === 0) return undefined\n const body = JSON.stringify({ data: models })\n listingCache.set(cacheKey, { at: Date.now(), body })\n return new Response(body, {\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 // ---- Image generation (\u751F\u56FE): config sync, native tool, `/\u751F\u56FE` command ----\n\n // One-time migration: the retired stdio MCP server's patch entry must go,\n // or every boot would spawn a `lib/image-mcp.mjs` that no longer exists and\n // the profile would keep a duplicate `mcp__dsh-image__generate_image` beside\n // the native tool. Best-effort: a read-only file only costs the cleanup, and\n // the next boot retries.\n try {\n const removed = removeLegacyImageMcpPatch()\n if (removed !== undefined) {\n console.warn(`[dsh-model-think-level] \u5DF2\u81EA\u52A8\u79FB\u9664\u65E7\u7248\u751F\u56FE MCP \u7684\u8865\u4E01\u6761\u76EE\uFF08${removed}\uFF09\u2014\u2014\u91CD\u542F DSH \u540E\u5B8C\u5168\u751F\u6548`)\n }\n } catch (error) {\n console.warn(`[dsh-model-think-level] \u65E7\u7248\u751F\u56FE MCP \u8865\u4E01\u6761\u76EE\u81EA\u52A8\u79FB\u9664\u5931\u8D25\uFF08\u53EF\u624B\u52A8\u5220\u9664\u6807\u8BB0\u5757\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}`)\n }\n //\n // There is NO wire interception any more: a chat model asks for a picture by\n // CALLING the MCP tool (`mcp__dsh-image__generate_image`), so image models\n // stay out of the composer's switcher and nothing rewrites an outbound\n // chat/completions request.\n\n /**\n * Re-derive the config file's `models[]` from the settings document, keeping\n * every stored override. Runs on boot and on every pi-ai document update, so\n * the config page, the MCP server and the command all read one snapshot.\n * Skipped while llm-pi-ai has not registered (an empty providers\n * map at boot must not wipe a config the previous run wrote).\n */\n const syncImageConfigNow = (): void => {\n try {\n if (piSection() === undefined) return\n const providers = providersOf()\n // An EMPTY providers map is not the user deleting their models: it is what\n // the document looks like before it is readable (boot, HMR, a reload that\n // re-registers the section before its value lands). Syncing it would write\n // models: [] and stamp defaultModel to null, and no later pass recovers the\n // pick. Only a populated document may prune rows.\n if (Object.keys(providers).length === 0) return\n updateImageConfig(document => syncImageConfig(document, providers))\n } catch {\n // The config file is best-effort state: a failed sync leaves the last\n // snapshot on disk, which the next successful sync replaces wholesale.\n }\n }\n syncImageConfigNow()\n\n /** The generation deps the host serves the core with (credentials via the store). */\n const imageGenerateDeps: GenerateDeps = {\n config: () => readImageConfig(),\n resolveKey: async ref => {\n try {\n return await resolveCredential(ctx.get('credentials') as CredentialsService | undefined, ref)\n } catch {\n return undefined\n }\n },\n // Beneath the wrapper: the images call composes its own auth from the\n // model row's reference, exactly like the listing probe above.\n send: headerOverlayBypass(),\n persistLastGood: (modelId, params) => {\n try {\n updateImageConfig(document => ({\n ...document,\n models: document.models.map(model => {\n if (model.id !== modelId) return model\n if (params === null) {\n return { ...model, endpoint: { ...model.endpoint, status: 'unsupported' as const } }\n }\n return { ...model, lastGoodParams: params }\n }),\n }))\n } catch {\n // A diagnostics write must never fail the generation that earned it.\n }\n },\n }\n\n // The `/\u751F\u56FE` host command. Registered only when the context carries a\n // commands service (a headless composition may not) \u2014 cordis THROWS on an\n // undeclared service read, so the lookup is fenced.\n let commandsService: CommandsServiceLike | undefined\n try {\n commandsService = (ctx as unknown as { commands?: CommandsServiceLike }).commands\n } catch {\n commandsService = undefined\n }\n registerImagegenCommand(\n commandsService,\n {\n modelIds: () => readImageConfig().models.map(model => model.id),\n generate: generateImage,\n generateDeps: imageGenerateDeps,\n },\n )\n\n // The native `generate_image` tool: the conversation model's primary entry.\n // Deferred on purpose \u2014 a host without the tools or attachments service\n // (headless, sdk) keeps every other feature and simply gets no image tool;\n // a hard `inject` entry would refuse to apply the whole plugin there.\n // The registration state feeds the client's keyed image-card registration,\n // which reads the name back over the config route.\n const imageToolState: { name: string | undefined; error: string | undefined } = { name: undefined, error: undefined }\n // The route saves the switch, so it needs a way to make the registry follow:\n // without it the pane would claim \"on\" while the session still has no tool\n // (or still has one it should no longer see).\n let reconcileImageTool: (() => void) | undefined\n ctx.inject(['tools', 'attachments'], (toolCtx: Context) => {\n let registered: { readonly name: string; readonly dispose: () => void } | undefined\n const release = (): void => {\n const current = registered\n registered = undefined\n imageToolState.name = undefined\n if (current === undefined) return\n try {\n current.dispose()\n } catch {\n // A registry that refuses the removal still drops the tool with the\n // plugin scope; the switch has done all it can.\n }\n }\n const acquire = (): void => {\n if (registered !== undefined) return\n // A throwing registration must not throw out of the route either: record\n // the message so the pane can show why, exactly like the boot path did.\n try {\n registered = registerGenerateImageTool(toolCtx, {\n generateDeps: imageGenerateDeps,\n attachments: (toolCtx as unknown as { attachments: unknown }).attachments as Parameters<typeof registerGenerateImageTool>[1]['attachments'],\n readConfig: () => readImageConfig(),\n })\n imageToolState.name = registered.name\n imageToolState.error = undefined\n } catch (error) {\n imageToolState.name = undefined\n imageToolState.error = error instanceof Error ? error.message : String(error)\n console.warn(`[dsh-model-think-level] \u5185\u5EFA\u751F\u56FE\u5DE5\u5177\u6CE8\u518C\u5931\u8D25\uFF08\u8BCA\u65AD\u8DEF\u7531 ${IMAGE_CONFIG_PATH} \u7684 tool.error \u4F1A\u5E26\u56DE\u8FD9\u6761\u539F\u56E0\uFF09\uFF1A${imageToolState.error}`)\n }\n }\n const reconcile = (): void => {\n if (readImageConfig().enabled) acquire()\n else release()\n }\n reconcileImageTool = reconcile\n toolCtx.effect(\n () => {\n reconcile()\n return () => {\n reconcileImageTool = undefined\n release()\n }\n },\n 'dsh-model-think-level: generate_image tool',\n )\n // A few lines of live defaults per model request, so the tool is called\n // with omitted params instead of guessed ones (the dsh-image-gen\n // precedent). Optional: hosts without the system-prompt service boot\n // unchanged and the tool description alone still guides the model.\n ctx.inject(['systemPrompt'], (promptCtx: Context) => {\n promptCtx.effect(\n () => (promptCtx as unknown as { systemPrompt: { context(contribution: { name: string; order: number; text: () => string }): () => void } }).systemPrompt.context({\n name: 'dsh-model-think-level:image-tool',\n order: 61,\n text: () => imageToolHint(readImageConfig()),\n }),\n 'dsh-model-think-level: image tool hint',\n )\n })\n })\n\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 // The fingerprint route dispatches through the same service, discovered the\n // same way: whichever of the two shapes supplied it, and re-read at request\n // time so a late registration is picked up.\n let fingerprintDispatch: LlmDispatchLike | undefined = availableLlm as LlmDispatchLike | undefined\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) {\n fingerprintDispatch = llm as LlmDispatchLike\n installPiAiBridge(llm)\n }\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 // Serializes fingerprint store writes (POST and DELETE) so two clicks cannot\n // interleave a read-modify-write. Reads stay unqueued, exactly like\n // `acquireKeyMutation` below.\n let fingerprintMutationTail = Promise.resolve()\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 // One listing read answers a whole Auto-adapt pass (it asks per\n // model) and every key-panel probe of the same route inside the\n // window. The identity of a read is the target plus the credential\n // reference it was composed from, so re-pointing a route or swapping\n // its `apiKeyEnv` never serves the previous answer; `?refresh=1`\n // forces the wire instead of waiting out the window.\n const listingKey = `${listingURL}\\u0000${apiKeyEnv ?? ''}`\n const cacheable = url.searchParams.get('refresh') !== '1'\n const remembered = cacheable ? probeRouteCache.get(listingKey) : undefined\n if (remembered !== undefined && Date.now() - remembered.at < LISTING_CACHE_MS) {\n sendJson(res, 200, { ok: true, url: displayUrl(listingURL), data: remembered.data })\n return\n }\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 // This probe waits on an interactive pass (Auto-adapt asks for\n // it per model), so it gets the catalogue budget rather than the\n // diagnostic one: a gateway that cannot list within it yields no\n // endpoint evidence, and the pass moves on to the knowledge base.\n signal: AbortSignal.timeout(Math.min(resolved.probeTimeoutMs, LISTING_PROBE_BUDGET_MS)),\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 probeRouteCache.set(listingKey, { at: Date.now(), data: entries })\n sendJson(res, 200, { ok: true, url: displayUrl(listingURL), data: entries })\n } catch (error) {\n // undici's own failure texts quote the original URL verbatim\n // (\"Request cannot be constructed from a URL that includes\n // credentials: http://user:sekrit@\u2026\") \u2014 the message loses its\n // secrets before it reaches the response body.\n sendJson(res, 502, {\n ok: false,\n error: `could not reach ${displayUrl(listingURL)}: ${redactUrlSecrets(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 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 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 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 res.setHeader('x-dsh-key-integrity', '20261101-explicit-delete+history64+shared-lease-drain')\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 const indexFile = keyIndexFilePath()\n const pendingMutations = new PendingCredentialMutations()\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 release = await acquireKeyMutation(indexFile)\n let finished = false\n releaseMutation = () => {\n if (finished) return\n finished = true\n pendingMutations.releaseAfterSettled(release)\n }\n }\n // The endpoint pair a provider card paints, answered from the index\n // file alone.\n //\n // The page hydrates this once per card per second (see the client's\n // `readEndpoints`) just to show two URLs. It used to pull the whole\n // key list for it -- a settings read plus one credential resolve per\n // key, on a service that serialises -- so an opened card's own list\n // queued behind dozens of those and the panel showed its loader for\n // seconds. This branch touches no settings and no credential.\n if (req.method === 'GET' && url.searchParams.get('op') === 'endpoints') {\n if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a route is required' })\n return\n }\n const endpoints = routeEndpointsOf(readKeyIndex(indexFile), route)\n sendJson(res, 200, {\n ok: true,\n route,\n endpoints: {\n openai: endpoints?.openai ?? null,\n anthropic: endpoints?.anthropic ?? null,\n },\n })\n return\n }\n if (req.method === 'GET' && url.searchParams.get('op') === 'balance') {\n if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a route is required' })\n return\n }\n const endpoint = routeBalanceOf(readKeyIndex(indexFile), route)\n sendJson(res, 200, { ok: true, route, endpoint: endpoint ?? null })\n return\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 /**\n * The profile a READ renders, from the section the guard and probe\n * routes already cache.\n *\n * This list is repainted constantly -- one GET per provider card\n * per second, plus one per invalidation -- and every one of them\n * used to call `settings.describe()`, a call the settings service\n * serialises across the whole host: that queue, not the list\n * itself, is what made an opened card wait seconds for its first\n * answer. The cache is dropped on `settings/document-updated`, so a\n * write from anywhere (this route, the official card's Save, the\n * autofill pass) still reaches the next read. Writes keep their own\n * fresh read below: a precondition decided from a snapshot is how a\n * route moves a key it no longer owns.\n */\n const readProfile = (): Record<string, unknown> | undefined =>\n providerProfileOf(piSection(true), route)\n /** The profile this request may fence a write on. */\n const writeProfile = (): Record<string, unknown> | undefined =>\n providerProfileOf(entryOf()?.value, route)\n const profileOf = (): Record<string, unknown> | undefined =>\n req.method === 'POST' ? writeProfile() : readProfile()\n if (route.length === 0 || profileOf() === 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\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<Record<string, 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 // Reads render from the cached section; a POST renders what it\n // just wrote, so it reads the document again (see `profileOf`).\n const profile = profileOf()\n const seat = enabledRefOf(profile)\n const routeModels = Array.isArray(profile?.['models'])\n ? profile['models'].filter(isRecord).map(model => typeof model['id'] === 'string' ? model['id'].trim() : '').filter(Boolean)\n : []\n const declaredModels = new Set(routeModels)\n const listed = keyEntriesOf(document, route)\n const refs = listed.map(entry => entry.ref)\n // The seat (the reference the adapter itself resolves) joins the\n // list when it can answer for itself: the index lists it, or the\n // store holds a value for it \u2014 the adapter still needs that one.\n // A profile can also name a reference nothing was ever stored\n // under (`apiKeyEnv: MAGPIE_GATEWAY_KEY` written by a shipped\n // patch, with no such variable in the environment). That is a\n // route waiting for its first key, not a key: painting it as a\n // \"not stored\" row put a phantom beside the official warning\n // that already says the variable is missing. Only a store that\n // positively answers \"nothing, and no value to read\" hides it \u2014\n // a store that cannot answer is unknown, not empty.\n const probed = seat !== undefined && !refs.includes(seat) ? [...refs, seat] : refs\n const facts = await displayCredentialFacts(credentials, probed, 250)\n if (seat !== undefined && !refs.includes(seat) && !holdsNothing(facts[seat])) refs.push(seat)\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.models = stored.models.filter(id => declaredModels.has(id))\n // Whose assignment the scope is: the probe writes every scope\n // it lands itself and says so, so the panel can report that\n // the ticks follow what each key lists rather than a choice.\n if (stored?.auto === true) (view as { auto?: boolean }).auto = true\n if (stored?.protocol !== undefined) (view as { protocol?: RouteProtocol }).protocol = stored.protocol\n // The cooldown memory rides the view even though no row paints\n // a badge from it any more: the routing pool is the state's\n // source of truth, and the field carries what it sees.\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 = routeEndpointsOf(document, 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 // An in-flight scope probe rides along, so an open panel can\n // follow the assignments the probe writes \u2014 the button starts\n // it, and the assignments are the only thing that shows up.\n const probing = keyProbeRuns.has(route)\n return {\n ok: true,\n route,\n entries,\n models: routeModels,\n ...(probing ? { probing: true } : {}),\n endpoints: {\n openai: endpoints?.openai ?? null,\n anthropic: endpoints?.anthropic ?? 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 let addedRef: string | 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 activeSeat = enabledNow()\n // The official create form has already stored its first key.\n // Reuse that exact value during draft drain instead of minting\n // a duplicate credential and losing the user's first-key label.\n if (activeSeat !== undefined && await resolveCredential(credentials, activeSeat) === value) {\n updateKeyIndex(document => withKeyEntry(document, route, activeSeat, alias), indexFile)\n refreshKeyScopes()\n releaseMutation?.()\n releaseMutation = undefined\n sendJson(res, 200, { ...await payload(), addedRef: activeSeat })\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 // A reference this route already lists may hold this very value\n // under a name the seat does not use. The create card is the\n // ordinary way there: the official form stores its key under the\n // profile's `apiKeyEnv`, then this drain adds the SAME secret\n // again, and without this check the second copy became a second\n // row with an identical mask \u2014 two keys that are one. Reusing the\n // holder keeps the list honest; the label the user typed rides\n // onto that row (it is the same secret, so it is the same key).\n // Only a reference whose readable value EQUALS the incoming one\n // qualifies; a store that cannot be read never matches.\n for (const ref of taken) {\n let held: string | undefined\n try {\n held = await resolveCredential(credentials, ref)\n } catch {\n continue\n }\n if (held !== value) continue\n // One write: an unlisted holder joins the list, a listed one\n // keeps its own scope and protocol pin (the label is the only\n // thing an add carries for it).\n updateKeyIndex(document => withKeyEntry(document, route, ref, alias), indexFile)\n // The profile may still name an empty reference (the shipped\n // patch's `apiKeyEnv`, or a seat that lost its value). The key\n // the user just added is this one, so it takes the seat;\n // otherwise the official card keeps warning about the old name\n // while a working key sits right below it.\n if (active !== ref) {\n let seatEmpty = false\n if (active !== undefined) {\n try {\n seatEmpty = holdsNothing((await credentialFacts(credentials, [active], CREDENTIAL_IPC_BUDGET_MS))[active])\n } catch {\n seatEmpty = false\n }\n }\n if (active === undefined || seatEmpty) {\n const failed = await setEnabledKey(ref)\n if (failed !== undefined) throw new Error(failed)\n }\n }\n refreshKeyScopes()\n releaseMutation?.()\n releaseMutation = undefined\n sendJson(res, 200, { ...await payload(), addedRef: ref })\n return\n }\n // A listed row the store positively holds NOTHING under is an\n // empty slot, not a taken name. Filling it keeps the reference\n // the profile \u2014 and any other computer that synced that\n // profile \u2014 already uses; minting `_3` beside an empty `_2` is\n // what made a re-fill after a sync drift away from the name the\n // seat resolves and leave a \"not stored\" row behind.\n //\n // The seat comes first (storing there needs no re-point at\n // all), then the remaining rows in the order the page shows\n // them. Only a store that answered \"nothing, and no value to\n // read\" qualifies \u2014 an unreadable store is unknown, and this\n // path must never overwrite a key it could not see. The\n // readable face gets the final word, because metadata can\n // outlive the value it describes.\n const listedRefs = keyEntriesOf(readKeyIndex(indexFile), route).map(entry => entry.ref)\n const slotCandidates = active !== undefined && listedRefs.includes(active)\n ? [active, ...listedRefs.filter(candidate => candidate !== active)]\n : listedRefs\n const slotFacts = slotCandidates.length > 0\n ? await credentialFacts(credentials, slotCandidates, CREDENTIAL_IPC_BUDGET_MS)\n : {}\n const emptySlot = slotCandidates.find(candidate => holdsNothing(slotFacts[candidate]))\n let created = emptySlot !== undefined\n && await resolveCredential(credentials, emptySlot) === undefined\n ? emptySlot\n : undefined\n if (created === undefined) {\n 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], CREDENTIAL_IPC_BUDGET_MS)\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 }\n // A profile can name a reference the store holds NOTHING under:\n // a shipped patch writes `apiKeyEnv: MAGPIE_GATEWAY_KEY` ahead of\n // any key, and the official card then warns that the variable is\n // missing. Such a route has no working key at all \u2014 the same\n // state as a profile naming no reference \u2014 so this add takes the\n // seat, or the warning would outlive the key that fixed it and\n // the adapter would keep resolving an empty name. Only a store\n // that POSITIVELY holds nothing hands the seat over: an\n // unreadable store is unknown, and re-pointing a working key on\n // a bad read is the one mistake this must not make.\n const seatBefore = active\n const seatIsEmpty = seatBefore !== undefined\n && seatBefore !== created\n && holdsNothing((await credentialFacts(credentials, [seatBefore], CREDENTIAL_IPC_BUDGET_MS))[seatBefore])\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, pendingMutations)\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 (seatBefore === undefined || seatIsEmpty) {\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, pendingMutations, CREDENTIAL_IPC_BUDGET_MS)\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 addedRef = created\n } else if (op === 'scope') {\n // Store the manual assignment from the provider's added models.\n // Omission clears it to catch-all; [] is an explicit empty\n // assignment. Anything else that is not an array \u2014 a comma\n // string above all \u2014 is refused: silently widening a narrowed\n // key to catch-all is the one direction a typo must not go.\n if (isRecord(body) && body['models'] !== undefined && !Array.isArray(body['models'])) {\n refuse('model assignments must be an array of model ids')\n return\n }\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 profile = providerProfileOf(entryOf()?.value, route)\n const declared = new Set(Array.isArray(profile?.['models'])\n ? profile['models'].filter(isRecord).map(model => model['id']) : [])\n if (scope?.some(id => !declared.has(id))) {\n refuse('model assignments must use models already added to this provider')\n return\n }\n const target = ref\n updateKeyIndex(\n document2 =>\n withKeyModels(\n hasKeyEntry(document2, route, target) ? document2 : withKeyEntry(document2, route, target),\n route, target, scope,\n ),\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 withKeyProtocol(\n hasKeyEntry(document2, route, target) ? document2 : withKeyEntry(document2, route, target),\n route, target, protocol,\n ),\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 and the Anthropic wire.\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 })\n : undefined\n updateKeyIndex(document => withRouteEndpoints(document, route, endpoints), indexFile)\n } else if (op === 'balance') {\n // The one URL a provider's balance is read from. It is display\n // only and independent of the protocol-family addresses: an\n // empty value clears it, and a route without one shows no\n // balance on the Models page.\n const endpoint = isRecord(body) && typeof body['endpoint'] === 'string'\n ? body['endpoint']\n : ''\n updateKeyIndex(document => withRouteBalance(document, route, endpoint), indexFile)\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, pendingMutations)\n if (refused !== undefined) {\n refuse(refused)\n return\n }\n forgetServes(route, ref)\n // A new value is a new upstream account: whatever the old one\n // refused says nothing about this one.\n keyRest.clear(restKeyOf(route, ref))\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], CREDENTIAL_IPC_BUDGET_MS))[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 forgetServes(route, ref)\n invalidateCredentialDisplay(credentials, ref)\n if (configured) {\n const refused = await forgetCredential(credentials, ref, pendingMutations, CREDENTIAL_IPC_BUDGET_MS)\n if (refused !== undefined) throw new Error(refused)\n }\n } catch (error) {\n const failures: string[] = []\n try {\n updateKeyIndex(current => {\n const original = Object.hasOwn(document.providers, route) ? document.providers[route] : undefined\n if (original !== undefined) return { ...current, providers: { ...current.providers, [route]: original } }\n const providers = { ...current.providers }\n delete providers[route]\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 === 'probe') {\n // The key panel's \u81EA\u52A8\u63A2\u6D4B button: ask every switched-on key of\n // a multi-key route what its own listing advertises, and write\n // what each key actually serves within the route's declared set\n // \u2014 a scope when it carries part of it, a switched-off row when\n // it carries none of it, nothing when it carries all of it. A\n // route with a single switched-on key has nothing to divide \u2014\n // one key serves whatever it serves \u2014 so the refusal says so\n // instead of running a sweep that can only confirm what the row\n // already reads.\n const listed = keyEntriesOf(readKeyIndex(indexFile), route)\n const seat = enabledNow()\n const distinct = new Set(listed.filter(entry => entry.disabled !== true).map(entry => entry.ref))\n if (seat !== undefined && !listed.some(entry => entry.ref === seat)) distinct.add(seat)\n if (distinct.size < 2) {\n refuse('a scope probe needs a second key; a single key serves whatever it serves')\n return\n }\n // Fire and forget: the probe answers through the list's\n // `probing` flag and the scope writes it lands, never through\n // this request, which returns as soon as the run is queued.\n void runKeyProbe(route)\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 or scoped just now would not sign a request until some\n // unrelated settings change happened to refresh it.\n refreshKeyScopes()\n if (['add', 'remove', 'value', 'protocol', 'endpoints', 'enable'].includes(op)) {\n invalidateListings(route)\n // A key edit is exactly the news a sweep exists to digest: a\n // new credential is a new upstream account, a fresh row has no\n // scope yet, and a row switched back on has to be asked again.\n scheduleKeyProbes(route)\n }\n // The transaction is committed. Slow display-only credential reads\n // must not hold the next unrelated mutation in the global queue.\n releaseMutation?.()\n releaseMutation = undefined\n const answer = await payload()\n sendJson(res, 200, addedRef === undefined ? answer : { ...answer, addedRef })\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 // One provider's balance, fetched from the URL that provider configured.\n //\n // The browser half cannot make this call itself: the balance API is a\n // third-party origin (CORS), and the request is signed with a stored key\n // that only the host can resolve. The URL itself is plugin state in the key\n // index (`balances`), written from the provider card's balance row. A route\n // with no URL answers `configured:false` \u2014 the Models page shows nothing in\n // that case \u2014 while a configured route that fails answers an error, so a\n // broken endpoint does not masquerade as \"not configured\".\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: BALANCE_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') {\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 if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a route is required' })\n return\n }\n let document: ReturnType<typeof readKeyIndex>\n try {\n document = readKeyIndex(keyIndexFilePath())\n } catch (error) {\n sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n return\n }\n const endpoint = routeBalanceOf(document, route)\n if (endpoint === undefined) {\n sendJson(res, 200, { ok: true, route, configured: false })\n return\n }\n let profile: Record<string, unknown> | undefined\n try {\n profile = providerProfileOf(piSection(true), route)\n } catch {\n sendJson(res, 502, { ok: false, configured: true, error: 'the llm-pi-ai settings could not be read' })\n return\n }\n if (profile === undefined) {\n sendJson(res, 400, {\n ok: false,\n configured: true,\n error: `no llm-pi-ai provider route \"${route}\"`,\n })\n return\n }\n // Only the FIRST key of the provider is asked for a balance.\n // Further keys may resolve to different upstream accounts, but the\n // row shows one amount per provider, so asking them would multiply\n // traffic for values nobody sees. A route whose key list is empty\n // falls back to the profile's seat (the only key it can have); a\n // route with no key at all still gets the call, because some\n // balance endpoints are public.\n const credentials = ctx.get('credentials') as CredentialsService | undefined\n const ref = keyEntriesOf(document, route)[0]?.ref ?? enabledRefOf(profile)\n let apiKey: string | undefined\n if (ref !== undefined) {\n try {\n apiKey = await resolveCredential(credentials, ref)\n } catch {\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: 'the credential store could not read the reference',\n })\n return\n }\n }\n try {\n const headers: Record<string, string> = { accept: 'application/json' }\n if (apiKey !== undefined) {\n // The upstream protocol family decides the header the provider\n // expects for an account-level call; the two are not combined,\n // so an endpoint that rejects the other family's header (or a\n // WAF that flags it) is not handed a credential it never asked\n // for. Redirects are refused for the same reason: the key must\n // only reach the authority the user typed.\n const api = typeof profile['api'] === 'string' ? profile['api'] : ''\n if (api === 'anthropic-messages') headers['x-api-key'] = apiKey\n else headers['authorization'] = `Bearer ${apiKey}`\n }\n const upstream = await headerOverlayBypass()(endpoint, {\n method: 'GET',\n headers,\n redirect: 'error',\n signal: AbortSignal.timeout(BALANCE_TIMEOUT_MS),\n })\n if (!upstream.ok) {\n const hint = upstream.status === 401 || upstream.status === 403 ? '; check the API key' : ''\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: `${displayUrl(endpoint)} answered ${upstream.status}${hint}`,\n })\n return\n }\n const text = await readBounded(upstream, endpoint)\n const reading = parseBalancePayload(text)\n if (reading === undefined) {\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: `${displayUrl(endpoint)} answered no recognisable balance`,\n })\n return\n }\n sendJson(res, 200, {\n ok: true,\n route,\n configured: true,\n amount: reading.amount,\n ...(reading.currency === undefined ? {} : { currency: reading.currency }),\n })\n } catch (error) {\n // undici's own failure texts quote the original URL verbatim;\n // strip credentials before the reason reaches the page.\n sendJson(res, 502, {\n ok: false,\n configured: true,\n error: `could not reach ${displayUrl(endpoint)}: ${redactUrlSecrets(error instanceof Error ? error.message : String(error))}`,\n })\n }\n },\n }),\n 'dsh-model-think-level: balance 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 UI-order document: the provider-row sequence and every provider's\n // model-row sequence the user set by dragging on the official Models page.\n //\n // The browser half keeps the live preference in localStorage \u2014 fast, and\n // shared across tabs through storage events \u2014 but localStorage does not\n // travel between machines, and the orderings are exactly what a user wants\n // everywhere. This route owns the synced copy (`ui-order.json` beside the\n // key index): the client pulls at boot and pushes every drag, arbitrated\n // last-writer-wins by the `savedAt` stamp each side carries; the host only\n // folds what arrives over what is stored, so a partial or buggy payload\n // cannot blank a good file. No secrets \u2014 provider routes and model ids\n // only \u2014 which is what makes the file safe to point a sync tool at.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: ORDER_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') {\n // An absent or malformed file is an EMPTY document, never an\n // error: the client decides whether to adopt or to seed it.\n sendJson(res, 200, { ok: true, data: readUiOrder(uiOrderFilePath()) })\n return\n }\n if (req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n // One document per deployment: a provider order plus every\n // provider's model order. 64KiB covers a hundred routes with\n // hundred-row model lists several times over.\n const body = await readJsonBody(req, 65_536)\n if (body === undefined) {\n sendJson(res, 400, { ok: false, error: 'the body is not a JSON document' })\n return\n }\n try {\n // Read-fold-write is synchronous (order-store is), so two\n // overlapping pushes cannot interleave the read-modify-write.\n // A payload no newer than the stored document is refused with\n // 409: it is a page that never saw the newer file, and letting it\n // win would roll the order and the switches back.\n const { document, stale } = commitUiOrderGuarded(body, Date.now())\n if (stale) {\n sendJson(res, 409, { ok: false, error: 'stale', data: document })\n return\n }\n sendJson(res, 200, { ok: true, data: document })\n } catch (error) {\n sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n }\n },\n }),\n 'dsh-model-think-level: ui-order route',\n )\n\n // Request camouflage: which CLIENT IDENTITY each provider route presents on\n // the wire. Stored in the plugin's own file beside the key index, because\n // the official provider card writes the whole `providers.<route>` object and\n // would drop a field its schema does not know.\n //\n // GET answers the whole map (the card shows its own route's choice, and the\n // editor can warn about another route presenting the same identity). POST\n // changes exactly ONE route, with `preset: null` meaning \"send as sent\", so\n // one save can never blank the other routes' choices.\n // Whether the disguise can reach the wire at all. Two seams can carry it:\n // this plugin's fetch overlay, and the pi-ai header transform every model\n // adapter calls. Asking only the overlay under-reports \u2014 `headerOverlayInstalled`\n // means OUR wrapper is the global fetch, which stops being true the moment\n // another plugin layers its own on top, even though ours still runs beneath\n // it. A route whose adapters are patched therefore counts as installed too,\n // which is the seam model requests actually cross.\n const requestSeamsInstalled = (): boolean => {\n if (headerOverlayInstalled()) return true\n const state = headerBridgeState()\n return isRecord(state) && typeof state['adaptersPatched'] === 'number' && state['adaptersPatched'] > 0\n }\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: CAMOUFLAGE_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') {\n sendJson(res, 200, {\n ok: true,\n data: {\n presets: CAMOUFLAGE_PRESETS,\n providers: readCamouflage().providers,\n installed: requestSeamsInstalled(),\n },\n })\n return\n }\n if (req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const body = await readJsonBody(req, 16_384)\n if (!isRecord(body)) {\n sendJson(res, 400, { ok: false, error: 'the body is not a JSON document' })\n return\n }\n const route = body['route']\n const preset = body['preset']\n if (typeof route !== 'string' || route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'route is required' })\n return\n }\n if (preset !== null && !isCamouflagePreset(preset)) {\n sendJson(res, 400, { ok: false, error: 'preset must be codex, claude or null' })\n return\n }\n try {\n const document = setRouteCamouflage(route, preset ?? undefined)\n // Rebuild the fetch index now: the next request must already carry\n // the identity this save selected, not the previous one.\n refreshHeaders()\n sendJson(res, 200, { ok: true, data: document })\n } catch (error) {\n sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n }\n },\n }),\n 'dsh-model-think-level: camouflage 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 // The override map can carry credential headers the user configured\n // for a gateway (an `authorization`, an `x-api-key`); nothing this\n // answers may sit in a cache, and those values must not echo.\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 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 * Credential-shaped values are masked: this is a status report,\n * not the editor's data source (the editor reads the settings\n * document through its own face), so no consumer needs them. */\n overrides: index.overrides.map(entry => ({\n origin: entry.origin,\n route: entry.route,\n headers: maskSensitiveHeaders(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 * with credential-shaped values masked the same way. */\n headerConflicts: index.headerConflicts.map(conflict => ({\n ...conflict,\n values: sensitiveHeader(conflict.header)\n ? conflict.values.map(() => SENSITIVE_HEADER_MASK)\n : conflict.values,\n })),\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 // Model fingerprint attribution (ModelTrace). One path, three verbs: GET\n // reads the stored verdicts for a provider, POST runs one model's three\n // challenges and stores the verdict, DELETE forgets one model.\n //\n // The POST answers as NDJSON -- one `progress` line per finished challenge,\n // then one `result` line -- because the page shows `\u68C0\u6D4B\u4E2D \u00B7 n/3` and only\n // the host knows when a challenge lands. A proxy that buffers the whole\n // response degrades this safely: the progress lines just arrive late, the\n // page falls back to an indeterminate badge, and the final line is still\n // the truth. Raw answer text never leaves this process; only statistics\n // are stored (design \u00A74.2).\n //\n // Early exit rides on `runProbe.shouldStop` below: two confident answers\n // close the run before the slowest challenge lands, and the verdict is\n // graded on the bank's own 2-query calibration (verdict.ts).\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: FINGERPRINT_PATH,\n handler: async (req, res) => {\n // Verdicts are per-model state the page re-reads: nothing this\n // route answers belongs in a cache (the NDJSON POST branch used to\n // set this only for itself; GET/DELETE were cacheable).\n res.setHeader('cache-control', 'no-store')\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n const method = req.method ?? 'GET'\n if (method !== 'GET' && method !== 'POST' && method !== 'DELETE') {\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 if (route.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a provider route is required' })\n return\n }\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 let bank: ReturnType<typeof loadBankSync>\n try {\n bank = loadBankSync()\n } catch (error) {\n sendJson(res, 500, {\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n })\n return\n }\n const file = fingerprintFilePath()\n const stamp = bankBuiltAt(bank)\n\n if (method === 'GET') {\n const document = readFingerprintStore(stamp, file)\n sendJson(res, 200, {\n ok: true,\n data: {\n bank: summarizeBank(bank),\n records: providerRecords(document, route),\n },\n })\n return\n }\n\n // Both writers go through one tail so two clicks cannot interleave a\n // read-modify-write on the same file. Reads stay unqueued.\n let releaseMutation: (() => void) | undefined\n const previous = fingerprintMutationTail\n fingerprintMutationTail = new Promise<void>(resolve => {\n releaseMutation = resolve\n })\n await previous\n try {\n if (method === 'DELETE') {\n const model = url.searchParams.get('model') ?? ''\n if (model.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a model id is required' })\n return\n }\n updateFingerprintStore(\n document => withoutRecord(document, route, model),\n stamp,\n file,\n )\n sendJson(res, 200, { ok: true })\n return\n }\n\n const body = await readJsonBody(req, 2048)\n const model = isRecord(body) && typeof body['model'] === 'string' ? body['model'] : ''\n if (model.length === 0) {\n sendJson(res, 400, { ok: false, error: 'a model id is required' })\n return\n }\n // Eligibility is a page-level rule (design \u00A70.1): a model outside\n // the two families cannot produce a verdict this bank can express,\n // so the route refuses instead of spending three calls to say\n // \"failed\".\n if (!isEligibleModel(model)) {\n sendJson(res, 400, {\n ok: false,\n error: `model \"${model}\" is not a GPT or Claude model`,\n })\n return\n }\n\n const llm = (fingerprintDispatch ?? (ctx as unknown as { llm?: unknown }).llm) as\n | LlmDispatchLike\n | undefined\n if (llm === undefined || typeof llm.prepareCall !== 'function') {\n sendJson(res, 503, { ok: false, error: 'the llm service is unavailable' })\n return\n }\n\n res.statusCode = 200\n res.setHeader('content-type', 'application/x-ndjson; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n // Tell any reverse proxy in front of us not to sit on the lines.\n res.setHeader('x-accel-buffering', 'no')\n const emit = (line: Record<string, unknown>): void => {\n res.write(`${JSON.stringify(line)}\\n`)\n }\n\n const challenges = generateChallenges(3)\n const controller = new AbortController()\n res.on('close', () => {\n if (!res.writableEnded) controller.abort()\n })\n\n let run: ProbeRunResult\n try {\n run = await runProbe({\n provider: route,\n model,\n challenges,\n llm,\n signal: controller.signal,\n timeoutMs: FINGERPRINT_CHALLENGE_TIMEOUT_MS,\n onOutcome: outcome => {\n emit({\n type: 'progress',\n index: outcome.index,\n ok: outcome.ok,\n ...(outcome.error === undefined ? {} : { error: outcome.error }),\n })\n },\n // Early exit (design \u00A75.3): the bank's 2-query calibration\n // carries 99.7% cross-validated accuracy, so two confident\n // answers may close the run before the slowest challenge\n // lands. The gate is deliberately double: the POOLED pair\n // must clear the 2-query probability bar, AND each answer\n // on its own must name the same winner \u2014 two answers biting\n // different candidates must not fuse into a lucky spike.\n shouldStop: settled => {\n const accepted = settled.filter(outcome => outcome.ok)\n if (accepted.length < 2) return false\n try {\n const outputs = accepted.map(outcome => ({\n text: outcome.text,\n expected_count: outcome.expectedCount,\n }))\n const pooled = analyzeGlobalOutputs(outputs, bank)\n if (pooled.probability < EARLY_IDENTIFIED_PROBABILITY) return false\n const first = analyzeGlobalOutputs(outputs.slice(0, 1), bank)\n const second = analyzeGlobalOutputs(outputs.slice(1), bank)\n return first.prediction === second.prediction\n } catch {\n return false\n }\n },\n })\n } catch (error) {\n emit({\n type: 'error',\n error: error instanceof Error ? error.message : String(error),\n })\n res.end()\n return\n }\n\n let attribution: AttributionResult | null = null\n let failure: string | undefined\n try {\n attribution = analyzeGlobalOutputs(run.outputs, bank)\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error)\n }\n // `analyzeGlobalOutputs` throws only when nothing was accepted, so\n // the failure case is exactly \"no usable answer\". When every call\n // died before producing text, say what actually went wrong.\n const usedOutputs = attribution === null ? 0 : attribution.used_outputs\n const record: FingerprintRecord = {\n provider: route,\n model,\n status: statusOf(attribution, usedOutputs),\n checkedAt: Date.now(),\n usedOutputs,\n }\n // \u9010\u9898\u8BB0\u8D26\u5728\u4E24\u79CD\u7ED3\u5C40\u4E0B\u90FD\u5199\uFF1A\u4E09\u9898\u5168\u5E9F\u65F6\uFF0C\u300C\u662F\u54EA\u4E00\u9898\u6CA1\u7B54\u3001\u7B54\u56DE\u6765\n // \u591A\u5C11\u300D\u6B63\u662F\u7528\u6237\u63A5\u7740\u8981\u95EE\u7684\u90A3\u53E5\u3002\u5B83\u8BB0\u7684\u662F\u5C1D\u8BD5\uFF0C\u4E0D\u662F\u7ED3\u8BBA\uFF0C\u6240\u4EE5\u4E0D\n // \u8DDF\u7740 failed \u6E05\u7A7A\u3002\n record.challenges = fingerprintChallengesOf(run.outcomes, attribution)\n if (attribution === null) {\n const firstFailure = run.outcomes.find(outcome => !outcome.ok)\n record.error =\n run.outputs.length === 0 && firstFailure?.error !== undefined\n ? firstFailure.error\n : (failure ?? NO_USABLE_OUTPUT)\n } else {\n record.prediction = attribution.prediction\n record.predictionName = attribution.prediction_name\n record.probability = attribution.probability\n record.familyPrediction = attribution.family_prediction\n record.familyProbability = attribution.family_probability\n record.top = topEntriesOf(attribution.results, 3)\n record.calibration = {\n queries: attribution.calibration.queries,\n cvAccuracy: attribution.calibration.cv_accuracy,\n }\n const timing = fingerprintTimingOf(run.outcomes)\n if (timing !== undefined) record.timing = timing\n }\n\n updateFingerprintStore(\n document => withRecord(document, record),\n stamp,\n file,\n )\n emit({ type: 'result', record })\n res.end()\n } catch (error) {\n sendJson(res, 500, {\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n })\n } finally {\n releaseMutation?.()\n }\n },\n }),\n 'dsh-model-think-level: fingerprint route',\n )\n\n // Image-generation config: GET answers the derived list merged with the\n // stored overrides (re-syncing first, so the snapshot is never stale), POST\n // saves the defaults and the default model.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: IMAGE_CONFIG_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 if (req.method === 'GET') {\n // A GET re-syncs first (an expired snapshot must not be served as\n // fresh); a failed sync leaves the stored document, still useful.\n syncImageConfigNow()\n const config = readImageConfig()\n sendJson(res, 200, {\n ok: true,\n enabled: config.enabled,\n models: config.models,\n defaultModel: config.defaultModel,\n defaults: config.defaults,\n outputDir: config.outputDir,\n syncedAt: config.syncedAt,\n // The native tool's registration state: the pane's status card\n // and the client's keyed image card both read this name back.\n tool: {\n registered: imageToolState.name !== undefined,\n name: imageToolState.name ?? null,\n ...(imageToolState.error === undefined ? {} : { error: imageToolState.error }),\n },\n })\n return\n }\n const body = await readJsonBody(req, 65_536)\n if (!isRecord(body)) {\n sendJson(res, 400, { ok: false, error: 'a JSON body is required' })\n return\n }\n // Save: defaults, output dir, default model, per-model row overrides.\n try {\n updateImageConfig(document => {\n let next: ImageConfig = document\n // The service switch: off unregisters the tool and refuses\n // every generation entry, while the models and params stay put.\n if (typeof body['enabled'] === 'boolean') next = { ...next, enabled: body['enabled'] }\n if (typeof body['defaultModel'] === 'string' && body['defaultModel'].length > 0) {\n next = { ...next, defaultModel: body['defaultModel'] }\n }\n if (body['defaultModel'] === null) next = { ...next, defaultModel: null }\n if (typeof body['outputDir'] === 'string' && body['outputDir'].length > 0) {\n next = { ...next, outputDir: body['outputDir'] }\n }\n if (isRecord(body['defaults'])) {\n const raw = body['defaults']\n next = {\n ...next,\n defaults: {\n size: typeof raw['size'] === 'string' && raw['size'].length > 0 ? raw['size'] : next.defaults.size,\n quality: typeof raw['quality'] === 'string' && raw['quality'].length > 0 ? raw['quality'] : next.defaults.quality,\n n: typeof raw['n'] === 'number' && Number.isInteger(raw['n']) && raw['n'] >= 1 ? Math.min(raw['n'], 16) : next.defaults.n,\n timeoutMs: typeof raw['timeoutMs'] === 'number' && raw['timeoutMs'] >= 60_000\n ? Math.min(raw['timeoutMs'], 3_600_000)\n : next.defaults.timeoutMs,\n },\n }\n }\n // A `models` row in the body (older clients send per-row param\n // overrides) is accepted and ignored: those overrides were\n // removed with the pane's row controls, so the params row is\n // now the only place size/quality/n are picked.\n return next\n })\n syncImageConfigNow()\n // Make the registry follow the saved switch before answering, so\n // the pane's next read reports the truth the session already has.\n try {\n reconcileImageTool?.()\n } catch {\n // A registry hiccup is reported through tool.error on the GET.\n }\n sendJson(res, 200, { ok: true })\n } catch (error) {\n sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })\n }\n },\n }),\n 'dsh-model-think-level: image 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 reads one provider's balance.\n *\n * The URL itself is configured per route in the plugin's key index (the\n * `balances` map) and is queried host-side, because only the host can resolve\n * the route's stored API key for the upstream call and the page would otherwise\n * face CORS on a third-party balance API. The route answers\n * `{ok, configured:false}` when the provider has no balance endpoint at all, so\n * the browser half can tell \"not configured\" (show nothing) from \"configured but\n * unreadable\" (show nothing but keep the endpoint).\n */\nexport const BALANCE_PATH = '/dsh-model-think-level/balance'\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/**\n * Same-origin host route owning model fingerprint attribution (ModelTrace).\n *\n * Three verbs on one path: `GET` returns the stored records for one provider\n * plus the bank summary the page needs to label families; `POST` runs one\n * model's three challenges and stores the verdict; `DELETE` forgets one model.\n * The attribution itself is `src/fingerprint/`, a pure port of ModelTrace's\n * `fingerprint-core.js` over a vendored bank -- so this route only does the\n * plumbing: run challenges through the llm service, parse, store.\n */\nexport const FINGERPRINT_PATH = '/dsh-model-think-level/fingerprint'\n\n/**\n * Same-origin host route owning the UI-order document: the provider-row\n * sequence and every provider's model-row sequence the user set by dragging\n * on the official Models page. `GET` answers the stored document,\n * `POST` folds a (whole-state) payload over it \u2014 the synced copy the browser\n * half pulls at boot and pushes on every drag, so the orderings survive a\n * machine switch (see {@link ORDER_FILE}).\n */\nexport const ORDER_PATH = '/dsh-model-think-level/ui-order'\n\n/**\n * File name of the UI-order document inside the plugin's home dir. Holds no\n * secrets \u2014 provider routes and model ids only \u2014 which is what makes it safe\n * to carry through a sync mechanism.\n */\nexport const ORDER_FILE = 'ui-order.json'\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 marker declaring the row an IMAGE-GENERATION model (\u751F\u56FE).\n *\n * The chat wire's own `input` vocabulary (pi-ai's MODALITY_GATE) only knows\n * text/image \u2014 the request modalities a model ACCEPTS \u2014 and an image generator\n * is not a request-modality answer at all: it is a different kind of model that\n * the composer's model switcher must hide (its entries cannot serve a chat\n * turn), so it lives beside the declaration as its own marker. Schemastery\n * passes unknown model keys through, so the marker survives official-page saves\n * and restarts like the other three; absence means \"not an image generator\",\n * and `false`/absent are the same state.\n */\nexport const INPUT_IMAGE_GEN_MARKER = 'inputImageGen'\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/**\n * Same-origin host route owning the request-camouflage document: `GET` answers\n * every route's selected client identity, `POST` saves one route's choice.\n * Backing file: `<DSH_HOME>/dsh-model-think-level/camouflage.json` (see\n * {@link CAMOUFLAGE_FILE}).\n *\n * The choice is plugin-owned rather than a pi-ai profile field because the\n * official add-provider card writes the WHOLE profile, which would drop a key\n * its schema does not know \u2014 and because a preset expands into several wire\n * headers the user's own `headers` dictionary must not have to carry.\n */\nexport const CAMOUFLAGE_PATH = '/dsh-model-think-level/camouflage'\n\n/** File name of the camouflage document inside the plugin's home dir. */\nexport const CAMOUFLAGE_FILE = 'camouflage.json'\n\n/**\n * Same-origin host route owning the image-generation config surface: `GET`\n * answers the derived image-model list merged with the stored overrides,\n * `POST` saves default model / default params / output dir / per-model rows.\n * Backing file: `<DSH_HOME>/dsh-model-think-level/image.json` (see\n * {@link IMAGE_CONFIG_FILE}).\n */\nexport const IMAGE_CONFIG_PATH = '/dsh-model-think-level/image-config'\n\n/** File name of the image-generation config inside the plugin's home dir. */\nexport const IMAGE_CONFIG_FILE = 'image.json'\n\n/**\n * The patch-layer id the RETIRED image-MCP entry carried. No entry is written\n * any more \u2014 the native `generate_image` tool replaced the stdio server \u2014 but\n * the id and the marker below still matter: the boot-time migration\n * (`src/image/legacy-cleanup.ts`) recognizes and removes a leftover block, so\n * an upgraded profile stops spawning the now-missing `lib/image-mcp.mjs` and\n * stops exposing the duplicate `mcp__dsh-image__generate_image`.\n */\nexport const IMAGE_MCP_PATCH_ID = 'dsh-image-mcp'\n\n/**\n * Marker-block name the retired installer used inside `cordis.patch.yml`. The\n * begin/end comment lines are `# >>> <name>:begin` / `# <<< <name>:end`; the\n * legacy cleanup splices exactly that byte range, so third-party marker blocks\n * (the dsh-skill-mcp-panel precedent) survive untouched.\n */\nexport const IMAGE_MCP_PATCH_MARK = 'dsh-model-think-level:image-mcp'\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 user's model assignment. Absent means a catch-all; an empty array is a\n * concrete empty assignment. Nothing but the user's explicit choice may\n * change this field \u2014 except a scope the host's own post-save probe wrote\n * (marked by {@link KeyEntry.auto}, and re-written by that probe on every\n * later pass until the user claims the scope with a manual edit).\n */\n readonly models?: readonly string[]\n /**\n * Whether the model scope is the probe's assignment rather than the user's.\n * The host rewrites an auto scope whenever it re-probes the route; a manual\n * scope edit clears the mark, and a manually claimed scope is never touched\n * by the probe again. Absent means the scope (or the catch-all) is the\n * user's, or has never been assigned at all.\n */\n readonly auto?: boolean\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 route's default\n * 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. Only the\n * host-supported OpenAI and Anthropic protocols are offered.\n */\nexport type RouteProtocol =\n | 'openai-completions'\n | 'anthropic-messages'\n | 'openai-responses'\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]\n\n/** The endpoint families a protocol can draw its base URL from. */\nexport type EndpointFamily = 'openai' | 'anthropic'\n\n/** Every endpoint family, in the order address rows and pickers show them. */\nexport const ENDPOINT_FAMILIES: readonly EndpointFamily[] = ['openai', 'anthropic']\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 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}\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 * A stored probe-maintained mark, or undefined when the scope is not the\n * probe's. Only a literal `true` counts \u2014 the same rule as\n * {@link normalizeKeyDisabled} \u2014 so a hand-edited index file cannot half-claim\n * the mark, and an entry never carries a redundant `auto: false`.\n * @param value - whatever arrived (the probe's write, or a hand-edited file).\n * @returns `true` when the scope is the probe's assignment, else undefined.\n */\nexport function normalizeKeyAuto(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 and an Anthropic-family endpoint.\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}\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 } = {}\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 return out.openai === undefined && out.anthropic === undefined\n ? undefined\n : out\n}\n\n/**\n * A stored balance endpoint, or undefined when the value carries nothing usable.\n *\n * This is the one URL a provider may add beside its base addresses: the host\n * queries it (with that route's enabled key) and the Models page shows the\n * amount in front of the provider's enable switch. It is not a request endpoint\n * and never takes part in routing, so it is kept outside {@link RouteEndpoints}\n * \u2014 a route may configure a balance URL without configuring either family\n * address, and vice versa. Blank and non-http(s) values are dropped rather than\n * stored, so \"no balance endpoint\" stays distinguishable from an empty string.\n * @param value - whatever arrived (the card's balance field, or a hand-edited file).\n * @returns the trimmed URL, or undefined when there is none.\n */\nexport function normalizeBalanceEndpoint(value: unknown): string | undefined {\n return isEndpointUrl(value) ? value.trim() : undefined\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 * Writes also keep immutable, bounded metadata-only pre-write history. A\n * synchronous read-modify-write cannot interleave in one JS thread; a detected\n * stale snapshot is rejected, but other processes and external synchronizers\n * still need a coordinated write/merge protocol.\n *\n * @module dsh-model-think-level/key-index\n */\n\nimport { mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { randomUUID } from 'node:crypto'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport {\n normalizeBalanceEndpoint,\n normalizeKeyAlias,\n normalizeKeyAuto,\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 * being user-assigned is the default for scopes, so only a probe-maintained\n * scope carries `auto`.\n */\nfunction makeEntry(\n ref: string,\n alias: string | undefined,\n models: readonly string[] | undefined,\n protocol: RouteProtocol | undefined,\n disabled: boolean | undefined,\n auto: boolean | undefined,\n): KeyIndexEntry {\n const entry: {\n ref: string\n alias?: string\n models?: readonly string[]\n protocol?: RouteProtocol\n disabled?: boolean\n auto?: 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 if (auto === true) entry.auto = 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 * Route \u2192 the URL that answers that provider's remaining balance.\n *\n * A balance endpoint is display-only: requests never use it, so it lives\n * beside the key metadata rather than in the pi-ai profile. Absent (or a\n * route without an entry) means \"not configured\", which is what the Models\n * page reads to decide whether to show a balance at all.\n */\n readonly balances?: Record<string, string>\n}\n\n/** JSON dictionaries treat every route, including __proto__, as an own key. */\nfunction setOwnRouteValue<T>(map: Record<string, T>, route: string, value: T): void {\n Object.defineProperty(map, route, { value, enumerable: true, configurable: true, writable: true })\n}\n\n/** Missing route names must never resolve through Object.prototype. */\nfunction ownRouteValue<T>(map: Record<string, T> | undefined, route: string): T | undefined {\n return map !== undefined && Object.hasOwn(map, route) ? map[route] : undefined\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 const auto = normalizeKeyAuto(record['auto'])\n list.push(makeEntry(ref, alias, models, protocol, disabled, auto))\n }\n if (list.length > 0) setOwnRouteValue(out, route, list)\n }\n const endpoints = parseEndpoints(root['endpoints'])\n const balances = parseBalances(root['balances'])\n let document: KeyIndexDocument = { version: 1, providers: out }\n if (endpoints !== undefined) document = { ...document, endpoints }\n if (balances !== undefined) document = { ...document, balances }\n return document\n}\n\n/**\n * Read the per-route balance URLs, dropping unusable entries. Separate for the\n * same reason the endpoint map is: an older file that never carried balances\n * still parses, and one bad line costs only that route.\n * @param raw - the decoded `balances` member (or anything else).\n * @returns the cleaned map, or undefined when it holds nothing usable.\n */\nfunction parseBalances(raw: unknown): Record<string, string> | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const out: Record<string, string> = {}\n for (const [route, value] of Object.entries(raw as Record<string, unknown>)) {\n if (route.length === 0) continue\n const endpoint = normalizeBalanceEndpoint(value)\n if (endpoint !== undefined) setOwnRouteValue(out, route, endpoint)\n }\n return Object.keys(out).length === 0 ? undefined : out\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) setOwnRouteValue(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 let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n // The raw SyntaxError names neither the file nor the repair; every caller\n // surfaces this message verbatim, so it carries the essentials itself.\n throw new Error('the key index is malformed; repair it before changing keys')\n }\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/** Metadata-only, immutable pre-write snapshots; never credential values. */\nexport const KEY_INDEX_HISTORY_LIMIT = 64\n\n/** Directory beside the index, deliberately outside the synced config file. */\nexport function keyIndexHistoryPath(file: string = keyIndexFilePath()): string {\n return `${file}.history`\n}\n\n/** Keep a bounded history, without making a committed write fail on cleanup. */\nfunction trimKeyIndexHistory(file: string): void {\n try {\n const directory = keyIndexHistoryPath(file)\n const snapshots = readdirSync(directory, { withFileTypes: true })\n .filter(entry => entry.isFile() && /^\\d{13}-[0-9a-f-]{36}\\.json$/.test(entry.name))\n .map(entry => entry.name).sort()\n for (const name of snapshots.slice(0, Math.max(0, snapshots.length - KEY_INDEX_HISTORY_LIMIT))) {\n unlinkSync(join(directory, name))\n }\n } catch {\n // Retaining extra snapshots is safer than reporting a successful commit\n // as a failure (which could trigger credential compensation).\n }\n}\n\n/** Write atomically, only after preserving the previous metadata successfully. */\nexport function writeKeyIndex(document: KeyIndexDocument, file: string = keyIndexFilePath()): void {\n const text = `${JSON.stringify(document, null, 2)}\\n`\n let previous: string | undefined\n try {\n previous = readFileSync(file, 'utf8')\n } catch (error) {\n if (!(typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT')) throw error\n }\n if (previous === text) return\n mkdirSync(dirname(file), { recursive: true })\n if (previous !== undefined) {\n // Never wash a malformed existing file into a fresh valid document.\n readKeyIndex(file)\n const directory = keyIndexHistoryPath(file)\n mkdirSync(directory, { recursive: true, mode: 0o700 })\n writeFileSync(join(directory, `${Date.now()}-${randomUUID()}.json`), previous,\n { encoding: 'utf8', flag: 'wx', mode: 0o600 })\n // Backup errors intentionally stop the overwrite; the original stays put.\n }\n const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`\n try {\n writeFileSync(temporary, text, { encoding: 'utf8', flag: 'wx', mode: 0o600 })\n renameSync(temporary, file)\n } catch (error) {\n try {\n unlinkSync(temporary)\n } catch {\n // The temp file is best-effort cleanup; the write failure is the news.\n }\n throw error\n }\n if (previous !== undefined) trimKeyIndexHistory(file)\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 current = readKeyIndex(file)\n const next = mutate(current)\n // A pure transform may overlap a different process or a re-entrant writer.\n // Refuse a detected stale snapshot instead of silently deleting its changes.\n if (JSON.stringify(readKeyIndex(file)) !== JSON.stringify(current)) {\n throw new Error('the key index changed while updating; retry the operation')\n }\n writeKeyIndex(next, file)\n return next\n}\n\n/** One route's keys, or an empty list; inherited names are never entries. */\nexport function keyEntriesOf(document: KeyIndexDocument, route: string): readonly KeyIndexEntry[] {\n const entries = ownRouteValue(document.providers, route)\n return Array.isArray(entries) ? entries : []\n}\n\n/** One route's extra endpoints, without inherited prototype members. */\nexport function routeEndpointsOf(document: KeyIndexDocument, route: string): RouteEndpoints | undefined {\n return ownRouteValue(document.endpoints, route)\n}\n\n/** One route's balance URL, without inherited prototype members. */\nexport function routeBalanceOf(document: KeyIndexDocument, route: string): string | undefined {\n return ownRouteValue(document.balances, route)\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, 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 touches its scope, nor silently re-pins\n // its protocol, nor switches it back on. A probe-maintained scope stays\n // probe-maintained: the label is not a claim on it.\n const keptLabel = label === undefined ? existing?.alias : label\n list[index] = makeEntry(ref, keptLabel, existing?.models, existing?.protocol, existing?.disabled, existing?.auto)\n }\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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, list[index]?.auto)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(document) }\n}\n\n/**\n * Set (or clear) the user's model assignment. `undefined` means catch-all, and\n * an empty array remains a concrete empty assignment.\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 // A manual assignment is a claim: the user chose what this key serves, so\n // the probe's maintenance mark goes with it and the probe never rewrites\n // this scope again.\n list[index] = makeEntry(ref, list[index]?.alias, scope, list[index]?.protocol, list[index]?.disabled, undefined)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(document) }\n}\n\n/**\n * Write the probe's model assignment, marking it as maintained.\n *\n * This is the host's post-save probe speaking, not the user: the scope is\n * rewritten on every probe pass until a manual edit (via {@link withKeyModels})\n * claims it. `undefined` stores a marked catch-all \u2014 the probe found the key\n * serving every declared model, and the catch-all is both the honest reading\n * and the one that keeps serving models added later.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param models - the ids the probe observed within the route's declared set,\n * or undefined for a maintained catch-all.\n */\nexport function withKeyAutoScope(\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, true)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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, list[index]?.auto)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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, existing?.auto)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document), ...balancesOf(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 setOwnRouteValue(map, route, cleaned)\n const next: KeyIndexDocument = { version: 1, providers: document.providers, ...balancesOf(document) }\n return Object.keys(map).length === 0 ? next : { ...next, endpoints: map }\n}\n\n/**\n * Set (or clear) one route's balance endpoint.\n *\n * The URL is display-only and independent of the protocol-family addresses, so\n * it is stored in its own map: writing endpoints never clears a balance URL and\n * writing a balance URL never disturbs the routing addresses.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param endpoint - the URL to store, or undefined/blank to clear it.\n */\nexport function withRouteBalance(\n document: KeyIndexDocument,\n route: string,\n endpoint: string | undefined,\n): KeyIndexDocument {\n const map: Record<string, string> = { ...(document.balances ?? {}) }\n const cleaned = normalizeBalanceEndpoint(endpoint)\n if (cleaned === undefined) delete map[route]\n else setOwnRouteValue(map, route, cleaned)\n const next: KeyIndexDocument = { version: 1, providers: document.providers, ...endpointsOf(document) }\n return Object.keys(map).length === 0 ? next : { ...next, balances: map }\n}\n\n/**\n * Carry a document's existing balance map forward on a write that does not\n * touch it, exactly as {@link endpointsOf} does for the routing addresses.\n * @param document - the source document.\n * @returns `{ balances }` when one exists, else `{}` (spreads to nothing).\n */\nfunction balancesOf(document: KeyIndexDocument): { balances?: Record<string, string> } {\n return document.balances === undefined ? {} : { balances: document.balances }\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), ...balancesOf(document) }`\n * so the writers above never silently drop a route's endpoints or balance URL\n * 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 setOwnRouteValue(providers, route, list)\n return { version: 1, providers, ...endpointsOf(document), ...balancesOf(document) }\n}\n\n/**\n * Drop one route entirely: its key list, its extra endpoints and its balance\n * URL. This is what a provider's deletion from the settings document reads as\n * \u2014 {@link withoutKeyEntry} only empties a list the user cleaned key by key,\n * and it deliberately leaves the endpoint maps alone, so a provider removed\n * wholesale by the host would otherwise leave its addresses and balance URL\n * behind for ever.\n * @param document - the current document.\n * @param route - the provider route key.\n */\nexport function withoutRoute(document: KeyIndexDocument, route: string): KeyIndexDocument {\n const providers: Record<string, readonly KeyIndexEntry[]> = { ...document.providers }\n delete providers[route]\n const endpoints = document.endpoints === undefined ? undefined : { ...document.endpoints }\n if (endpoints !== undefined) delete endpoints[route]\n const balances = document.balances === undefined ? undefined : { ...document.balances }\n if (balances !== undefined) delete balances[route]\n let next: KeyIndexDocument = { version: 1, providers }\n if (endpoints !== undefined && Object.keys(endpoints).length > 0) next = { ...next, endpoints }\n if (balances !== undefined && Object.keys(balances).length > 0) next = { ...next, balances }\n return next\n}\n", "/**\n * A process-wide key-mutation queue, shared by all plugin instances and HMR\n * generations. Reference allocation, credential writes and compensation must\n * not interleave merely because two apply() calls have different closures.\n * This is not a cross-process lock; external writers still need reconciliation.\n */\nimport { resolve } from 'node:path'\nimport { keyIndexFilePath } from './key-index.js'\n\nconst KEY_MUTATION_QUEUES = Symbol.for('dsh-model-think-level.key-mutation-queues')\ntype QueueRegistry = typeof globalThis & {\n [KEY_MUTATION_QUEUES]?: Map<string, Promise<void>>\n}\nconst registry = globalThis as QueueRegistry\nconst queues = registry[KEY_MUTATION_QUEUES] ??= new Map<string, Promise<void>>()\n\n/** Acquire one index's mutation turn; release in finally, even on failures. */\nexport async function acquireKeyMutation(file: string = keyIndexFilePath()): Promise<() => void> {\n const absolute = resolve(file)\n const key = process.platform === 'win32' ? absolute.toLowerCase() : absolute\n const previous = queues.get(key) ?? Promise.resolve()\n let releaseTurn: () => void = () => {}\n const turn = new Promise<void>(done => { releaseTurn = done })\n queues.set(key, turn)\n await previous\n let released = false\n return () => {\n if (released) return\n released = true\n if (queues.get(key) === turn) queues.delete(key)\n releaseTurn()\n }\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 TWO different kinds of knowledge, which are never\n * mixed up:\n * - an ASSIGNMENT ({@link KeyCandidate.models}): the user's own scope. A scope\n * that lists the model can serve it; a scope that does not is an exact\n * denial; an UNSCOPED key is a catch-all that serves whatever is left\n * (the state before a key has been scoped, and the way a user says \"this\n * key takes whatever is left\");\n * - an OBSERVATION ({@link ServingKnowledge}): what each key's `/models`\n * listing advertised the last time it answered. Keys on one route can sit\n * in different upstream groups, so \"key B lists this model, key A does not\"\n * is a real fact about the pair \u2014 but only when a sibling DOES list it: a\n * failed listing is not an empty one, and a key nobody probed stays a\n * candidate. This is the case a per-key scope cannot express, because the\n * user never assigned anything and the first key is a catch-all.\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. A\n * failure that names THIS model ({@link classifyFailure}'s `unserved`) rests\n * only the (key, model) pair, so a key that carries one group's models and\n * not another's keeps serving the ones it does carry.\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\":\n * deliberately left as a catch-all. An array (possibly empty) is a concrete\n * 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 * 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/**\n * What the plugin has OBSERVED about one route's keys, as opposed to what the\n * user ASSIGNED in each key's `models`.\n *\n * A listing says what an account's upstream group actually carries; an\n * assignment says what the user ordered. They answer different questions, so\n * they travel separately: an assignment always wins, and an observation only\n * decides between keys the user left unscoped.\n */\nexport interface ServingKnowledge {\n /**\n * Each reference's last successful listing: the model ids that key's\n * `/models` answer advertised. A reference with NO entry never answered and\n * is therefore unknown \u2014 never \"serves nothing\", because a failed listing must\n * not be read as an empty one.\n */\n readonly listed: ReadonlyMap<string, readonly string[]>\n}\n\n/**\n * Whether `key` can serve `model`, per the assignment and observation rules.\n * @param key - the candidate, with its manual scope (if any).\n * @param model - the model id the request names, or undefined when unknown.\n * @param knowledge - what the route's keys were last observed serving.\n */\nexport function canServe(key: KeyCandidate, model: string | undefined, knowledge?: ServingKnowledge): 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 // The user's assignment is the authority: it excludes a model exactly the way\n // it includes one.\n if (models !== undefined) return models.includes(model)\n // An unscoped key is a catch-all until something observes otherwise.\n if (knowledge === undefined) return true\n const listed = knowledge.listed.get(key.ref)\n // Never probed: unknown, so it keeps the benefit of the doubt.\n if (listed === undefined) return true\n if (listed.includes(model)) return true\n // This key's listing does not name the model. That is only evidence of a\n // refusal when a SIBLING key's listing does name it: several keys of one route\n // can sit in different upstream groups, and \"key B carries it, key A does not\"\n // is exactly the pair this rule exists for. When nobody lists it, no\n // observation is decisive and the key stays a candidate.\n for (const [ref, other] of knowledge.listed) {\n if (ref !== key.ref && other.includes(model)) return false\n }\n return true\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, grouped into\n * four tiers: a key the user assigned this model to, then a key whose own\n * listing advertises it, then a key nothing is known about, then \u2014 last, when no\n * sibling lists it either \u2014 a key that was probed and does not carry it. When\n * the 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 * @param knowledge - what the route's keys were last observed serving.\n * @returns the ordered candidates to try.\n */\nexport function keysForModel(\n keys: readonly KeyCandidate[],\n model: string | undefined,\n knowledge?: ServingKnowledge,\n): KeyCandidate[] {\n if (model === undefined) return [...keys]\n const eligible = keys.filter(key => canServe(key, model, knowledge))\n if (eligible.length === 0) return [...keys]\n const rankOf = (key: KeyCandidate): number => {\n // An explicit assignment outranks an observation: honouring \"this model\n // belongs to that key\" is what makes the user's rule true on the wire.\n if (key.models !== undefined) return 0\n const listed = knowledge?.listed.get(key.ref)\n if (listed === undefined) return 2\n return listed.includes(model) ? 1 : 3\n }\n // A stable sort keeps the \"both can serve -> first key\" rule inside a tier.\n return [...eligible].sort((a, b) => rankOf(a) - rankOf(b))\n}\n\n/** The wire families: one body format and one endpoint shape each. */\nexport type WireFamily = 'anthropic' | 'openai'\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 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`)\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\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 (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 family has exactly one wire, so a key pinned to it needs no\n * 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 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 \u2014 but only when the key actually carries that family's\n * 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 : '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 bare\n * 400/404/422 is a request-shape problem that every key would answer identically,\n * so it is returned to the caller unchanged rather than multiplied across keys.\n *\n * The one exception is a 400/404/422 whose BODY names the model as unsupported:\n * that is not a request-shape problem at all but a fact about this key's upstream\n * group (a multi-account relay answers exactly this way for a model another\n * account carries), so it fails over like any other key-level refusal.\n * @param status - the response status code.\n * @param bodyText - the (bounded) response body, when the caller has read it.\n */\nexport function shouldFailover(status: number, bodyText = ''): boolean {\n if (classifyFailure(status, bodyText) === 'unserved') return true\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 bare 400 has no kind at all \u2014 and between \"this key\" and \"this key\n * for THIS model\", which is why `unserved` exists.\n */\nexport type FailureKind = 'auth' | 'rate' | 'quota' | 'server' | 'timeout' | 'refused' | 'unserved'\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 * Bodies that say \"this account does not carry this model\" rather than \"your\n * request is malformed\".\n *\n * A relay that fans one route out over several upstream accounts answers a model\n * only SOME accounts carry with a 404 whose text names the model (\"Model\n * \\\"x\\\" is not supported by any configured account in this group\") or a 400 with\n * `model_not_found`. Every key repeating that error is the bug this pattern\n * fixes: the model exists, the key's group just does not carry it, so the next\n * key must be tried. Deliberately anchored on model words \u2014 a bare 404 (\"404 page\n * not found\") is still a request-shape failure.\n */\nconst UNSERVED_FAILURE = new RegExp([\n 'model_not_found',\n 'model[_\\\\s-](?:not[_\\\\s-](?:found|supported|available|exist(?:s)?)|does\\\\s+not\\\\s+exist|is\\\\s+not\\\\s+(?:found|supported))',\n // The same sentence with the model id between the noun and the verdict:\n // `Model \"gpt-6.1-sol\" is not supported`, `model kimi-k2 not found`.\n 'model[\\\\s\\\\S]{0,80}?(?:not\\\\s+(?:supported|found|available|allowed)|does\\\\s+not\\\\s+exist)',\n '(?:invalid|unknown|unsupported|unrecognized|unrecognised|no\\\\s+such|invalid_request)[_\\\\s-]*model',\n 'not\\\\s+supported\\\\s+by\\\\s+(?:any|this)',\n 'no\\\\s+(?:available\\\\s+)?(?:channel|account)s?\\\\s+(?:for|to\\\\s+serve)',\n '\u6A21\u578B[^,\uFF0C\"\u300D]{0,24}?(?:\u4E0D\u5B58\u5728|\u4E0D\u5B58\u5728\u6216\u4E0D\u652F\u6301|\u4E0D\u652F\u6301|\u672A\u627E\u5230|\u65E0\u6743\u9650|\u4E0D\u53EF\u7528|\u65E0\u6548)',\n '\u4E0D\u652F\u6301[^,\uFF0C\"\u300D]{0,12}?\u6A21\u578B',\n '\u65E0\u53EF\u7528(?:\u6E20\u9053|\u8D26\u53F7|\u8D26\u6237)|\u5206\u7EC4(?:\u4E2D|\u5185)?[^,\uFF0C\"\u300D]{0,12}?(?:\u4E0D\u652F\u6301|\u65E0\u6B64|\u6CA1\u6709)',\n].join('|'), 'i')\n\n/** Bodies that announce an authentication problem rather than a model one. */\nconst AUTH_FAILURE = /invalid[_\\s-]*(?:api[_\\s-]*)?(?:key|token|secret)|unauthorized|authentication|api[_\\s-]*key[_\\s-]*(?:is[_\\s-]*)?(?:invalid|expired|revoked)|\u5BC6\u94A5|\u8BA4\u8BC1\u5931\u8D25/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) {\n if (QUOTA_FAILURE.test(bodyText)) return 'quota'\n // A stream that died with the provider's own \"no such model\" text is the\n // same pair-level refusal a 404 would have carried.\n return UNSERVED_FAILURE.test(bodyText) ? 'unserved' : 'refused'\n }\n if (status === 400 || status === 404 || status === 422) {\n return UNSERVED_FAILURE.test(bodyText) ? 'unserved' : undefined\n }\n if (status === 401 || status === 403) {\n // A relay can refuse a model it does not carry with a 403 as well; the\n // authentication wording, when present, still wins.\n if (UNSERVED_FAILURE.test(bodyText) && !AUTH_FAILURE.test(bodyText)) return 'unserved'\n return 'auth'\n }\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 // A group membership changes when the provider re-plans its accounts, not when\n // a request goes wrong: bench the pair for long enough to stop asking every\n // turn, short enough to pick the model back up after a server-side reshuffle.\n unserved: 10 * 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, plus\n * the model when the failure was about ONE model rather than the credential.\n *\n * A 401 or a 429 describes the credential and its account, so charging the same\n * key a known failure on every model of the route is exactly what a cooldown\n * exists to prevent. An `unserved` refusal is narrower: the account's group\n * carries some models and not others, so benching the whole key would throw away\n * the models it does carry. Those pass a `model` and get a pair-scoped entry.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param model - the model the refusal named, when the cooldown is pair-scoped.\n */\nexport function restKeyOf(route: string, ref: string, model?: string | undefined): string {\n const pair = `${route}\\u0000${ref}`\n return model === undefined || model.length === 0 ? pair : `${pair}\\u0000${model}`\n}\n\n/**\n * Whether a key should be deferred for this request: it may be benched as a\n * whole, or benched for this model alone.\n * @param store - the cooldown memory.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param model - the model this request names.\n * @param now - the clock.\n */\nexport function isRestingFor(\n store: RestStore,\n route: string,\n ref: string,\n model: string | undefined,\n now: number,\n): boolean {\n if (store.isResting(restKeyOf(route, ref), now)) return true\n return model !== undefined && store.isResting(restKeyOf(route, ref, model), now)\n}\n\n/**\n * Retire every cooldown a successful attempt disproves: the key works, and for\n * this model it works too.\n * @param store - the cooldown memory.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param model - the model that just answered.\n */\nexport function clearRest(store: RestStore, route: string, ref: string, model?: string | undefined): void {\n store.clear(restKeyOf(route, ref))\n if (model !== undefined) store.clear(restKeyOf(route, ref, model))\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 * Known credential header names, including legacy/profile-owned headers.\n * Recognizing `x-goog-api-key` here prevents stale credentials from leaking;\n * it does not enable a Google protocol. Used to overwrite the credential the\n * transport already set and remove it when re-signing 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 * What each key's own listing said it serves \u2014 the observed half of routing.\n *\n * A provider route fans one request shape out over several credentials, and a\n * relay may resolve each of them to a different upstream ACCOUNT with its own\n * catalogue: one key's group carries `gpt-6.1-sol`, another key's group does not\n * and answers \"Model ... is not supported by any configured account in this\n * group\". The plugin cannot derive that split from configuration \u2014 keys are\n * opaque references and the upstream group an account belongs to is declared\n * nowhere \u2014 so it records what it observed: every successful model listing per\n * key, with the moment it was taken.\n *\n * `canServe` and `keysForModel` read these observations as a preference and a\n * guardrail (see key-route-core.ts), never as an assertion: a list that could not\n * be read is UNKNOWN, not empty, and a model no key lists is still tried on\n * every key \u2014 the provider, not the plugin, has the last word.\n *\n * The document is derived, not authored: losing it costs a round of failed\n * requests until the next listing, never correctness. It is therefore parsed\n * leniently \u2014 a malformed entry is dropped instead of thrown over \u2014 unlike the\n * key index, which holds what the user wrote.\n *\n * @module dsh-model-think-level/key-serves\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { harnessHome } from './key-index.js'\n\n/** What one key's last successful listing advertised. */\nexport interface KeyServesEntry {\n /** Model ids, as the listing sent them, de-duplicated and in listing order. */\n readonly models: readonly string[]\n /** When that listing was read (epoch ms), so a client merge can tell ages apart. */\n readonly at: number\n}\n\n/** Every route's per-key observations. */\nexport interface KeyServesDocument {\n readonly version: 1\n readonly providers: Readonly<Record<string, Readonly<Record<string, KeyServesEntry>>>>\n}\n\n/**\n * The bound a single key's recorded catalogue may reach. A relay advertising\n * thousands of ids is a misconfiguration; keeping the first few hundred still\n * answers \"does this key serve the model\" without letting one document grow\n * without limit.\n */\nconst MODELS_PER_KEY = 512\n\n/** A fresh, empty document. */\nexport function emptyKeyServes(): KeyServesDocument {\n return { version: 1, providers: {} }\n}\n\n/** Absolute path of the observation document beside the key index. */\nexport function keyServesFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', 'key-serves.json')\n}\n\n/** One model id, cleaned to the shape a listing can carry. */\nfunction normalizeModelId(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const id = value.trim()\n return id.length === 0 ? undefined : id\n}\n\n/**\n * Parse an already-decoded document, dropping whatever does not fit. Never\n * throws: this file is a cache of observations, so a corrupt one is an empty one.\n * @param raw - the decoded JSON value (or anything else).\n * @returns a well-formed document.\n */\nexport function parseKeyServes(raw: unknown): KeyServesDocument {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return emptyKeyServes()\n const providers = (raw as Record<string, unknown>)['providers']\n if (typeof providers !== 'object' || providers === null || Array.isArray(providers)) return emptyKeyServes()\n const out: Record<string, Record<string, KeyServesEntry>> = {}\n for (const [route, keys] of Object.entries(providers as Record<string, unknown>)) {\n if (route.length === 0 || typeof keys !== 'object' || keys === null || Array.isArray(keys)) continue\n const list: Record<string, KeyServesEntry> = {}\n for (const [ref, entry] of Object.entries(keys as Record<string, unknown>)) {\n if (ref.length === 0 || typeof entry !== 'object' || entry === null || Array.isArray(entry)) continue\n const record = entry as Record<string, unknown>\n const models = Array.isArray(record['models'])\n ? [...new Set(record['models'].map(normalizeModelId).filter((id): id is string => id !== undefined))]\n : []\n const at = typeof record['at'] === 'number' && Number.isFinite(record['at']) ? record['at'] : 0\n if (models.length === 0) continue\n list[ref] = { models: models.slice(0, MODELS_PER_KEY), at }\n }\n if (Object.keys(list).length > 0) out[route] = list\n }\n return { version: 1, providers: out }\n}\n\n/**\n * Read the document. Never throws: an absent file and an unreadable one both\n * mean \"nothing observed yet\".\n * @param file - document path (tests pass a temp file).\n */\nexport function readKeyServes(file: string = keyServesFilePath()): KeyServesDocument {\n try {\n return parseKeyServes(JSON.parse(readFileSync(file, 'utf8')) as unknown)\n } catch {\n return emptyKeyServes()\n }\n}\n\n/** Write the document at one path, atomically. */\nexport function writeKeyServes(document: KeyServesDocument, file: string = keyServesFilePath()): 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/** What one key last advertised, or undefined when it was never listed. */\nexport function servesOf(\n document: KeyServesDocument,\n route: string,\n ref: string,\n): readonly string[] | undefined {\n return document.providers[route]?.[ref]?.models\n}\n\n/**\n * One route's observations, keyed by reference \u2014 the shape `canServe` reads.\n * @param document - the observation document.\n * @param route - the provider route.\n */\nexport function servesOfRoute(\n document: KeyServesDocument,\n route: string,\n): ReadonlyMap<string, readonly string[]> {\n const entries = document.providers[route] ?? {}\n return new Map(Object.entries(entries).map(([ref, entry]) => [ref, entry.models]))\n}\n\n/**\n * Record one key's listing, replacing whatever it said before. A key with an\n * empty catalogue is dropped from the document: an empty list would assert\n * \"serves nothing\", which is the reading this module exists to avoid.\n * @param document - the current document.\n * @param route - the provider route.\n * @param ref - the credential reference.\n * @param models - the listing's model ids.\n * @param at - when the listing was read (epoch ms).\n */\nexport function withServes(\n document: KeyServesDocument,\n route: string,\n ref: string,\n models: readonly string[],\n at: number,\n): KeyServesDocument {\n const ids = [...new Set(models.map(normalizeModelId).filter((id): id is string => id !== undefined))]\n .slice(0, MODELS_PER_KEY)\n const current = document.providers[route] ?? {}\n const next: Record<string, KeyServesEntry> = { ...current }\n if (ids.length === 0) delete next[ref]\n else next[ref] = { models: ids, at }\n return { version: 1, providers: { ...document.providers, [route]: next } }\n}\n\n/**\n * Forget one key's observations, for a key that was removed or re-pointed.\n * @param document - the current document.\n * @param route - the provider route.\n * @param ref - the credential reference.\n */\nexport function withoutServes(document: KeyServesDocument, route: string, ref: string): KeyServesDocument {\n const current = document.providers[route]\n if (current === undefined || current[ref] === undefined) return document\n const next = { ...current }\n delete next[ref]\n const providers = { ...document.providers }\n if (Object.keys(next).length === 0) delete providers[route]\n else providers[route] = next\n return { version: 1, providers }\n}\n", "/**\n * The UI-order document: the sequence the user set by dragging the provider\n * rows, and every provider's model-row sequence, mirrored host-side.\n *\n * The live preference lives in the browser half's localStorage\n * (provider-order.ts / model-order.ts) \u2014 fast, and shared across tabs through\n * storage events. localStorage does not travel, though, and the orderings are\n * exactly the kind of setting a user wants on every machine, so the document\n * is mirrored into `<DSH_HOME>/dsh-model-think-level/ui-order.json` beside the\n * key index: a file the user can carry through any sync mechanism. The client\n * is the only writer (it pulls at boot and pushes every drag, last-writer-wins\n * on the `savedAt` stamp); the host only reads, stores and serves it.\n *\n * The file holds no secrets \u2014 provider routes and model ids only \u2014 which is\n * what makes it safe to point a sync tool at. It is parsed leniently: an\n * unreadable or malformed document degrades to \"nothing stored\", never an\n * error, and a partial payload MERGES over what is already stored, so a\n * buggy writer cannot wipe a good file with an empty one. Every write is\n * atomic, like the key index's.\n *\n * @module dsh-model-think-level/order-store\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { harnessHome } from './key-index.js'\nimport { ORDER_FILE } from './constants.js'\n\n/** The whole synced ordering state, stamped by the writing client. */\nexport interface UiOrderDocument {\n readonly version: 1\n /**\n * Epoch ms of the writing client's last ORDER CHANGE \u2014 set by the browser\n * at change time, not by the host at write time, so machines can arbitrate\n * which side is newer. Zero means \"unstamped\" (a hand-made file).\n */\n readonly savedAt: number\n /** The dragged provider-row sequence, first row first. */\n readonly providerOrder: readonly string[]\n /** Every provider's dragged model-row sequence, keyed by provider id. */\n readonly modelOrder: Readonly<Record<string, readonly string[]>>\n /**\n * The provider ids switched OFF on the Models page. The DISABLED set, not\n * the enabled one \u2014 an empty list means \"everything is on\", which is a real\n * state a machine can hold and another machine must be able to adopt, not\n * the absence of an opinion.\n */\n readonly providersDisabled: readonly string[]\n}\n\n/** A fresh, empty document. */\nexport function emptyUiOrder(): UiOrderDocument {\n return { version: 1, savedAt: 0, providerOrder: [], modelOrder: {}, providersDisabled: [] }\n}\n\n/** Absolute path of the document beside the key index. */\nexport function uiOrderFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', ORDER_FILE)\n}\n\n/** One id, cleaned to the shape an order can carry. */\nfunction normalizeId(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const id = value.trim()\n return id.length === 0 ? undefined : id\n}\n\n/** An id sequence, de-duplicated keeping the first occurrence's position. */\nfunction normalizeIds(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n return [...new Set(value.map(normalizeId).filter((id): id is string => id !== undefined))]\n}\n\n/**\n * Parse an already-decoded payload, dropping whatever does not fit. Never\n * throws: this file is a UI preference, so a corrupt one is an empty one.\n * @param raw - the decoded JSON value (or anything else).\n */\nexport function parseUiOrder(raw: unknown): UiOrderDocument {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return emptyUiOrder()\n const record = raw as Record<string, unknown>\n const savedAt = typeof record['savedAt'] === 'number' && Number.isFinite(record['savedAt'])\n ? record['savedAt']\n : 0\n const rawProviders = record['providerOrder']\n const rawModels = record['modelOrder']\n const modelOrder: Record<string, readonly string[]> = {}\n if (typeof rawModels === 'object' && rawModels !== null && !Array.isArray(rawModels)) {\n for (const [provider, value] of Object.entries(rawModels as Record<string, unknown>)) {\n if (provider.length === 0) continue\n const ids = normalizeIds(value)\n // An entry with no nameable model left is not an order: keeping it would\n // pin the provider's rows to slots they can no longer hold.\n if (ids.length > 0) modelOrder[provider] = ids\n }\n }\n return {\n version: 1,\n savedAt,\n providerOrder: normalizeIds(rawProviders),\n modelOrder,\n providersDisabled: normalizeIds(record['providersDisabled']),\n }\n}\n\n/**\n * Fold a (possibly partial) payload over a current document: a field the\n * payload carries in a usable shape replaces the stored one, every other\n * field keeps the stored value. A writer that can only name what it knows \u2014\n * or a corrupted body \u2014 therefore can never blank a good file.\n * @param current - the stored document.\n * @param patch - the incoming payload, as posted by the client.\n * @param at - the savedAt to stamp when the payload carries no usable one.\n */\nexport function mergeUiOrder(current: UiOrderDocument, patch: unknown, at: number): UiOrderDocument {\n if (typeof patch !== 'object' || patch === null || Array.isArray(patch)) return current\n const record = patch as Record<string, unknown>\n const providers = record['providerOrder']\n const models = record['modelOrder']\n const disabled = record['providersDisabled']\n const savedAt = typeof record['savedAt'] === 'number' && Number.isFinite(record['savedAt'])\n ? record['savedAt']\n : at\n const parsedModels = parseUiOrder({\n version: 1,\n savedAt,\n providerOrder: Array.isArray(providers) ? providers : current.providerOrder,\n modelOrder: typeof models === 'object' && models !== null && !Array.isArray(models) ? models : current.modelOrder,\n // An absent field keeps the stored set; an explicit empty ARRAY is a real\n // \"everything is on\" and replaces it.\n providersDisabled: Array.isArray(disabled) ? disabled : current.providersDisabled,\n })\n return parsedModels\n}\n\n/**\n * Read the document. Never throws: an absent file and an unreadable one both\n * mean \"nothing stored yet\" \u2014 the client decides whether to adopt or to seed.\n * @param file - document path (tests pass a temp file).\n */\nexport function readUiOrder(file: string = uiOrderFilePath()): UiOrderDocument {\n try {\n return parseUiOrder(JSON.parse(readFileSync(file, 'utf8')) as unknown)\n } catch {\n return emptyUiOrder()\n }\n}\n\n/** Write the document at one path, atomically. */\nexport function writeUiOrder(document: UiOrderDocument, file: string = uiOrderFilePath()): 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/** The payload's own stamp, when it carries a usable one (0 and junk mean none). */\nfunction savedAtOf(patch: unknown): number | undefined {\n if (typeof patch !== 'object' || patch === null) return undefined\n const at = (patch as Record<string, unknown>)['savedAt']\n return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : undefined\n}\n\n/** Whether two documents say the same thing, their stamps aside. */\nexport function sameUiOrderContent(left: UiOrderDocument, right: UiOrderDocument): boolean {\n const shape = (document: UiOrderDocument): string => JSON.stringify([\n document.providerOrder,\n document.modelOrder,\n document.providersDisabled,\n ])\n return shape(left) === shape(right)\n}\n\n/**\n * Read, fold a payload over it, and write back \u2014 the POST route's whole body.\n * The read and the write bracket one synchronous section, so two overlapping\n * requests cannot interleave the read-modify-write.\n * @returns the document as it now stands on disk.\n */\nexport function commitUiOrder(patch: unknown, at: number, file: string = uiOrderFilePath()): UiOrderDocument {\n const next = mergeUiOrder(readUiOrder(file), patch, at)\n writeUiOrder(next, file)\n return next\n}\n\n/**\n * The guarded fold the route uses: a payload that is not NEWER than the stored\n * document may not rewrite it.\n *\n * `savedAt` is the arbitration every machine shares, so a push that carries an\n * older (or the same) stamp with different content is a page that never saw the\n * newer file \u2014 a second computer, or a tab whose boot answer arrived late. Letting\n * it write would flip the stored order and the switches back to what that page\n * still held, which is exactly how a disabled set \"un-syncs\" itself. The answer\n * tells the sender it lost, and carries the document that actually won so it can\n * adopt it instead of retrying.\n * @param patch - the posted payload.\n * @param at - the stamp to use when the payload carries none.\n * @param file - document path (tests pass a temp file).\n * @returns the stored document, and whether the payload was refused as stale.\n */\nexport function commitUiOrderGuarded(patch: unknown, at: number, file: string = uiOrderFilePath()): { document: UiOrderDocument, stale: boolean } {\n const current = readUiOrder(file)\n const incoming = savedAtOf(patch)\n const merged = mergeUiOrder(current, patch, at)\n if (incoming !== undefined && incoming <= current.savedAt) {\n // An old identical POST is an idempotent success, not permission to lower\n // savedAt: otherwise a later-arriving intermediate edit could win next.\n return { document: current, stale: !sameUiOrderContent(merged, current) }\n }\n const document = { ...merged, savedAt: Math.max(current.savedAt, merged.savedAt) }\n writeUiOrder(document, file)\n return { document, stale: false }\n}\n", "/**\n * The camouflage document: which client identity each provider route asks the\n * wire to present.\n *\n * It lives in the plugin's own home directory rather than in the pi-ai profile\n * for the same reason the key index does: the official add-provider card writes\n * the WHOLE profile at `providers.<route>`, so a field the official schema does\n * not know would be dropped by the first save. It also keeps the identity out of\n * the user's `headers` dictionary \u2014 a preset expands into several headers, and\n * unfolding them into the user's own list would make \"turn it off\" a manual\n * cleanup instead of one switch.\n *\n * The document holds no secrets: route names and one of two preset names. It is\n * parsed leniently (an unreadable file means \"nothing camouflaged\") and written\n * atomically, like the key index and the UI order.\n *\n * @module dsh-model-think-level/camouflage-store\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { harnessHome } from './key-index.js'\nimport { CAMOUFLAGE_FILE } from './constants.js'\nimport { isCamouflagePreset, type CamouflagePreset } from './camouflage.js'\n\n/** The whole stored document. */\nexport interface CamouflageDocument {\n /** Schema version; a future shape can migrate by reading this. */\n readonly version: 1\n /** Route \u2192 the identity its requests present. Absent means \"as sent\". */\n readonly providers: Readonly<Record<string, CamouflagePreset>>\n}\n\n/** A fresh, empty document. */\nexport function emptyCamouflage(): CamouflageDocument {\n return { version: 1, providers: {} }\n}\n\n/** Absolute path of the document beside the key index. */\nexport function camouflageFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', CAMOUFLAGE_FILE)\n}\n\n/**\n * Parse an already-decoded document. Never throws and never trusts the input:\n * an entry with an unknown preset is dropped, so a file written by a newer\n * build costs only the settings this build cannot express.\n * @param raw - the decoded JSON value (or anything else).\n */\nexport function parseCamouflage(raw: unknown): CamouflageDocument {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return emptyCamouflage()\n const providers = (raw as Record<string, unknown>)['providers']\n if (typeof providers !== 'object' || providers === null || Array.isArray(providers)) return emptyCamouflage()\n const out: Record<string, CamouflagePreset> = {}\n for (const [route, value] of Object.entries(providers as Record<string, unknown>)) {\n if (route.length === 0) continue\n if (!isCamouflagePreset(value)) continue\n // `defineProperty` keeps `__proto__` an ordinary own key, exactly like the\n // key index does: a JSON dictionary treats every name as data.\n Object.defineProperty(out, route, { value, enumerable: true, configurable: true, writable: true })\n }\n return { version: 1, providers: out }\n}\n\n/** Read the document. Never throws; an absent file means \"nothing stored\". */\nexport function readCamouflage(file: string = camouflageFilePath()): CamouflageDocument {\n try {\n return parseCamouflage(JSON.parse(readFileSync(file, 'utf8')) as unknown)\n } catch {\n return emptyCamouflage()\n }\n}\n\n/** Write the document at one path, atomically. */\nexport function writeCamouflage(document: CamouflageDocument, file: string = camouflageFilePath()): 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 * Set or clear one route's identity.\n *\n * `undefined` removes the entry rather than storing \"off\": the document then\n * says exactly what it means, and a route deleted and re-created cannot inherit\n * a stale identity.\n * @param route - the provider route key.\n * @param preset - the identity, or undefined to clear it.\n * @param file - document path (tests pass a temp file).\n * @returns the document as it now stands on disk.\n */\nexport function setRouteCamouflage(\n route: string,\n preset: CamouflagePreset | undefined,\n file: string = camouflageFilePath(),\n): CamouflageDocument {\n const current = readCamouflage(file)\n const providers: Record<string, CamouflagePreset> = { ...current.providers }\n if (preset === undefined) delete providers[route]\n else Object.defineProperty(providers, route, { value: preset, enumerable: true, configurable: true, writable: true })\n const next: CamouflageDocument = { version: 1, providers }\n writeCamouflage(next, file)\n return next\n}\n\n/** One route's stored identity, never resolving through Object.prototype. */\nexport function camouflageOf(document: CamouflageDocument, route: string): CamouflagePreset | undefined {\n return Object.hasOwn(document.providers, route) ? document.providers[route] : undefined\n}\n", "/**\n * Request camouflage: the client identities a provider account may demand on\n * the wire, and the exact headers/bodies that make a request look like the\n * official CLI of that vendor.\n *\n * This module is deliberately pure: it owns no storage, no fetch wrapper and\n * no settings document. The host reads the per-route choice from the plugin's\n * own file (`camouflage-store.ts`), folds it into the header index as\n * `HeaderOverride.camouflage`, and the two request seams\n * (`headers-fetch.ts` for the wire headers and body, `headers-pi-ai.ts` for a\n * protocol switch) call into the planners here.\n *\n * The two identities are modelled on what gateway projects actually check, not\n * on what a browser can spoof:\n *\n * - `codex` \u2014 an OpenAI Codex CLI. The checks seen in the wild accept a\n * `codex_cli_rs/...` user agent OR an `originator: codex_cli_rs` header, and\n * then require at least one `x-codex-*` header to be present. The identity\n * therefore ships all three: the agent string, the originator, and a session\n * header carrying a stable per-process id.\n * - `claude` \u2014 a Claude Code CLI. The checks require a\n * `claude-cli/<major>.<minor>.<patch>` user agent, a non-empty `x-app`,\n * `anthropic-beta` and `anthropic-version`, a Claude Code system block in the\n * Messages body, and a parseable `metadata.user_id`. The planner supplies\n * every one of those; `anthropic-version` is normally already set by the\n * SDK and is only filled in when absent.\n *\n * Nothing here fabricates an OAuth token, an account id or a billing header:\n * a fake credential is a different failure mode (a hard 401) and is not what\n * these gates ask for. Camouflage only changes the CLIENT identity.\n *\n * @module dsh-model-think-level/camouflage\n */\n\nimport { randomUUID } from 'node:crypto'\n\n/** The identities a provider editor may pick. */\nexport type CamouflagePreset = 'codex' | 'claude'\n\n/** Every preset, in the order the editor lists them. */\nexport const CAMOUFLAGE_PRESETS: readonly CamouflagePreset[] = ['codex', 'claude']\n\n/** Whether a stored/downloaded value names a preset this build understands. */\nexport function isCamouflagePreset(value: unknown): value is CamouflagePreset {\n return value === 'codex' || value === 'claude'\n}\n\n/** A preset's display name, in the product's own words (the GUI translates). */\nexport const CAMOUFLAGE_LABEL: Readonly<Record<CamouflagePreset, string>> = {\n codex: 'Codex',\n claude: 'Claude',\n}\n\n/**\n * Pi-ai's own Claude Code version, kept in step with the installed adapter.\n *\n * The gates parse only `major.minor.patch`, so the exact patch level does not\n * have to match the vendor's latest release \u2014 but a version from the future is\n * one more thing an edge may reject, so the adapter's constant is the source.\n */\nconst CLAUDE_CLI_VERSION = '2.1.251'\n/** A Codex CLI release number in the shape the gate's version parser accepts. */\nconst CODEX_CLI_VERSION = '0.55.0'\n\n/**\n * One id per process, used as the session/story identity of the impersonated\n * CLI. Stable across a whole run so retries and follow-up turns share it, the\n * way a real CLI would.\n */\nconst PROCESS_DEVICE_ID = randomUUID().replace(/-/g, '')\nconst PROCESS_SESSION_ID = randomUUID()\nconst PROCESS_CODEX_SESSION_ID = randomUUID()\n\n/** The `user-agent` a preset puts on the wire. */\nexport function camouflageUserAgent(preset: CamouflagePreset): string {\n return preset === 'codex'\n ? `codex_cli_rs/${CODEX_CLI_VERSION} (macOS 15.6; arm64)`\n : `claude-cli/${CLAUDE_CLI_VERSION} (external, cli)`\n}\n\n/**\n * Whether a URL speaks the Anthropic Messages wire, which is the only body\n * shape the Claude identity patches. Path matching (not the route's declared\n * protocol) is used because a key may switch the wire under a route.\n */\nexport function isAnthropicMessagesUrl(url: string): boolean {\n try {\n const pathname = new URL(url).pathname.replace(/\\/+$/, '')\n return pathname.endsWith('/v1/messages') || pathname.endsWith('/messages')\n } catch {\n return false\n }\n}\n\n/**\n * The headers a preset adds, as a plain record. Names are lower-case because\n * `Headers` normalises them anyway and the index comparisons are name-based.\n *\n * A value already present on the request is only replaced for the identity's\n * OWN marker headers; see {@link applyCamouflageHeaders}.\n */\nexport function camouflageHeaders(preset: CamouflagePreset): Record<string, string> {\n if (preset === 'codex') {\n return {\n 'user-agent': camouflageUserAgent('codex'),\n originator: 'codex_cli_rs',\n 'x-codex-session-id': PROCESS_CODEX_SESSION_ID,\n }\n }\n return {\n 'user-agent': camouflageUserAgent('claude'),\n 'x-app': 'cli',\n 'anthropic-version': '2023-06-01',\n 'anthropic-beta': 'claude-code-20250219',\n }\n}\n\n/**\n * Apply a preset's headers to a request. The identity's own markers are forced\n * (a leftover `user-agent` from a generic SDK is exactly what the gate rejects);\n * `anthropic-version` is only filled in when absent, because the SDK's value is\n * the protocol's own and newer than what this module could safely hard-code.\n *\n * @returns whether anything was written (the wrapper's cheap \"no patch\" test).\n */\nexport function applyCamouflageHeaders(headers: Headers, preset: CamouflagePreset): boolean {\n let changed = false\n for (const [name, value] of Object.entries(camouflageHeaders(preset))) {\n if (name === 'anthropic-version' && headers.has(name)) continue\n if (headers.get(name) === value) continue\n try {\n headers.set(name, value)\n changed = true\n } catch {\n // An illegal pair must not take the request down; the remaining markers\n // are still worth sending.\n }\n }\n return changed\n}\n\n/** The Claude Code identity block the Messages gate looks for. */\nexport const CLAUDE_CODE_SYSTEM_TEXT = \"You are Claude Code, Anthropic's CLI for Claude.\"\n\n/**\n * Build the `metadata.user_id` a Claude Code client sends.\n *\n * The shape is `user_<device>_account_<account>_session_<session>`; the gate\n * only requires `device_id` and `session_id` to be present, so the account\n * segment is a stable placeholder rather than a fabricated account.\n */\nexport function camouflageClaudeUserId(): string {\n return `user_${PROCESS_DEVICE_ID}_account_${PROCESS_DEVICE_ID}_session_${PROCESS_SESSION_ID}`\n}\n\n/**\n * Patch one JSON request body for a preset. Returns `undefined` when the body\n * needs no change (or is not a JSON object), so callers can keep the original\n * text and its identity.\n *\n * The Claude patch is the minimum the Messages gate reads: the identity system\n * block (prepended, keeping the caller's own blocks intact) and a parseable\n * `metadata.user_id`. Tools, images, signatures and thinking blocks are never\n * touched \u2014 corrupting them would break the agent loop the request belongs to.\n *\n * @param text - the request body, already decoded as UTF-8.\n * @param preset - the selected identity.\n * @param url - the request URL, used to decide whether this is a Messages body.\n */\nexport function patchCamouflageBody(text: string, preset: CamouflagePreset, url: string): string | undefined {\n if (preset !== 'claude') return undefined\n if (!isAnthropicMessagesUrl(url)) return undefined\n let body: unknown\n try {\n body = JSON.parse(text) as unknown\n } catch {\n return undefined\n }\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return undefined\n const record = body as Record<string, unknown>\n let changed = false\n const system = record['system']\n if (Array.isArray(system)) {\n const first = system[0]\n const firstText = typeof first === 'object' && first !== null && !Array.isArray(first)\n ? (first as Record<string, unknown>)['text']\n : undefined\n if (typeof firstText !== 'string' || !firstText.startsWith('You are Claude Code')) {\n system.unshift({ type: 'text', text: CLAUDE_CODE_SYSTEM_TEXT })\n changed = true\n }\n } else if (typeof system === 'string') {\n if (!system.startsWith('You are Claude Code')) {\n record['system'] = [\n { type: 'text', text: CLAUDE_CODE_SYSTEM_TEXT },\n { type: 'text', text: system },\n ]\n changed = true\n }\n } else {\n record['system'] = [{ type: 'text', text: CLAUDE_CODE_SYSTEM_TEXT }]\n changed = true\n }\n const metadata = record['metadata']\n const existingUserId = typeof metadata === 'object' && metadata !== null && !Array.isArray(metadata)\n ? (metadata as Record<string, unknown>)['user_id']\n : undefined\n if (typeof existingUserId !== 'string' || existingUserId.length === 0) {\n record['metadata'] = {\n ...(typeof metadata === 'object' && metadata !== null && !Array.isArray(metadata) ? metadata as Record<string, unknown> : {}),\n user_id: camouflageClaudeUserId(),\n }\n changed = true\n }\n return changed ? JSON.stringify(record) : undefined\n}\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 fetch overlay and every\n * other catalogue reader 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 (the overlay's per-key probe). */\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 }\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 * 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'\nimport type { CamouflagePreset } from './camouflage.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 * The client identity this route asks the wire to present, when the user\n * picked one in the advanced pane. Absent means \"send whatever the adapter\n * sent\" \u2014 the conservative default. The identity is stored in the plugin's\n * own document, not in the profile, so it survives an official card save.\n */\n camouflage?: CamouflagePreset\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 * Header names that must never ride a configured overlay onto the wire. Node's\n * `Headers` (unlike the browser) accepts these silently, and undici then fails\n * the whole request \u2014 a configured `transfer-encoding` kills every request the\n * route makes, and a mismatched `content-length` hangs it with no response and\n * no error. Refusing them at configuration time turns \"the route is down\" into\n * \"the header is ignored\".\n */\nconst WIRE_FORBIDDEN_HEADERS: ReadonlySet<string> = new Set([\n 'host',\n 'content-length',\n 'transfer-encoding',\n 'connection',\n 'te',\n 'trailer',\n 'upgrade',\n 'expect',\n 'keep-alive',\n 'proxy-connection',\n 'proxy-authenticate',\n 'proxy-authorization',\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 \u2014 except the wire-forbidden set\n * above, which `Headers.set()` (an editing API, not a wire validator) happily\n * accepts and the wire then chokes on.\n */\nexport function isSendableHeader(name: string, value: string): boolean {\n if (name.length === 0) return false\n if (WIRE_FORBIDDEN_HEADERS.has(name.toLowerCase())) 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.\n *\n * @param providers - the settings document's provider profiles.\n * @param camouflages - route \u2192 client identity, from the plugin's own document.\n * Optional: a deployment with no camouflage file builds exactly the index it\n * built before, and a route named here that the settings no longer carry is\n * simply never matched.\n */\nexport function buildHeaderIndex(\n providers: Record<string, Record<string, unknown>>,\n camouflages?: Readonly<Record<string, CamouflagePreset | undefined>>,\n): HeaderIndex {\n const index = emptyIndex()\n const claimedUserAgents = new Map<string, { routes: string[]; values: string[] }>()\n for (const [route, rawProfile] of Object.entries(providers)) {\n // A half-written settings document can park `null` on a provider slot;\n // one unguarded read here would throw through refreshHeaders into the\n // host's settings write path. Skip the slot, keep the plugin alive.\n if (!isRecord(rawProfile)) continue\n const profile: Record<string, unknown> = rawProfile\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 camouflage = camouflages !== undefined && Object.hasOwn(camouflages, route)\n ? camouflages[route]\n : undefined\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 ...(camouflage === undefined ? {} : { camouflage }),\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 * 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'\nimport { isSendableHeader } from './headers-core.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 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). */\nexport const LISTABLE_PROTOCOLS: ReadonlySet<string> = new Set([\n 'anthropic-messages',\n 'openai-completions',\n 'openai-responses',\n])\n\n/**\n * A URL safe to echo in responses: a baseURL may carry userinfo\n * (https://user:pass@host) or a key in its query (?api_key=\u2026 \u2014 a common relay\n * spelling), and failure messages must never repeat either. The path is what\n * identifies the probe; credentials live in the userinfo and the query, both\n * of which are dropped, along with the fragment. A string that is not a\n * parseable URL is replaced with a placeholder \u2014 echoing the raw input back\n * would defeat the whole point (the opaque `user:pass@host` spelling parses\n * as a non-special scheme whose userinfo setters are no-ops).\n */\nexport function displayUrl(raw: string): string {\n try {\n const url = new URL(raw)\n url.username = ''\n url.password = ''\n url.search = ''\n url.hash = ''\n // A non-special scheme ('user:pass@host' parses as scheme 'user' with an\n // opaque path and NO host) keeps its credentials in the path text, where\n // the setters above are no-ops: refuse to echo such a string at all.\n if (!url.username && !url.password && url.host === '' && /^[^\\s@/]+:[^\\s@]+@/.test(raw)) {\n return '[unparseable URL]'\n }\n return url.toString()\n } catch {\n return '[unparseable URL]'\n }\n}\n\n/**\n * Redact credential-bearing URL shapes from free-form error text: any\n * `user:password@` authority (with or without a scheme \u2014 the opaque spelling\n * parses as scheme+path and survives URL-level stripping) loses its secret.\n * Applied to upstream error messages before they reach a response body, since\n * undici's own texts quote the original URL verbatim.\n */\nexport function redactUrlSecrets(text: string): string {\n return text.replace(\n /([a-z][a-z0-9+.-]*:\\/\\/)?([^\\s'\"@/]+):([^\\s'\"@]+)@/gi,\n (match, scheme: string | undefined) => (scheme === undefined ? '[redacted]@' : `${scheme}[redacted]@`),\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).\n */\nexport function 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/**\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 * 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 // The same wire-forbidden rule the header overlay applies: a configured\n // `transfer-encoding` must be dropped here too, or the probe dies on it.\n if (!isSendableHeader(name, value)) 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 */\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). 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 (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. */\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. */\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 * Shared facts and target derivation of per-key model probing.\n *\n * A key is not tied to one protocol: a route can answer on an OpenAI-family\n * address and an Anthropic-family one, and each key may\n * pin a protocol of its own. Asking every key against the route's default wire\n * would therefore ask half of them a question their credential cannot answer \u2014\n * an Anthropic-pinned key returns `401` from an OpenAI gateway. The probe\n * targets a key may be asked of are derived 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 \u2014 wherever a per-key listing is wanted, from\n * the fetch overlay that assembles a provider's catalogue to the post-save\n * probe that auto-checks each key's scope.\n *\n * The exact rules live on {@link listingTargetsOf}, the one derivation every\n * caller shares.\n *\n * @module dsh-model-think-level/key-probe\n */\n\nimport type { EndpointFamily, RouteEndpoints, RouteProtocol } from './key-refs.js'\nimport { endpointFamilyOf } from './key-refs.js'\nimport { LISTABLE_PROTOCOLS, 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}\n\n/** One address a key's listing may be asked on. */\nexport interface ProbeTarget {\n readonly api: RouteProtocol\n readonly baseURL: string\n}\n\n/**\n * What one key's probe learned, as the catalogue merge reads it.\n */\nexport interface KeyProbeResult {\n readonly ref: string\n /**\n * The key's scope: the union of every address that answered. Undefined when\n * no address answered \u2014 the caller must then keep the previous scope rather\n * than recording \"serves nothing\".\n */\n readonly models: string[] | undefined\n}\n\n/** The per-key probe facts a target derivation reads (the routing scope's shape). */\nexport interface ProbeKeyShape {\n /** The wire this key pins, when it pins one. */\n readonly protocol?: RouteProtocol\n /** The base URL a pinned key signs against (its family's address). */\n readonly endpoint?: string\n /** The family addresses an UNPINNED key may dispatch on. */\n readonly endpoints?: RouteEndpoints\n}\n\n/**\n * The addresses one key's listing may be asked on, deduplicated by listing URL.\n *\n * The rules mirror routing (key-route-core):\n * - a pin is honoured only through its own wire; its address is the family's\n * stored endpoint when the route configured one, the route's own URL\n * otherwise (a same-family pin rides the route's address \u2014 only the wire\n * changes, and the route's URL serves that family);\n * - an unpinned key is AUTOMATIC (the request speaks the model family's own\n * wire where the provider addressed it), so it is asked on the route's wire\n * plus every cross-family address the route configured \u2014 the only way to\n * learn that the key also reaches those families' models;\n * - targets whose listing this plugin cannot read, and addresses that are\n * empty, are dropped; a gateway that spells one listing under two protocols\n * is asked once.\n */\nexport function listingTargetsOf(\n key: ProbeKeyShape,\n routeAPI: RouteProtocol,\n routeBaseURL: string,\n): ProbeTarget[] {\n const wanted: ProbeTarget[] = key.protocol !== undefined\n ? [{ api: key.protocol, baseURL: key.endpoint ?? routeBaseURL }]\n : [\n { api: routeAPI, baseURL: routeBaseURL },\n ...Object.entries(key.endpoints ?? {})\n .filter(([family]) => family !== endpointFamilyOf(routeAPI))\n .map(([family, url]) => ({ api: FAMILY_PROTOCOL[family as EndpointFamily], baseURL: url ?? '' })),\n ]\n const asked = new Set<string>()\n const distinct: ProbeTarget[] = []\n for (const target of wanted) {\n if (!LISTABLE_PROTOCOLS.has(target.api) || target.baseURL.length === 0) continue\n const url = probeListingUrl(target.baseURL, target.api)\n if (asked.has(url)) continue\n asked.add(url)\n distinct.push(target)\n }\n return distinct\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 * 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 * The family is IMAGE GENERATION (\u751F\u56FE): these models produce images from\n * prompts and cannot serve a chat turn, so the composer's model switcher\n * hides them and the row editor's modality pills stand down to the single\n * \u751F\u56FE answer. Such an entry declares `efforts: false` (a generator takes no\n * reasoning_effort) and no `input` \u2014 the two chat-input answers would read\n * it back as a vision chat model.\n */\n imageGen?: true\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 /**\n * The listing's OUTPUT-modality disclosure, normalized to lowercase strings,\n * when it named one (OpenRouter's `architecture.output_modalities` and its\n * flattened copies). This is the disclosure that answers \"is this an image\n * generator\": a model whose listing says it outputs images and not text\n * cannot serve a chat turn.\n */\n output?: 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 /** Whether the model is an image generator (\u751F\u56FE), when derivable. */\n imageGen?: boolean\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 // ---- Image-generation families (\u751F\u56FE) -----------------------------------\n // These models produce images from prompts and cannot serve a chat turn, so\n // every entry declares `imageGen: true` with `efforts: false` and NO `input`:\n // the composer's switcher hides the row and the row editor's modality pills\n // stand down to the single \u751F\u56FE answer. A relay renaming them keeps matching\n // through the name heuristic below.\n {\n id: 'openai-gpt-image',\n // 'dalle' covers aggregator spellings that strip the hyphen.\n patterns: ['gpt-image', 'dall-e', 'dalle'],\n efforts: false,\n imageGen: true,\n note: 'OpenAI \u751F\u56FE\u7CFB\uFF08gpt-image-1 / DALL\u00B7E 3\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'google-imagen',\n // '-image' keys the Gemini-native image-output generations\n // (gemini-2.5-flash-image \"nano banana\", gemini-3-pro-image\u2026), whose ids\n // carry the word as its own token; 'imagen' keys the dedicated generator.\n patterns: ['imagen', 'flash-image', 'pro-image', 'nano-banana'],\n efforts: false,\n imageGen: true,\n note: 'Google \u751F\u56FE\u7CFB\uFF08Imagen / Gemini-Image \"nano banana\"\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'black-forest-flux',\n patterns: ['flux'],\n efforts: false,\n imageGen: true,\n note: 'FLUX \u7CFB\uFF08FLUX.1 schnell/dev/pro \u7B49\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'stability-sd',\n patterns: ['stable-diffusion', 'sdxl', 'sd3'],\n efforts: false,\n imageGen: true,\n note: 'Stability \u751F\u56FE\u7CFB\uFF08Stable Diffusion / SDXL / SD3\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'zhipu-cogview',\n patterns: ['cogview'],\n efforts: false,\n imageGen: true,\n note: '\u667A\u8C31 CogView \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'aliyun-wanx',\n patterns: ['wanx'],\n efforts: false,\n imageGen: true,\n note: '\u963F\u91CC\u4E07\u76F8 Wanx \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'bytedance-seedream',\n patterns: ['seedream', 'seededit'],\n efforts: false,\n imageGen: true,\n note: '\u5B57\u8282 Seedream / SeedEdit \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'qwen-image',\n // The generation line only: 'qwen-vl' stays with the vision entry above\n // (longest-hit keeps the strictly longer 'qwen-vl' ahead where both fire).\n patterns: ['qwen-image'],\n efforts: false,\n imageGen: true,\n note: '\u901A\u4E49\u5343\u95EE Qwen-Image \u751F\u56FE\u7CFB\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\u3002',\n },\n {\n id: 'midjourney',\n patterns: ['midjourney', 'niji'],\n efforts: false,\n imageGen: true,\n note: 'Midjourney / Niji \u751F\u56FE\u7CFB\uFF08\u4E2D\u8F6C\u5E38\u89C1\uFF09\uFF1A\u56FE\u50CF\u751F\u6210\u6A21\u578B\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5BF9\u8BDD\u6A21\u578B\u4F7F\u7528\u2014\u2014\u5728\u8F93\u5165\u6846\u6A21\u578B\u5207\u6362\u5217\u8868\u4E2D\u5E26\u300C\u751F\u56FE\u300D\u6807\u8BB0\u5C55\u793A\u3002\u8BF7\u52FF\u52FE\u601D\u8003\u6863\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 *\n * A letter immediately followed by a generation digit also gains a space\n * ('qwen3' \u2192 'qwen 3'): both the haystack and the patterns go through this\n * same normalizer, so dotted spellings ('qwen3.8' \u2194 pattern 'qwen3.8') keep\n * matching while the previously-dead compact forms ('qwen3-max', 'glm4-plus',\n * 'gemini3-pro') now reach their family entries instead of falling to generic.\n */\nfunction normalizeLoose(value: string): string {\n return value\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, ' ')\n .replace(/([a-z])(\\d)/g, '$1 $2')\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 // Only the host-supported OpenAI/Anthropic protocols are inferred. Models\n // such as Gemini served through an OpenAI-compatible gateway keep that wire;\n // the plugin does not provide a native Gemini protocol.\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 RESPONSES_PROTOCOL = 'openai-responses'\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 // An IPv6 literal arrives bracketed from URL.hostname. Only loopback and\n // site-local/link-local scopes read as self-hosted; a public v6 address is\n // someone else's machine exactly as a public v4 would be.\n if (host.startsWith('[')) {\n const v6 = host.slice(1, -1)\n return v6 === '::1' || v6 === '::' || v6.startsWith('fe80:') || v6.startsWith('fc') || v6.startsWith('fd')\n }\n if (host === 'localhost' || 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 false\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/**\n * Compat switches the openai-completions gate offers and NO sibling wire\n * protocol takes (llm-pi-ai COMPLETIONS_COMPAT_GATE vs RESPONSES_COMPAT_GATE\n * and the anthropic gate). These are exactly the keys this plugin's knowledge\n * base and editors write, so a route switched off openai-completions leaves\n * them behind on its models -- and the kernel then refuses every model that\n * still carries one (\"sets compat ..., but its api is ..., which does not\n * take it\"), dropping it from the served catalog.\n */\nexport const COMPLETIONS_ONLY_COMPAT: readonly string[] = [\n 'supportsReasoningEffort',\n 'thinkingFormat',\n 'thinkingTokenBudgetField',\n 'supportsThinkingTokenBudget',\n 'vllmPriority',\n]\n\n/** The anthropic-messages gate's exclusive switch (see sanitizeCompatForProtocol). */\nexport const ANTHROPIC_ONLY_COMPAT: readonly string[] = ['forceAdaptiveThinking']\n\n/**\n * Drop the compat switches one STORED block carries that its route's wire\n * protocol does not take -- the repair for a protocol switched after the\n * switches were written: openai-completions \u2192 openai-responses leaves\n * `supportsReasoningEffort` behind, and the kernel then refuses the model at\n * catalog resolution. Returns the cleaned copy, or undefined when there is\n * nothing to drop (the common case, so a caller never writes speculatively).\n *\n * Deliberately a denylist of the keys this plugin writes, not an allowlist of\n * each gate: a hand-tuned key this plugin does not know stays exactly as\n * stored -- the same courtesy {@link sanitizeCompatForProtocol} extends to\n * suggestions. A protocol this module does not know strips nothing.\n */\nexport function stripForeignCompat(\n compat: Record<string, unknown>,\n api: string,\n): Record<string, unknown> | undefined {\n const norm = normalize(api)\n let foreign: readonly string[]\n if (norm === COMPAT_CAPABLE_PROTOCOL) foreign = ANTHROPIC_ONLY_COMPAT\n else if (norm === RESPONSES_PROTOCOL) foreign = [...COMPLETIONS_ONLY_COMPAT, ...ANTHROPIC_ONLY_COMPAT]\n else if (norm === ANTHROPIC_PROTOCOL) foreign = COMPLETIONS_ONLY_COMPAT\n else return undefined\n let stripped = false\n const copy: Record<string, unknown> = { ...compat }\n for (const key of foreign) {\n if (key in copy) {\n delete copy[key]\n stripped = true\n }\n }\n return stripped ? copy : undefined\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 // A budget field is a claim that the model consumes thinking tokens: an\n // entry that explicitly declares \"does not reason\" must never gain one,\n // whatever the endpoint shape suggests (the mistral-legacy / gpt-4o\n // self-hosted case).\n const reasoning = entry.efforts !== false\n if (compat === undefined) {\n return reasoning && isSelfHostedEndpoint(route.baseURL)\n ? { thinkingTokenBudgetField: 'thinking_token_budget' }\n : undefined\n }\n if (reasoning && 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 * Image-generation name tokens -- the last-resort tier for rows neither the\n * knowledge base nor the endpoint named: the vendor/generator tokens that\n * appear in image-generation ids. Boundary matching keeps 'flux' from hitting\n * 'afflux' and 'sd3' from hitting 'sd3x5-anything-else' spellings it should\n * still hit ('sd3.5' normalizes to 'sd3 5', where the boundary holds).\n */\nconst IMAGE_GEN_NAME_TOKENS: readonly string[] = [\n 'dall-e',\n 'dalle',\n 'gpt-image',\n 'imagen',\n 'flux',\n 'stable-diffusion',\n 'sdxl',\n 'sd3',\n 'cogview',\n 'wanx',\n 'seedream',\n 'seededit',\n 'midjourney',\n 'niji',\n 'nano-banana',\n 'image-gen',\n 'imagegen',\n 'qwen-image',\n 'grok-2-image',\n]\n\n/** Whether the id alone reads as an image generator (\u751F\u56FE) -- the lowest-confidence tier. */\nexport function inferImageGenFromName(modelId: string): boolean {\n const haystack = normalizeLoose(modelId)\n for (const token of IMAGE_GEN_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 true\n at = haystack.indexOf(needle, at + 1)\n }\n }\n return false\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 imageGen: boolean | undefined\n let contextWindow: number | undefined\n let maxTokens: number | undefined\n\n if (entry?.imageGen === true) imageGen = true\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. The\n // OUTPUT disclosure is the endpoint's word on \"is this an image generator\":\n // a listing that says the model outputs images and not text cannot serve a\n // chat turn, and one that names text output is a chat model even when a\n // relay renamed it into a generator-looking id.\n const listedInput = declaredCoreInput(endpoint?.input)\n if (listedInput !== undefined) {\n input = listedInput\n inputSource = 'endpoint'\n }\n const listedOutput = endpoint?.output\n if (listedOutput !== undefined) {\n imageGen = listedOutput.includes('image') && !listedOutput.includes('text')\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. The\n // image-generation guess stands beside it: an id that names a generator is\n // answered with the \u751F\u56FE marker instead of a vision-chat declaration.\n if (input === undefined) {\n const guessed = inferModalitiesFromName(modelId)\n if (guessed !== undefined) {\n input = guessed\n inputSource = 'heuristic'\n }\n }\n if (imageGen === undefined && inferImageGenFromName(modelId)) imageGen = true\n\n // The \u751F\u56FE answer replaces the chat-input declaration, whichever tier named\n // it: a request-modality array beside the marker would read the row back as\n // a vision chat model on every reader that ignores the marker.\n if (imageGen === true) {\n input = undefined\n inputSource = undefined\n }\n\n const modalityParts = {\n ...(input === undefined ? {} : { input }),\n ...(inputSource === undefined ? {} : { inputSource }),\n ...(imageGen === undefined ? {} : { imageGen }),\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 * Reading a provider's balance out of its balance endpoint's answer.\n *\n * Balance APIs are not standardised: a DeepSeek-compatible gateway answers\n * `balance_infos[].total_balance`, an OpenAI-compatible one usually carries\n * `total_available`, a Moonshot-style one nests `available_balance` under\n * `data`, and some return a bare number. The host therefore does not try to\n * understand a vendor: it walks the decoded JSON and picks the first value\n * whose FIELD reads like a balance, preferring the loudest spelling (`balance`)\n * over weaker synonyms (`remaining`, `credit`, `amount`) and shallower values\n * over deeper ones. A response with no recognisable field yields no reading, so\n * the page shows nothing rather than a made-up zero.\n *\n * This module is deliberately free of `node:` imports: the browser half uses\n * {@link formatBalance} to render the chip, and the host half uses\n * {@link parseBalancePayload} on the raw response. Pure functions only, so both\n * sides share one definition of \"a balance\".\n *\n * @module dsh-model-think-level/balance\n */\n\n/** A balance read from a provider endpoint. */\nexport interface BalanceReading {\n /** The amount itself, in the endpoint's own currency/unit. */\n readonly amount: number\n /** ISO code or symbol the endpoint named, when it named one. */\n readonly currency?: string\n}\n\n/**\n * Field names that mean \"balance\", strongest first. Keys are compared after\n * {@link normalizeKey}, so `total_balance`, `totalBalance` and `TOTAL-BALANCE`\n * all read as `totalbalance`.\n */\nconst BALANCE_KEYS: readonly string[] = [\n 'balance',\n 'totalbalance',\n 'availablebalance',\n 'remainingbalance',\n 'creditbalance',\n 'balanceusd',\n 'totalavailable',\n 'available',\n 'remaining',\n 'credits',\n 'credit',\n 'amount',\n 'left',\n 'remain',\n 'remainingquota',\n 'quotaremaining',\n 'remainquota',\n 'availablequota',\n 'points',\n]\n\n/** The rank of each accepted field name. Lower wins. */\nconst BALANCE_RANK = new Map(BALANCE_KEYS.map((key, index) => [key, index]))\n\n/**\n * Rank of the `total_credits - total_usage` fallback used by OpenRouter-style\n * credit APIs. It loses to every explicit balance field, wins over nothing.\n */\nconst CREDIT_PAIR_RANK = (BALANCE_RANK.get('totalavailable') ?? 0) + 0.5\n\n/** The two halves OpenRouter-style credit endpoints split a balance into. */\nconst TOTAL_CREDIT_KEYS: readonly string[] = ['totalcredits', 'totalgranted']\nconst USED_CREDIT_KEYS: readonly string[] = ['totalusage', 'totalused']\n\n/** Fields beside the amount that name its currency or unit. */\nconst CURRENCY_KEYS: readonly string[] = [\n 'currency',\n 'currencycode',\n 'currencyname',\n 'unit',\n 'unitname',\n 'symbol',\n]\n\n/** How deep and how wide a response is walked before it is given up on. */\nconst MAX_DEPTH = 8\nconst MAX_NODES = 2_000\n\n/** The largest response text worth decoding for a balance. */\nconst MAX_TEXT_LENGTH = 256_000\n\n/** A candidate value found by the walk. */\ninterface Candidate {\n readonly reading: BalanceReading\n readonly rank: number\n readonly depth: number\n readonly order: number\n}\n\n/** Fold a field name to its comparison form. */\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[\\s_-]+/g, '')\n}\n\n/**\n * Read a numeric amount out of a JSON value or a numeric string.\n *\n * Numbers must be finite; strings may carry thousands separators, a leading\n * currency symbol or a trailing currency code, but nothing else (an HTML page\n * or a date must not read as money). Anything longer than a short label is\n * refused rather than searched for a number.\n * @param value - a number or string from the response.\n * @returns the amount, or undefined when the value is not one.\n */\nfunction amountOf(value: unknown): number | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined\n if (typeof value !== 'string') return undefined\n const text = value.trim().replace(/,/g, '')\n if (text.length === 0 || text.length > 32) return undefined\n const match = /^[\\s$\u00A5\u20AC\u00A3\u20A9]*(-?\\d+(?:\\.\\d+)?)[\\sA-Za-z$\u00A5\u20AC\u00A3\u20A9]*$/.exec(text)\n if (match === null) return undefined\n const amount = Number(match[1])\n return Number.isFinite(amount) ? amount : undefined\n}\n\n/** The currency/unit a record names beside its amount, if any. */\nfunction currencyOf(record: Record<string, unknown>): string | undefined {\n for (const key of CURRENCY_KEYS) {\n const normalized = normalizeKey(key)\n for (const [field, value] of Object.entries(record)) {\n if (normalizeKey(field) !== normalized || typeof value !== 'string') continue\n const currency = value.trim()\n if (currency.length === 0 || currency.length > 16) continue\n // A three-letter ISO code is upper-cased so `usd` and `USD` render alike;\n // a symbol is kept verbatim.\n return /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : currency\n }\n }\n return undefined\n}\n\n/** One named numeric field of a record, or undefined when it holds none. */\nfunction numericField(record: Record<string, unknown>, names: readonly string[]): number | undefined {\n for (const [field, value] of Object.entries(record)) {\n if (!names.includes(normalizeKey(field))) continue\n const amount = amountOf(value)\n if (amount !== undefined) return amount\n }\n return undefined\n}\n\n/**\n * `total_credits - total_usage`, the shape OpenRouter-style credit APIs use\n * instead of a single remaining-balance field. Only answered when BOTH halves\n * are present, so half a pair never becomes money.\n */\nfunction creditPairOf(record: Record<string, unknown>): number | undefined {\n const total = numericField(record, TOTAL_CREDIT_KEYS)\n const used = numericField(record, USED_CREDIT_KEYS)\n if (total === undefined || used === undefined) return undefined\n return total - used\n}\n\n/** Walk one decoded value, collecting every balance-shaped field. */\nfunction collect(\n value: unknown,\n depth: number,\n out: Candidate[],\n budget: { nodes: number },\n order: { next: number },\n): void {\n if (depth > MAX_DEPTH || budget.nodes <= 0) return\n budget.nodes -= 1\n if (Array.isArray(value)) {\n for (const item of value) collect(item, depth + 1, out, budget, order)\n return\n }\n if (typeof value !== 'object' || value === null) return\n const record = value as Record<string, unknown>\n const currency = currencyOf(record)\n const pair = creditPairOf(record)\n if (pair !== undefined) {\n out.push({\n reading: currency === undefined ? { amount: pair } : { amount: pair, currency },\n rank: CREDIT_PAIR_RANK,\n depth,\n order: order.next++,\n })\n }\n for (const [key, entry] of Object.entries(record)) {\n const rank = BALANCE_RANK.get(normalizeKey(key))\n if (rank !== undefined) {\n const amount = amountOf(entry)\n if (amount !== undefined) {\n out.push({\n reading: currency === undefined ? { amount } : { amount, currency },\n rank,\n depth,\n order: order.next++,\n })\n // The value is the amount itself; there is nothing below it to read.\n continue\n }\n }\n collect(entry, depth + 1, out, budget, order)\n }\n}\n\n/**\n * Pick the most balance-shaped value out of a decoded response.\n * @param body - the decoded JSON value.\n * @returns the chosen reading, or undefined when no field was recognised.\n */\nfunction readingOf(body: unknown): BalanceReading | undefined {\n const out: Candidate[] = []\n collect(body, 0, out, { nodes: MAX_NODES }, { next: 0 })\n if (out.length === 0) return undefined\n // The field name outranks its depth: a shallow `total_available` is a\n // balance, while a deep `remaining` may belong to some unrelated sub-object.\n out.sort((a, b) => a.rank - b.rank || a.depth - b.depth || a.order - b.order)\n return out[0]?.reading\n}\n\n/**\n * Read one balance endpoint's raw response body.\n *\n * JSON is preferred; a body that is not JSON is accepted only when the whole\n * (trimmed) body is a number, which covers the plain-text balance endpoints.\n * @param text - the raw response body, as text.\n * @returns the reading, or undefined when nothing in it names a balance.\n */\nexport function parseBalancePayload(text: string): BalanceReading | undefined {\n const trimmed = text.trim()\n if (trimmed.length === 0 || trimmed.length > MAX_TEXT_LENGTH) return undefined\n let body: unknown\n try {\n body = JSON.parse(trimmed) as unknown\n } catch {\n const amount = amountOf(trimmed)\n return amount === undefined ? undefined : { amount }\n }\n if (typeof body === 'number') return Number.isFinite(body) ? { amount: body } : undefined\n if (typeof body === 'string') {\n const amount = amountOf(body)\n return amount === undefined ? undefined : { amount }\n }\n if (typeof body !== 'object' || body === null) return undefined\n return readingOf(body)\n}\n\n/** Currency symbols the chip can show in front of the number. */\nconst CURRENCY_SYMBOLS = new Map<string, string>([\n ['USD', '$'],\n ['US$', '$'],\n ['$', '$'],\n ['CNY', '\u00A5'],\n ['RMB', '\u00A5'],\n ['\u00A5', '\u00A5'],\n ['EUR', '\u20AC'],\n ['\u20AC', '\u20AC'],\n ['GBP', '\u00A3'],\n ['\u00A3', '\u00A3'],\n ['JPY', '\u00A5'],\n ['KRW', '\u20A9'],\n ['HKD', 'HK$'],\n ['TWD', 'NT$'],\n])\n\n/** Format an amount with at most two decimals, grouped by thousands. */\nfunction formatAmount(amount: number): string {\n const sign = amount < 0 ? '-' : ''\n const absolute = Math.abs(amount)\n const fixed = Number.isInteger(absolute)\n ? String(absolute)\n : absolute.toFixed(2).replace(/0+$/, '').replace(/\\.$/, '')\n const [whole = '0', fraction] = fixed.split('.')\n const grouped = whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return `${sign}${grouped}${fraction === undefined ? '' : `.${fraction}`}`\n}\n\n/**\n * Render a reading for the provider row: `$12.34` when the endpoint named a\n * currency the plugin knows, `12.34 USD` for other codes, and the bare number\n * when it named no currency at all.\n * @param reading - the parsed balance.\n * @returns the display text, never empty.\n */\nexport function formatBalance(reading: BalanceReading): string {\n const number = formatAmount(reading.amount)\n const currency = reading.currency?.trim() ?? ''\n if (currency.length === 0) return number\n const symbol = CURRENCY_SYMBOLS.get(currency.toUpperCase())\n if (symbol !== undefined) return `${symbol}${number}`\n return `${number} ${currency}`\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 { applyCamouflageHeaders, patchCamouflageBody } from './camouflage.js'\nimport {\n applyKeyToHeaders,\n classifyFailure,\n clearRest,\n isRestingFor,\n keyRest,\n parseRetryAfter,\n restKeyOf,\n restLast,\n shouldFailover,\n WIRE_DISPATCH_HEADER,\n type FailureKind,\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/**\n * Registry key for the DISPATCH hooks: the seam that can answer a request\n * without sending it (the image-generation wire dispatch). Kept beside the\n * header registry, but deliberately separate \u2014 a dispatch hook must run for\n * every request regardless of which routes the header index matches, and its\n * lifecycle is independent of header entries.\n */\nconst DISPATCH_REGISTRY = Symbol.for('dsh-model-think-level.dispatch-overrides')\n\n/** What a dispatch hook is told about the request it may claim. */\nexport interface DispatchContext {\n /** The request URL, as resolved by the wrapper. */\n readonly url: string\n /** The request method, uppercased (GET when neither side named one). */\n readonly method: string\n /**\n * Lazily read the request body as text. Cached; a `Request` input is cloned\n * (the caller's stream survives), an `init.body` string is taken directly,\n * and any other shape yields undefined \u2014 the hook decides what \"unreadable\"\n * means (the image dispatch lets those through rather than mis-claiming).\n */\n readonly bodyText: () => Promise<string | undefined>\n /** The fetch beneath this wrapper, avoiding recursive interception. */\n readonly send: typeof globalThis.fetch\n}\n\n/** A dispatch candidate: return a Response to fully claim the request (it is never sent); undefined passes it through. */\nexport type DispatchHook = (context: DispatchContext) => Promise<Response | undefined>\n\n/** The process-wide dispatch hook list. */\ninterface DispatchRegistry {\n readonly hooks: DispatchHook[]\n}\n\nfunction dispatchRegistryOf(): DispatchRegistry {\n const holder = globalThis as unknown as Record<symbol, DispatchRegistry | undefined>\n let registry = holder[DISPATCH_REGISTRY]\n if (registry === undefined) {\n registry = { hooks: [] }\n holder[DISPATCH_REGISTRY] = registry\n }\n return registry\n}\n\n/**\n * Register one dispatch hook. Order is registration order; the FIRST hook to\n * return a Response claims the request. @returns the remover (idempotent).\n */\nexport function registerDispatchHook(hook: DispatchHook): () => void {\n const registry = dispatchRegistryOf()\n registry.hooks.push(hook)\n return () => {\n const at = registry.hooks.indexOf(hook)\n if (at !== -1) registry.hooks.splice(at, 1)\n }\n}\n\n/** How many dispatch hooks are live (diagnostics; 0 = the seam costs nothing). */\nexport function dispatchHookCount(): number {\n return dispatchRegistryOf().hooks.length\n}\n\n/** The caller's request method, the way Fetch resolves it. */\nfunction methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {\n if (init?.method !== undefined && init.method.length > 0) return init.method.toUpperCase()\n if (typeof Request !== 'undefined' && input instanceof Request) return input.method.toUpperCase()\n return 'GET'\n}\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 * 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\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/**\n * The caller's request as it should leave the wrapper when this layer does NOT\n * claim it: identical to what came in, except an internal wire-dispatch marker\n * (see WIRE_DISPATCH_HEADER) is stripped. The wire seam marks the requests it\n * has already signed \u2014 including ones this layer will never match (a key\n * endpoint on another origin than the route's base URL leaves the index\n * empty) \u2014 and a marker that survives a passthrough ships an internal\n * identifier upstream. Unmarked requests come back untouched, so the plain\n * passthrough keeps the caller's exact object identity.\n */\nfunction passthroughInit(input: RequestInfo | URL, init: RequestInit | undefined): RequestInit | undefined {\n if (init?.headers === undefined || init.headers === null) return init\n const headers = new Headers(init.headers as HeadersInit)\n if (headers.get(WIRE_DISPATCH_HEADER) !== '1') return init\n headers.delete(WIRE_DISPATCH_HEADER)\n return { ...init, headers }\n}\n\n/**\n * The UTF-8 byte length of a serialized request body, for `content-length`.\n *\n * `TextEncoder` is the only length primitive guaranteed next to both the\n * browser and the Node fetch this module wraps, so the seam does not depend on\n * `Buffer` being in scope.\n */\nfunction textByteLength(text: string): number {\n return new TextEncoder().encode(text).byteLength\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, passthroughInit(input, init))\n // The dispatch seam runs BEFORE any header matching: a hook that claims\n // the request answers it without a send (the image-generation wire\n // dispatch is the user), so a claimed request never reaches the route\n // logic below. When no hook is registered this is one length check.\n const hooks = dispatchRegistryOf().hooks\n if (hooks.length > 0) {\n const context: DispatchContext = {\n url,\n method: methodOf(input, init),\n bodyText: () => bodyTextOf(input, init),\n send: base,\n }\n for (const hook of hooks) {\n let claimed: Response | undefined\n try {\n claimed = await hook(context)\n } catch {\n // A throwing hook must not take the request down: it simply does\n // not claim anything.\n claimed = undefined\n }\n if (claimed !== undefined) return claimed\n }\n }\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, passthroughInit(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, passthroughInit(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 // The client identity is applied FIRST, so the route's own stored headers\n // below still win: an operator who wants a different user-agent than the\n // preset ships can override that single value by hand.\n if (override.camouflage !== undefined && applyCamouflageHeaders(patched, override.camouflage)) {\n hasPatch = true\n }\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 // A Claude identity also has to look like Claude Code in the Messages body:\n // the gate parses the system block and `metadata.user_id`, neither of which\n // any header can carry. The transform is pure JSON-in/JSON-out and bails on\n // anything it cannot parse, so a body it does not understand is sent\n // untouched rather than mangled. Codex needs headers only.\n let camouflageBody: string | undefined\n if (override.camouflage === 'claude') {\n const text = await bodyTextOf(input, init)\n if (text !== undefined) {\n camouflageBody = patchCamouflageBody(text, 'claude', url)\n if (camouflageBody !== undefined) hasPatch = true\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, body: string | undefined = camouflageBody): Promise<Response> => {\n const headers = new Headers(patched)\n if (keyValue !== undefined) applyKeyToHeaders(headers, keyValue)\n if (body !== undefined) {\n // The patched document replaces the caller's own, so the length header\n // has to follow it or the server reads a truncated body.\n headers.set('content-length', String(textByteLength(body)))\n if (typeof Request !== 'undefined' && input instanceof Request) {\n try {\n return base(new Request(input.clone(), { ...init, body, headers }), { ...init, body, headers })\n } catch {\n // A Request body that cannot be reconstructed keeps its own copy;\n // the identity headers above are still applied.\n }\n } else {\n return base(input, { ...init, body, headers })\n }\n }\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. The marker is\n // stripped from a COPY either way: a route that declares no headers of its\n // own (the common shape) has `hasPatch === false`, and returning the\n // original input/init here would ship the internal marker upstream.\n if (patched.get(WIRE_DISPATCH_HEADER) === '1') {\n patched.delete(WIRE_DISPATCH_HEADER)\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 // A key may be benched as a whole (auth, quota, a server fault) or for this\n // model alone (a group whose plan does not carry it); either defers it.\n candidate => isRestingFor(keyRest, override.route, candidate.ref, model, Date.now()),\n )\n\n const method = init?.method ?? (typeof Request !== 'undefined' && input instanceof Request ? input.method : undefined)\n const listingRequest = isModelListingRequest(url, method)\n if (listingRequest && keyed) {\n // The create/edit form may be trying a new key against an address an\n // existing route already uses. Its explicit signature belongs to this\n // listing; replacing it with saved keys would test the wrong credential.\n const supplied = seedHeaders(input, init)\n const authNames = ['authorization', 'x-api-key', 'x-goog-api-key'] as const\n const suppliedKeys = authNames.map(name => {\n const value = supplied.get(name)\n return name === 'authorization' ? value?.replace(/^Bearer\\s+/i, '').trim() : value?.trim()\n }).filter((value): value is string => value !== undefined && value.length > 0)\n if (suppliedKeys.some(value => !keyCandidates.some(candidate => candidate.value === value))) {\n for (const name of authNames) {\n const value = supplied.get(name)\n if (value === null) patched.delete(name)\n else patched.set(name, value)\n }\n return attempt(undefined)\n }\n }\n\n if (entry.modelListing !== undefined && listingRequest && 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, passthroughInit(input, init))\n\n /**\n * Read a failed attempt's body, bounded: enough to tell \"out of quota\" and\n * \"this account does not carry the model\" from \"too fast\". Best effort \u2014 a\n * body that cannot be read still leaves the status, which is the part that\n * matters.\n */\n const failureBody = async (response: Response): Promise<string> => {\n try {\n return await readBoundedText(response, 4096)\n } catch {\n return ''\n }\n }\n\n /**\n * Charge one rejected attempt to the key that placed it: the status, the\n * provider's `Retry-After` and the body decide how long it rests \u2014 and WHAT\n * rests. An `unserved` refusal names the model, so it benches the (key,\n * model) pair and leaves the key free for the models its group does carry; a\n * refusal whose model could not be read benches nothing, because the KEY is\n * not what is known to have failed.\n */\n const chargeFailure = (candidate: KeyCandidate, response: Response, kind: FailureKind | undefined): void => {\n if (kind === undefined) return\n if (kind === 'unserved' && model === undefined) return\n const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'), Date.now())\n const restKey = kind === 'unserved'\n ? restKeyOf(override.route, candidate.ref, model)\n : restKeyOf(override.route, candidate.ref)\n keyRest.note(restKey, kind, retryAfterMs === undefined ? undefined : { retryAfterMs })\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 (response.status < 400) {\n clearRest(keyRest, override.route, solo.ref, model)\n return response\n }\n const bodyText = await failureBody(response)\n if (shouldFailover(response.status, bodyText)) {\n chargeFailure(solo, response, classifyFailure(response.status, bodyText))\n } else {\n clearRest(keyRest, override.route, solo.ref, model)\n }\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 \u2014\n // UNLESS its body names the model, which makes it a fact about this key's\n // upstream group instead (see `shouldFailover`): a relay answering \"this\n // model is not supported by any configured account in this group\" for one\n // account must be asked of the next.\n let lastFailure: unknown\n let unserved = 0\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 (response.status < 400) {\n clearRest(keyRest, override.route, candidate.ref, model)\n return response\n }\n const bodyText = await failureBody(response)\n if (!shouldFailover(response.status, bodyText)) {\n clearRest(keyRest, override.route, candidate.ref, model)\n return response\n }\n const kind = classifyFailure(response.status, bodyText)\n if (kind === 'unserved') unserved += 1\n chargeFailure(candidate, response, kind)\n if (index === keyCandidates.length - 1) {\n // Every key refused the same model: the provider's own error is the\n // truth but not the whole story, so the answer names what the plugin\n // found (see `withUnservedNote`).\n return unserved === keyCandidates.length && model !== undefined\n ? await withUnservedNote(response, bodyText, model, unserved)\n : response\n }\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/** A plain JSON object, for reading an error envelope without a shape assumption. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * The sentence appended to a route-wide model refusal: the provider's own error\n * says which group refused it, this says what that means and what to do.\n * @param model - the model every key refused.\n * @param tried - how many keys were tried.\n */\nfunction unservedNote(model: string, tried: number): string {\n return ` [dsh-model-think-level: all ${tried} keys of this provider refused model \"${model}\" \u2014 `\n + 'none of their upstream groups carries it. Add a key whose group does, or assign the model '\n + 'to a key\\'s scope in the provider\\'s Keys panel.]'\n}\n\n/**\n * Append the unserved note to the first message field of a JSON error body.\n * @returns the rewritten payload, or undefined when the body has no field to\n * append to (a shape this module does not know stays untouched).\n */\nfunction noteInto(payload: unknown, note: string): Record<string, unknown> | undefined {\n if (!isPlainObject(payload)) return undefined\n const message = payload['message']\n if (typeof message === 'string' && message.length > 0) return { ...payload, message: `${message}${note}` }\n const error = payload['error']\n if (isPlainObject(error) && typeof error['message'] === 'string' && error['message'].length > 0) {\n return { ...payload, error: { ...error, message: `${error['message']}${note}` } }\n }\n if (typeof error === 'string' && error.length > 0) return { ...payload, error: `${error}${note}` }\n return undefined\n}\n\n/**\n * The final answer when every key of a route refused the same model: the\n * provider's error, plus one sentence naming the real cause.\n *\n * A relay that fans one route out over several upstream accounts answers \"this\n * model is not supported by any configured account in this group\" per ACCOUNT,\n * so the user reads a 404 that looks like a typo in the model id while the model\n * is simply on a group another key holds. Only a JSON error body with a message\n * field is rewritten; any other shape is returned exactly as the provider sent it.\n * @param response - the last attempt's response.\n * @param bodyText - its body, already read (bounded) by the caller.\n * @param model - the model every key refused.\n * @param tried - how many keys were tried.\n */\nasync function withUnservedNote(\n response: Response,\n bodyText: string,\n model: string,\n tried: number,\n): Promise<Response> {\n const text = bodyText.length > 0 ? bodyText : await response.text().catch(() => '')\n let payload: unknown\n try {\n payload = JSON.parse(text)\n } catch {\n return response\n }\n const patched = noteInto(payload, unservedNote(model, tried))\n if (patched === undefined) return response\n const headers = new Headers(response.headers)\n // The body is re-encoded: its old length and encoding no longer describe it.\n headers.delete('content-length')\n headers.delete('content-encoding')\n headers.set('content-type', 'application/json')\n return new Response(JSON.stringify(patched), {\n status: response.status,\n statusText: response.statusText,\n headers,\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 {\n CLAUDE_CODE_SYSTEM_TEXT,\n camouflageClaudeUserId,\n camouflageHeaders,\n type CamouflagePreset,\n} from './camouflage.js'\nimport { selectOverride, type HeaderIndex, type HeaderOverride } from './headers-core.js'\nimport { anthropicRequestBaseUrl } from './listing.js'\nimport {\n classifyFailure,\n clearRest,\n isHonoured,\n isRestingFor,\n keyRest,\n planKeys,\n recordRoutePlan,\n restKeyOf,\n wireOf,\n WIRE_DISPATCH_HEADER,\n type FailureKind,\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 '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 preset's identity headers layered under the caller's own values.\n *\n * Every ordinary name keeps whatever the adapter or the route already set; only\n * the identity's own markers are added when absent. `user-agent` is the\n * exception and is always forced \u2014 it is the header the whole identity is\n * judged by, and the Harness attribution layer otherwise rewrites it. Route\n * headers are merged on top by the caller, so a hand-written value still wins.\n */\nfunction withCamouflageHeaders(merged: ProviderHeaders, preset: CamouflagePreset): ProviderHeaders {\n const identity = camouflageHeaders(preset)\n const present = new Set(Object.keys(merged).map(name => name.toLowerCase()))\n const next: ProviderHeaders = { ...merged }\n for (const [name, value] of Object.entries(identity)) {\n if (!present.has(name)) next[name] = value\n }\n next['user-agent'] = identity['user-agent'] as string\n return next\n}\n\n/**\n * Put the Claude Code identity at the front of a context's system prompt.\n *\n * Only the protocol-switch path needs this: there pi-ai re-encodes the body\n * itself, so the JSON patch in `camouflage.ts` never sees it. A context whose\n * prompt is not a plain string is left alone rather than guessed at.\n */\nfunction withClaudeIdentityContext<T>(context: T): T {\n if (!isRecord(context)) return context\n const systemPrompt = context['systemPrompt']\n if (typeof systemPrompt === 'string') {\n if (systemPrompt.startsWith('You are Claude Code')) return context\n return { ...context, systemPrompt: `${CLAUDE_CODE_SYSTEM_TEXT}\\n\\n${systemPrompt}` } as T\n }\n if (systemPrompt === undefined || systemPrompt === null) {\n return { ...context, systemPrompt: CLAUDE_CODE_SYSTEM_TEXT } as T\n }\n return context\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 const identified = override?.camouflage === undefined\n ? merged\n : withCamouflageHeaders(merged, override.camouflage)\n return override?.hasHeaders ? { ...identified, ...override.headers } : identified\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 : 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 wire may switch into Anthropic Messages, where the body is\n // re-encoded by the target implementation: the CLIENT identity has to\n // ride in the context and options instead of the JSON text.\n const switchedToClaude = protocol === 'anthropic-messages'\n && routeOverrideOf(source, model)?.camouflage === 'claude'\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 normalized = await normalizeDispatchedContext(context)\n const dispatchedContext = switchedToClaude ? withClaudeIdentityContext(normalized) : normalized\n const existingMetadata = isRecord(options['metadata']) ? options['metadata'] : undefined\n const suppliedUserId = existingMetadata?.['user_id']\n const metadata = switchedToClaude\n ? {\n ...(existingMetadata ?? {}),\n user_id: typeof suppliedUserId === 'string' && suppliedUserId.length > 0\n ? suppliedUserId\n : camouflageClaudeUserId(),\n }\n : undefined\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 ...(metadata === undefined ? {} : { metadata }),\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 => isRestingFor(keyRest, route ?? '', candidate.ref, modelId, 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 /**\n * The cooldown a failed attempt answers for. A refusal that names the\n * model is a fact about the (key, model) pair \u2014 a relay whose accounts\n * sit in different groups carries some models on one key and not the\n * other \u2014 so it benches only that pair; everything else (a bad\n * credential, a quota, a dead server) benches the key itself.\n */\n const restKeyFor = (candidate: KeyCandidate, kind: FailureKind): string =>\n kind === 'unserved' && modelId !== undefined\n ? restKeyOf(route ?? '', candidate.ref, modelId)\n : restKeyOf(route ?? '', candidate.ref)\n let lastErrorEvent: Record<string, unknown> | undefined\n let lastError: unknown\n for (const candidate of plan.ordered) {\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 const kind = classifyFailure(undefined, error instanceof Error ? error.message : '') ?? 'refused'\n keyRest.note(restKeyFor(candidate, kind), kind)\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 const kind = classifyFailure(undefined, errorTextOf(event as Record<string, unknown>)) ?? 'refused'\n keyRest.note(restKeyFor(candidate, kind), kind)\n break\n }\n committed = true\n clearRest(keyRest, route ?? '', candidate.ref, modelId)\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 image-generation config: `<DSH_HOME>/dsh-model-think-level/image.json`.\n *\n * The file holds no secrets \u2014 credential references only \u2014 which is what makes\n * it safe to keep in plain text and to hand to the MCP subprocess through one\n * `DSH_IMAGE_CONFIG` env var. Its `models[]` is a DERIVED SNAPSHOT: the source\n * of truth is the `llm-pi-ai` settings document's `inputImageGen` rows (the\n * same marker the Models page and the auto-fill write), and this file layers\n * the user's per-model overrides (endpoint verdict, param abilities, picked\n * size/quality/n) on top. Syncing keeps every override keyed by model id, so a\n * model that leaves the settings document drops out and one that comes back\n * keeps its overrides.\n *\n * Parsing follows `key-index.ts`: read-never-throw for absent files, defensive\n * field-by-field drops for malformed content, and an atomic temp-then-rename\n * write so a crash mid-write cannot leave a half-parsed config behind.\n *\n * @module dsh-model-think-level/image/config\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { IMAGE_CONFIG_FILE } from '../constants.js'\nimport { harnessHome } from '../key-index.js'\nimport { IMAGE_SIZE_TIERS } from './sizes.js'\n\n/** Endpoint verdict of one image model. `unverified` is the honest default. */\nexport type EndpointStatus = 'unverified' | 'ok' | 'unsupported'\n\n/** Wire shape the model row speaks. Only OpenAI-compatible images is wired up. */\nexport type ImageApi = 'images' | 'none'\n\n/** The conservative ability table every freshly derived row starts with. */\nexport interface ImageParams {\n readonly sizes: readonly string[]\n readonly qualities: readonly string[]\n readonly maxN: number\n /** How the endpoint wants its answer: b64 inline, an output_format field, or nothing. */\n readonly responseFormat: 'b64_json' | 'output_format' | 'none'\n}\n\n/** One derived model row, before user overrides. */\nexport interface ImageModelSeed {\n readonly id: string\n readonly route: string\n readonly modelId: string\n readonly label: string\n /** The route profile's `displayName` (the provider name the Models page\n * shows), when the profile has one; absent when the profile does not. */\n readonly providerLabel?: string\n readonly api: ImageApi\n readonly baseURL: string\n readonly keyRef?: string\n}\n\n/** One image model as the config stores it: derived facts + user overrides. */\nexport interface ImageModel {\n readonly id: string\n readonly route: string\n readonly modelId: string\n readonly label: string\n readonly providerLabel?: string\n readonly api: ImageApi\n readonly baseURL: string\n readonly keyRef?: string\n readonly endpoint: { readonly kind: 'images'; readonly status: EndpointStatus; readonly checkedAt: string | null }\n readonly params: ImageParams\n readonly lastGoodParams: ImageParams | null\n}\n\n/** The defaults every model row inherits when it does not override. */\nexport interface ImageDefaults {\n readonly size: string\n readonly quality: string\n readonly n: number\n readonly timeoutMs: number\n}\n\n/** The whole config document, exactly as it sits on disk. */\nexport interface ImageConfig {\n readonly version: 2\n /**\n * Whether the image-generation service is on. Off means the native tool is\n * not registered and every generation entry refuses; the models and image\n * params stay in the file untouched, so switching back on costs one click.\n */\n readonly enabled: boolean\n /** When `models[]` was last re-derived from the settings document. */\n readonly syncedAt: string\n /** `\"<route>/<modelId>\"` of the default model, when the user picked one. */\n readonly defaultModel: string | null\n readonly defaults: ImageDefaults\n readonly outputDir: string\n readonly models: readonly ImageModel[]\n}\n\n/** A mutable view of the config the writers build from. */\nexport type ImageConfigDraft = {\n -readonly [K in keyof ImageConfig]: ImageConfig[K]\n}\n\n/** Conservative defaults: nothing here assumes a capability the API may not have. */\nexport const IMAGE_FALLBACK_PARAMS: ImageParams = {\n sizes: IMAGE_SIZE_TIERS.map(tier => tier.value),\n qualities: ['low', 'medium', 'high', 'auto'],\n maxN: 4,\n responseFormat: 'b64_json',\n}\n\n/** Absolute path of the image config. */\nexport function imageConfigFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', IMAGE_CONFIG_FILE)\n}\n\n/** A fresh, empty config. */\nexport function emptyImageConfig(now: () => Date = () => new Date()): ImageConfig {\n return {\n version: 2,\n enabled: true,\n syncedAt: now().toISOString(),\n defaultModel: null,\n defaults: { size: '1024x1024', quality: 'high', n: 1, timeoutMs: 300_000 },\n outputDir: 'generated-images',\n models: [],\n }\n}\n\n/** Whether a value is a plain-ish object (not null, not an array). */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isSize(value: unknown): value is string {\n return typeof value === 'string' && /^\\d{2,5}x\\d{2,5}$/.test(value)\n}\n\nfunction stringList(value: unknown, limit = 32): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out = value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0).slice(0, limit)\n return out.length > 0 ? out : undefined\n}\n\nfunction parseParams(raw: unknown): ImageParams | undefined {\n if (!isRecord(raw)) return undefined\n const sizes = stringList(raw['sizes'])?.filter(isSize)\n const qualities = stringList(raw['qualities'])\n const maxN = typeof raw['maxN'] === 'number' && Number.isInteger(raw['maxN']) && raw['maxN'] >= 1\n ? Math.min(raw['maxN'], 16)\n : undefined\n const responseFormat = raw['responseFormat'] === 'output_format' || raw['responseFormat'] === 'none'\n ? raw['responseFormat']\n : raw['responseFormat'] === 'b64_json' ? 'b64_json' as const : undefined\n if (sizes === undefined && qualities === undefined && maxN === undefined && responseFormat === undefined) return undefined\n return {\n sizes: sizes ?? IMAGE_FALLBACK_PARAMS.sizes,\n qualities: qualities ?? IMAGE_FALLBACK_PARAMS.qualities,\n maxN: maxN ?? IMAGE_FALLBACK_PARAMS.maxN,\n responseFormat: responseFormat ?? IMAGE_FALLBACK_PARAMS.responseFormat,\n }\n}\n\n/**\n * Parse an already-decoded config document. Never throws and never trusts the\n * input: anything unrecognisable is dropped field by field, so a hand-edited\n * or truncated file costs at most the fields it got wrong. Overrides of model\n * rows this document does not know are kept \u2014 the next sync may re-derive them.\n */\nexport function parseImageConfig(raw: unknown, now: () => Date = () => new Date()): ImageConfig {\n const base = emptyImageConfig(now)\n if (!isRecord(raw)) return base\n const defaultsRaw = isRecord(raw['defaults']) ? raw['defaults'] : {}\n const defaults: ImageDefaults = {\n size: isSize(defaultsRaw['size']) ? defaultsRaw['size'] : base.defaults.size,\n quality: typeof defaultsRaw['quality'] === 'string' && defaultsRaw['quality'].length > 0\n ? defaultsRaw['quality']\n : base.defaults.quality,\n n: typeof defaultsRaw['n'] === 'number' && Number.isInteger(defaultsRaw['n']) && defaultsRaw['n'] >= 1\n ? Math.min(defaultsRaw['n'], 16)\n : base.defaults.n,\n timeoutMs: typeof defaultsRaw['timeoutMs'] === 'number' && defaultsRaw['timeoutMs'] >= 60_000\n ? Math.min(defaultsRaw['timeoutMs'], 3_600_000)\n : base.defaults.timeoutMs,\n }\n // A leftover `mcp` block from the retired stdio server is dropped by the\n // field-by-field parse: only known keys are read, so the stale state on\n // disk costs nothing and is rewritten away on the next save.\n const models: ImageModel[] = []\n const seen = new Set<string>()\n if (Array.isArray(raw['models'])) {\n for (const entry of raw['models']) {\n if (!isRecord(entry)) continue\n const model = parseImageModel(entry)\n if (model === undefined || seen.has(model.id)) continue\n seen.add(model.id)\n models.push(model)\n }\n }\n return {\n version: 2,\n // A config written before the switch existed has no opinion on it: the\n // shipped behaviour was \"on\", so only an explicit false turns it off.\n enabled: raw['enabled'] !== false,\n syncedAt: typeof raw['syncedAt'] === 'string' ? raw['syncedAt'] : base.syncedAt,\n defaultModel: typeof raw['defaultModel'] === 'string' && raw['defaultModel'].length > 0 ? raw['defaultModel'] : null,\n defaults,\n outputDir: typeof raw['outputDir'] === 'string' && raw['outputDir'].length > 0 ? raw['outputDir'] : base.outputDir,\n models,\n }\n}\n\nfunction parseImageModel(raw: Record<string, unknown>): ImageModel | undefined {\n const id = typeof raw['id'] === 'string' && raw['id'].length > 0 ? raw['id'] : undefined\n const route = typeof raw['route'] === 'string' && raw['route'].length > 0 ? raw['route'] : undefined\n const modelId = typeof raw['modelId'] === 'string' && raw['modelId'].length > 0 ? raw['modelId'] : undefined\n if (id === undefined || route === undefined || modelId === undefined) return undefined\n const api: ImageApi = raw['api'] === 'images' ? 'images' : 'none'\n const endpointRaw = isRecord(raw['endpoint']) ? raw['endpoint'] : {}\n const status: EndpointStatus = endpointRaw['status'] === 'ok' || endpointRaw['status'] === 'unsupported'\n ? endpointRaw['status']\n : 'unverified'\n const params = parseParams(raw['params']) ?? { ...IMAGE_FALLBACK_PARAMS }\n return {\n id,\n route,\n modelId,\n label: typeof raw['label'] === 'string' && raw['label'].length > 0 ? raw['label'] : modelId,\n ...(typeof raw['providerLabel'] === 'string' && raw['providerLabel'].length > 0 ? { providerLabel: raw['providerLabel'] } : {}),\n api,\n baseURL: typeof raw['baseURL'] === 'string' ? raw['baseURL'] : '',\n ...(typeof raw['keyRef'] === 'string' && raw['keyRef'].length > 0 ? { keyRef: raw['keyRef'] } : {}),\n endpoint: {\n kind: 'images',\n status,\n checkedAt: typeof endpointRaw['checkedAt'] === 'string' ? endpointRaw['checkedAt'] : null,\n },\n params,\n lastGoodParams: parseParams(raw['lastGoodParams']) ?? null,\n }\n}\n\n/** Read the config; an absent or unreadable file means a fresh, empty one. */\nexport function readImageConfig(file: string = imageConfigFilePath()): ImageConfig {\n let text: string\n try {\n text = readFileSync(file, 'utf8')\n } catch {\n return emptyImageConfig()\n }\n try {\n return parseImageConfig(JSON.parse(text) as unknown)\n } catch {\n // A corrupt file must not take the config surface down: start over (the\n // next sync rewrites the file with the derived snapshot).\n return emptyImageConfig()\n }\n}\n\n/** Write the config at one path, atomically (sibling temp file, then rename). */\nexport function writeImageConfig(document: ImageConfig, file: string = imageConfigFilePath()): 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 * Derive the image-model seeds from a resolved `llm-pi-ai` providers map: every\n * route's `models[]` row carrying `inputImageGen === true`, with the route's\n * api/baseURL/credential reference (and its displayName, the provider name the\n * list shows) attached. This is the SAME marker the Models\n * page editor and the auto-fill write, so both writers feed this list.\n *\n * A route whose protocol cannot carry an OpenAI-compatible images call still\n * lists its rows \u2014 marked `api: 'none'` so the UI can badge \"no compatible\n * endpoint\" and refuse generation.\n */\nexport function deriveImageSeeds(providers: Record<string, Record<string, unknown>>): ImageModelSeed[] {\n const seeds: ImageModelSeed[] = []\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile) || !Array.isArray(profile['models'])) continue\n const apiRaw = typeof profile['api'] === 'string' ? profile['api'] : ''\n // OpenAI-compatible wires can carry an images call on the same base URL;\n // Anthropic's cannot (its wire has no images endpoint at all).\n const api: ImageApi = apiRaw === 'openai-completions' || apiRaw === 'openai-responses' || apiRaw === 'openai' || apiRaw === ''\n ? 'images'\n : 'none'\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'].trim() : ''\n const keyRef = typeof profile['apiKeyEnv'] === 'string' && profile['apiKeyEnv'].length > 0 ? profile['apiKeyEnv'] : undefined\n const providerLabel = typeof profile['displayName'] === 'string' ? profile['displayName'].trim() : ''\n for (const row of profile['models']) {\n if (!isRecord(row) || row['inputImageGen'] !== true) continue\n const modelId = typeof row['id'] === 'string' ? row['id'].trim() : ''\n if (modelId.length === 0) continue\n const label = typeof row['name'] === 'string' && row['name'].trim().length > 0 ? row['name'].trim() : modelId\n const seed: ImageModelSeed = {\n id: `${route}/${modelId}`,\n route,\n modelId,\n label,\n api,\n baseURL,\n ...(providerLabel.length === 0 ? {} : { providerLabel }),\n ...(keyRef === undefined ? {} : { keyRef }),\n }\n if (!seeds.some(existing => existing.id === seed.id)) seeds.push(seed)\n }\n }\n return seeds\n}\n\n/**\n * Re-derive `models[]` from the settings document while keeping every stored\n * override keyed by model id. A derived row starts from the conservative\n * ability table; a stored row of the same id hands its overrides (endpoint\n * verdict, params, lastGoodParams) forward. Rows the settings document no\n * longer declares are dropped; defaultModel that points at a dropped model is\n * cleared.\n *\n * The old per-row size/quality/n picks are gone on purpose: the pane's params\n * row is the single place those are chosen, so a leftover pick from an older\n * build must not quietly outrank it. They are simply not carried forward.\n */\nexport function syncImageConfig(\n stored: ImageConfig,\n providers: Record<string, Record<string, unknown>>,\n now: () => Date = () => new Date(),\n): ImageConfig {\n const seeds = deriveImageSeeds(providers)\n const previous = new Map(stored.models.map(model => [model.id, model]))\n const models: ImageModel[] = seeds.map(seed => {\n const kept = previous.get(seed.id)\n const params = kept !== undefined ? kept.params : { ...IMAGE_FALLBACK_PARAMS }\n return {\n ...seed,\n endpoint: kept?.endpoint ?? { kind: 'images' as const, status: 'unverified' as const, checkedAt: null },\n params,\n lastGoodParams: kept?.lastGoodParams ?? null,\n }\n })\n const ids = new Set(models.map(model => model.id))\n // A pass that derives no row at all carries no evidence about which ids exist:\n // that is also what an empty providers map looks like before the settings\n // document is readable, and what the document looks like in the middle of a\n // rows rewrite. Clearing the picked default there is how a configured default\n // model disappears for good \u2014 the next pass re-derives the rows, but the pick\n // is already gone and nothing tells the user. Keeping it is safe: a default\n // that matches no row is never used to generate (resolveImageModel refuses it\n // and falls back to the sole candidate rule), so a stale pick cannot quietly\n // fire with some other model.\n const keepDefault = stored.defaultModel !== null\n && (models.length === 0 || ids.has(stored.defaultModel))\n return {\n ...stored,\n syncedAt: now().toISOString(),\n defaultModel: keepDefault ? stored.defaultModel : null,\n models,\n }\n}\n\n/**\n * Resolve the model a generation should use, per the design's priority:\n * an explicit pick (the dialog's current model, or a call's `model` argument)\n * wins; then the config's defaultModel; then the sole candidate when exactly\n * one exists. `undefined` when nothing resolves.\n */\nexport function resolveImageModel(\n config: ImageConfig,\n explicit?: string | undefined,\n): ImageModel | undefined {\n if (explicit !== undefined && explicit.length > 0) {\n const direct = config.models.find(model => model.id === explicit)\n if (direct !== undefined) return direct\n const byModelId = config.models.filter(model => model.modelId === explicit)\n if (byModelId.length === 1) return byModelId[0]\n const byLabel = config.models.filter(model => model.label === explicit)\n if (byLabel.length === 1) return byLabel[0]\n return undefined\n }\n if (config.defaultModel !== null) {\n const named = config.models.find(model => model.id === config.defaultModel)\n if (named !== undefined) return named\n }\n return config.models.length === 1 ? config.models[0] : undefined\n}\n\n/**\n * The params one generation uses: the call's explicit values win, then the\n * config defaults (the pane's params row). `n` is additionally clamped to the\n * model's ability table (a row that says maxN 2 never fires 8 requests).\n * `referenceImages` never comes from config \u2014 it is per-call.\n */\nexport function effectiveParams(\n config: ImageConfig,\n model: ImageModel | undefined,\n request: { size?: string; quality?: string; n?: number },\n): { size: string; quality: string; n: number } {\n const n = Math.max(1, Math.min(16, request.n ?? config.defaults.n))\n return {\n size: request.size ?? config.defaults.size,\n quality: request.quality ?? config.defaults.quality,\n n: model === undefined ? n : Math.min(n, model.params.maxN),\n }\n}\n\n/** One synchronous read-modify-write of the config file. */\nexport function updateImageConfig(\n mutate: (document: ImageConfig) => ImageConfig,\n file: string = imageConfigFilePath(),\n): ImageConfig {\n const next = mutate(readImageConfig(file))\n writeImageConfig(next, file)\n return next\n}\n", "/**\n * The image-size ladder the config pane shows: three friendly tiers over the\n * pixel values the endpoint actually receives.\n *\n * The wire stays pixel-based (`1024x1024` \u2026) \u2014 the tiers are presentation only,\n * so relaying the picked value needs no translation. Legacy sizes a config may\n * still hold (`1536x1024`, `512x512`) map to the nearest tier by longest edge;\n * ties keep the smaller tier so the UI never claims more pixels than stored.\n *\n * @module dsh-model-think-level/image/sizes\n */\n\n/** One size tier: the label the picker shows and the value the wire gets. */\nexport interface ImageSizeTier {\n readonly label: '1K' | '2K' | '4K'\n readonly value: string\n /** The longest edge in pixels; also the sort order of the ladder. */\n readonly edge: number\n}\n\n/** The ladder, smallest first. The values are the wire's `size` strings. */\nexport const IMAGE_SIZE_TIERS: readonly ImageSizeTier[] = [\n { label: '1K', value: '1024x1024', edge: 1024 },\n { label: '2K', value: '2048x2048', edge: 2048 },\n { label: '4K', value: '4096x4096', edge: 4096 },\n]\n\n/** The longest edge of a `WxH` size, or undefined for anything else. */\nexport function longestEdge(size: string): number | undefined {\n const match = /^(\\d{2,5})x(\\d{2,5})$/.exec(size.trim())\n if (match === null) return undefined\n return Math.max(Number(match[1]), Number(match[2]))\n}\n\n/** The tier a stored size maps to (unparsable sizes read as the smallest). */\nexport function tierOfSize(size: string): ImageSizeTier {\n const edge = longestEdge(size)\n let best = IMAGE_SIZE_TIERS[0]!\n if (edge === undefined) return best\n let bestDistance = Number.POSITIVE_INFINITY\n for (const tier of IMAGE_SIZE_TIERS) {\n const distance = Math.abs(tier.edge - edge)\n if (distance < bestDistance) {\n best = tier\n bestDistance = distance\n }\n }\n return best\n}\n\n/** The picker text for a stored size (`1536x1024` \u2192 `1K`). */\nexport function sizeLabel(size: string): string {\n return tierOfSize(size).label\n}\n\n/** The canonical wire value for a stored size (`1536x1024` \u2192 `1024x1024`). */\nexport function canonicalSize(size: string): string {\n return tierOfSize(size).value\n}\n", "/**\n * The image-generation core: ONE implementation of the OpenAI-compatible\n * images API call + disk write, behind three entries (the `generate_image`\n * native tool, the `/image-generate` route, the `/\u751F\u56FE` host command).\n * Anything about request construction, param fallback, sanitization or file\n * naming lives here and nowhere else.\n *\n * Endpoint choice: no reference images \u2192 `POST {baseURL}/images/generations`\n * (JSON); with reference images \u2192 `POST {baseURL}/images/edits` with a\n * hand-built multipart/form-data body (zero dependencies \u2014 the boundary is\n * constructed here, not by a library the bundle cannot carry).\n *\n * Failure taxonomy (v3): the GUI used to show an image-only key's `403\n * permission_denied` as \"API \u5BC6\u94A5\u65E0\u6548\" because the CHAT wire produced it. This\n * core never talks the chat wire, and its errors are classified \u2014 auth vs\n * image-endpoint-only permission vs missing endpoint vs param \u2014 so every entry\n * can show the operative sentence instead of the misleading one. Error text is\n * sanitized: the key value can never appear in a message, whatever shape the\n * upstream echoes back.\n *\n * @module dsh-model-think-level/image/generate\n */\n\nimport { mkdirSync, readFileSync, writeFileSync, existsSync, statSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { harnessHome } from '../key-index.js'\nimport { createImageDeadline, type ImageDeadline } from './deadline.js'\nimport {\n effectiveParams,\n readImageConfig,\n resolveImageModel,\n type ImageConfig,\n type ImageModel,\n} from './config.js'\n\n/** What a caller asks for. Everything but `prompt` is optional. */\nexport interface GenerateRequest {\n /** `\"<route>/<modelId>\"`, a bare modelId, or the label; default when omitted. */\n readonly model?: string\n readonly prompt: string\n /**\n * Caller cancellation is propagated to cooperative dependencies and bounds\n * local waiting even when they ignore it. Aborting HTTP is best effort: it\n * cannot guarantee that a remote paid job or an already-started save stops.\n */\n readonly signal?: AbortSignal\n readonly size?: string\n readonly quality?: string\n readonly n?: number\n /** Local file paths; any non-empty list switches to the edits endpoint. */\n readonly referenceImages?: readonly string[]\n /**\n * Reference images as already-decoded bytes \u2014 the attachment-backed channel:\n * the native tool resolves conversation image IDs through the attachment\n * store and hands the bytes over, so no temp file ever hits the disk. Any\n * entry here (alone or beside `referenceImages`) switches to the edits\n * endpoint.\n */\n readonly referenceFiles?: readonly {\n readonly name: string\n readonly mime: string\n readonly bytes: Uint8Array\n }[]\n /**\n * Where to land the file: a path ending in `.png` is honored EXACTLY (an\n * existing one gains a `-2` suffix \u2014 never overwritten), anything else is\n * created as a directory and receives the slug-timestamp naming. Absent\n * means the config's `outputDir`.\n */\n readonly outputPath?: string\n}\n\n/** One generated image: the b64 payload the wire returned + where it landed. */\nexport interface GeneratedImage {\n readonly filePath: string\n readonly data: string\n}\n\n/** What a successful generation reports. */\nexport interface GenerateResult {\n /**\n * Every image the wire returned, in order, each already written to disk.\n * The upstream is asked for `paramsUsed.n` images; a relay that answers\n * fewer yields fewer entries \u2014 the result never invents one.\n */\n readonly images: readonly GeneratedImage[]\n readonly mime: string\n readonly model: string\n /** The prompt this run answered (the reply's markdown alt text derives from it). */\n readonly prompt: string\n readonly paramsUsed: { readonly size: string; readonly quality: string; readonly n: number }\n /**\n * What the fallback chain had to change, in order \u2014 the \"\u56DE\u9000\u8BF4\u660E\" the reply\n * text carries. Empty when the first attempt went through untouched.\n */\n readonly revisions: readonly string[]\n}\n\n/** The classified failure `generateImage` throws (as `GenerateError`). */\nexport type GenerateFailureKind = 'config' | 'auth' | 'permission' | 'endpoint' | 'param' | 'reference' | 'upstream' | 'timeout' | 'aborted'\n\nexport class GenerateError extends Error {\n readonly kind: GenerateFailureKind\n readonly status?: number\n constructor(kind: GenerateFailureKind, message: string, status?: number) {\n super(message)\n this.name = 'GenerateError'\n this.kind = kind\n if (status !== undefined) this.status = status\n }\n}\n\n/** The faces this core needs from its host. All injectable for tests. */\nexport interface GenerateDeps {\n /** The live config; read fresh per call (the MCP path re-reads the file). */\n readonly config?: () => ImageConfig\n /** Resolve one credential reference to its value. */\n readonly resolveKey: (ref: string, signal?: AbortSignal) => Promise<string | undefined>\n /** The fetch beneath any wrapper \u2014 the images call must not be re-intercepted. */\n readonly send: typeof globalThis.fetch\n /** Base dir for relative `outputDir`s (defaults to the harness home). */\n readonly home?: () => string\n /** Persist `lastGoodParams` after a successful fallback (host: config file). */\n readonly persistLastGood?: (modelId: string, params: ImageModel['lastGoodParams']) => void\n /** Now, for file stamps (defaults to Date.now). */\n readonly now?: () => number\n /** Per-call timeout override (ms). */\n readonly timeoutMs?: number\n}\n\n/** Error classification patterns: what the fallback chain may still fix. */\nconst PARAM_ERROR_PATTERNS: readonly { readonly pattern: RegExp; readonly revision: string }[] = [\n { pattern: /response_format/i, revision: 'removed response_format' },\n { pattern: /output_format/i, revision: 'removed output_format' },\n { pattern: /\\bquality\\b/i, revision: 'lowered quality' },\n { pattern: /\\bsize\\b/i, revision: 'reset size to 1024x1024' },\n { pattern: /\\bn\\b|num_images|too many images/i, revision: 'set n to 1' },\n]\n\nconst QUALITY_LADDER: readonly string[] = ['high', 'medium', 'low']\n\n/** Strip the credential and other obvious secrets out of any error text. */\nfunction sanitize(text: string, key: string | undefined): string {\n let out = text\n if (key !== undefined && key.length >= 4) {\n // Length-independent: even a partial echo must not survive.\n out = out.split(key).join('***')\n out = out.split(encodeURIComponent(key)).join('***')\n const head = key.slice(0, 6)\n const tail = key.slice(-4)\n if (key.length > 12) out = out.split(`${head}...${tail}`).join('***')\n }\n // A bearer token pasted back by an echo, whatever it reads as.\n out = out.replace(/(?:Bearer\\s+|sk-)[A-Za-z0-9_\\-=.]{8,}/g, '***')\n return out\n}\n\n/** Read under the call's deadline, cancelling even a non-cooperative body. */\nasync function responseBytes(response: Response, deadline: ImageDeadline, limit = Infinity): Promise<Uint8Array> {\n deadline.check()\n const reader = response.body?.getReader()\n if (reader === undefined) return new Uint8Array()\n const chunks: Uint8Array[] = []\n let length = 0\n let complete = false\n try {\n while (length < limit) {\n const { done, value } = await deadline.run(() => reader.read())\n if (done) { complete = true; break }\n const chunk = value.subarray(0, limit - length)\n chunks.push(chunk)\n length += chunk.length\n }\n deadline.check()\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length }\n return bytes\n } finally {\n // Cleanup must not become another unbounded await. A rejected/late cancel\n // is consumed, and releaseLock rejects any still-pending read safely.\n if (!complete) void reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n}\n\n/** Only error snippets are bounded; successful JSON must never be truncated. */\nasync function boundedText(response: Response, deadline: ImageDeadline, limit = 4096): Promise<string> {\n try {\n return new TextDecoder().decode(await responseBytes(response, deadline, limit))\n } catch {\n deadline.check()\n return ''\n }\n}\n\n/** The upstream JSON envelope of an error, flattened to one sentence. */\nfunction upstreamMessage(body: unknown): string | undefined {\n if (typeof body === 'object' && body !== null) {\n const record = body as Record<string, unknown>\n const error = record['error']\n if (typeof error === 'string') return error\n if (typeof error === 'object' && error !== null && typeof (error as Record<string, unknown>)['message'] === 'string') {\n return (error as Record<string, unknown>)['message'] as string\n }\n if (typeof record['message'] === 'string') return record['message']\n }\n return undefined\n}\n\n/**\n * Classify one failed attempt. The 403 case is the user's actual incident: a\n * key restricted to a site's IMAGE endpoints must never read as \"invalid key\".\n * `text` arrives SANITIZED (the caller strips the credential before this sees\n * it) \u2014 every message built here flows into user-visible copy.\n */\nfunction classifyFailure(status: number, text: string): { kind: GenerateFailureKind; message: string } {\n if (status === 401 || /invalid[_\\s-]?api[_\\s-]?key/i.test(text) || /incorrect api key/i.test(text)) {\n return { kind: 'auth', message: '\u5BC6\u94A5\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF08upstream 401\uFF09' }\n }\n if (status === 403 || /permission_denied/i.test(text) || /\u4EC5\u5F00\u653E\u56FE\u7247\u63A5\u53E3/i.test(text) || /only (?:the )?image/i.test(text)) {\n return {\n kind: 'permission',\n message: '\u8BE5\u5BC6\u94A5\u88AB\u9650\u5236\u4E3A\u8BE5\u7AD9\u70B9\u7684\u56FE\u7247\u63A5\u53E3\u4E13\u7528\uFF0C\u4E0D\u80FD\u7528\u4E8E\u804A\u5929\u63A5\u53E3\u3002\u5DF2\u6539\u8D70 images \u63A5\u53E3\uFF1B\u5982\u4ECD\u5931\u8D25\uFF0C\u8BF7\u5230\u914D\u7F6E\u9875\u5BF9\u8BE5\u6A21\u578B\u6267\u884C\u300C\u6D4B\u8BD5\u300D\u3002',\n }\n }\n if (status === 404) {\n return { kind: 'endpoint', message: '\u8BE5\u4F9B\u5E94\u5546\u5730\u5740\u4E0A\u4E0D\u5B58\u5728 images \u7AEF\u70B9\uFF08404\uFF09\u2014\u2014\u8BF7\u5230\u914D\u7F6E\u9875\u786E\u8BA4\u8BE5\u6A21\u578B\u7684\u7AEF\u70B9\u7C7B\u578B' }\n }\n if (status === 429) {\n return { kind: 'upstream', message: '\u4E0A\u6E38\u9650\u6D41\uFF08429\uFF09\u2014\u2014\u8BF7\u7A0D\u540E\u91CD\u8BD5' }\n }\n if (status >= 400 && status < 500) {\n return { kind: 'param', message: text.trim().length > 0 ? text.trim().slice(0, 400) : `\u4E0A\u6E38\u62D2\u7EDD\u4E86\u8BF7\u6C42\uFF08${status}\uFF09` }\n }\n return { kind: 'upstream', message: text.trim().length > 0 ? text.trim().slice(0, 400) : `\u4E0A\u6E38\u9519\u8BEF\uFF08${status}\uFF09` }\n}\n\n/** Whether this 4xx names a param the fallback chain can drop or downgrade. */\nfunction fallbackRevisionFor(status: number, bodyText: string): string | undefined {\n if (status < 400 || status >= 500) return undefined\n for (const { pattern, revision } of PARAM_ERROR_PATTERNS) {\n if (pattern.test(bodyText)) return revision\n }\n return undefined\n}\n\n/** The multipart body of an /images/edits call, hand-built (zero deps). */\nexport function buildMultipart(\n boundary: string,\n fields: Readonly<Record<string, string>>,\n images: readonly { readonly name: string; readonly bytes: Uint8Array; readonly mime: string }[],\n): { body: Uint8Array<ArrayBuffer>; contentType: string } {\n const encoder = new TextEncoder()\n const chunks: Uint8Array[] = []\n const push = (text: string): void => { chunks.push(encoder.encode(text)) }\n for (const [name, value] of Object.entries(fields)) {\n push(`--${boundary}\\r\\n`)\n push(`Content-Disposition: form-data; name=\"${name}\"\\r\\n\\r\\n`)\n push(`${value}\\r\\n`)\n }\n images.forEach(image => {\n push(`--${boundary}\\r\\n`)\n push(`Content-Disposition: form-data; name=\"image[]\"; filename=\"${image.name.replace(/\"/g, '')}\"\\r\\n`)\n push(`Content-Type: ${image.mime}\\r\\n\\r\\n`)\n chunks.push(image.bytes)\n push(`\\r\\n`)\n })\n push(`--${boundary}--\\r\\n`)\n const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0)\n const body = new Uint8Array(total)\n let at = 0\n for (const chunk of chunks) {\n body.set(chunk, at)\n at += chunk.length\n }\n return { body, contentType: `multipart/form-data; boundary=${boundary}` }\n}\n\n/** MIME type of a reference image, by the extension the path carries. */\nfunction mimeOfPath(path: string): string {\n const lower = path.toLowerCase()\n if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg'\n if (lower.endsWith('.webp')) return 'image/webp'\n if (lower.endsWith('.gif')) return 'image/gif'\n return 'image/png'\n}\n\n/** Filesystem slug of a prompt: CJK kept, everything unsafe folded to `-`. */\nexport function promptSlug(prompt: string): string {\n const slug = prompt\n .slice(0, 40)\n .replace(/[\\r\\n]+/g, ' ')\n .replace(/[\\\\/:*?\"<>|\\u0000-\\u001f]/g, '')\n .replace(/\\s+/g, '-')\n .replace(/^-+|-+$/g, '')\n return slug.length > 0 ? slug : 'image'\n}\n\n/** The output dir for one config: absolute when configured absolute, else under home. */\nfunction outputDirOf(deps: GenerateDeps, config: ImageConfig): string {\n const home = deps.home?.() ?? harnessHome()\n const dir = config.outputDir\n if (/^([A-Za-z]:[\\\\/]|\\/)/.test(dir)) return dir\n return join(home, 'dsh-model-think-level', dir)\n}\n\n/** A file path that never overwrites: `<slug>-<ts>.png`, plus -2, -3\u2026 when taken. */\nfunction destinationOf(dir: string, slug: string, now: () => number): string {\n const base = join(dir, `${slug}-${now()}.png`)\n if (!existsSync(base)) return base\n for (let index = 2; ; index += 1) {\n const candidate = join(dir, `${slug}-${now()}-${index}.png`)\n if (!existsSync(candidate)) return candidate\n }\n}\n\n/**\n * Where this run's file lands. An explicit `.png` path is honored exactly\n * (an existing one gains a numeric suffix \u2014 the never-overwrite rule);\n * anything else \u2014 an existing directory, a trailing separator, a non-png\n * name \u2014 is created as a directory and receives the slug-timestamp naming.\n */\nexport function resolveDestination(\n requested: string | undefined,\n fallbackDir: string,\n slug: string,\n now: () => number,\n): string {\n if (requested === undefined || requested.trim().length === 0) {\n mkdirSync(fallbackDir, { recursive: true })\n return destinationOf(fallbackDir, slug, now)\n }\n const target = resolve(requested.trim())\n let isDir = false\n try {\n isDir = statSync(target).isDirectory()\n } catch {\n // Absent: classify by spelling below.\n }\n if (isDir || /[\\\\/]$/.test(target) || !target.toLowerCase().endsWith('.png')) {\n mkdirSync(target, { recursive: true })\n return destinationOf(target, slug, now)\n }\n mkdirSync(dirname(target), { recursive: true })\n if (!existsSync(target)) return target\n for (let index = 2; ; index += 1) {\n const candidate = target.replace(/\\.png$/i, `-${index}.png`)\n if (!existsSync(candidate)) return candidate\n }\n}\n\n/** The b64 payloads of a successful images answer, in the order the wire returned them. */\nasync function imagesOfAnswer(answer: unknown, send: typeof globalThis.fetch, deadline: ImageDeadline, key: string | undefined): Promise<string[]> {\n if (typeof answer !== 'object' || answer === null) throw new GenerateError('upstream', '\u4E0A\u6E38\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u5E94\u7B54\u7ED3\u6784')\n const data = (answer as Record<string, unknown>)['data']\n if (!Array.isArray(data) || data.length === 0) {\n // Some relays wrap the answer one level deeper; try the common shapes once.\n for (const nestedKey of ['images', 'output', 'result'] as const) {\n const nested = (answer as Record<string, unknown>)[nestedKey]\n if (Array.isArray(nested) && nested.length > 0) return imagesOfAnswer({ data: nested }, send, deadline, key)\n }\n throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u7F3A\u5C11 data \u6570\u7EC4')\n }\n const images: string[] = []\n for (const entry of data) {\n if (typeof entry !== 'object' || entry === null) throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u7684 data \u6570\u7EC4\u91CC\u6709\u975E\u5BF9\u8C61\u9879')\n const record = entry as Record<string, unknown>\n if (typeof record['b64_json'] === 'string' && record['b64_json'].length > 0) {\n images.push(record['b64_json'])\n continue\n }\n deadline.check()\n if (typeof record['url'] === 'string' && record['url'].length > 0) {\n try {\n const response = await deadline.run(() => send(record['url'] as string, { redirect: 'follow', signal: deadline.signal }))\n if (!response.ok) throw new GenerateError('upstream', `\u4E0B\u8F7D\u4E0A\u6E38\u56FE\u7247\u5931\u8D25\uFF08${response.status}\uFF09`)\n const bytes = await responseBytes(response, deadline)\n let binary = ''\n for (let index = 0; index < bytes.length; index += 1) binary += String.fromCharCode(bytes[index]!)\n deadline.check()\n images.push(btoa(binary))\n } catch (error) {\n deadline.check()\n if (error instanceof GenerateError) throw error\n throw new GenerateError('upstream', `\u4E0B\u8F7D\u4E0A\u6E38\u56FE\u7247\u5931\u8D25\uFF1A${sanitize(error instanceof Error ? error.message : String(error), key)}`)\n }\n continue\n }\n throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u65E2\u65E0 b64_json \u4E5F\u65E0 url')\n }\n return images\n}\n\n/** The core and native tool use identical cancellation/timeout classification. */\nexport function createGenerateDeadline(timeoutMs: number, signal?: AbortSignal): ImageDeadline {\n return createImageDeadline(timeoutMs, signal, kind => new GenerateError(kind, kind === 'aborted'\n ? '\u751F\u6210\u5DF2\u53D6\u6D88'\n : `\u751F\u6210\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09\u2014\u2014\u53EF\u5728\u914D\u7F6E\u9875\u8C03\u5927\u8D85\u65F6`))\n}\n\n/**\n * Run one generation. Reads the config fresh, resolves the model per the\n * priority chain, merges params, calls the images endpoint (with one pass of\n * the param fallback chain), decodes and writes the file.\n */\nexport async function generateImage(deps: GenerateDeps, request: GenerateRequest, sharedDeadline?: ImageDeadline): Promise<GenerateResult> {\n const config = deps.config?.() ?? readImageConfig()\n const deadline = sharedDeadline ?? createGenerateDeadline(deps.timeoutMs ?? config.defaults.timeoutMs, request.signal)\n try {\n deadline.check()\n return await generateWithinDeadline(deps, request, config, deadline)\n } catch (error) {\n deadline.check()\n throw error\n } finally {\n if (sharedDeadline === undefined) deadline.dispose()\n }\n}\n\nasync function generateWithinDeadline(deps: GenerateDeps, request: GenerateRequest, config: ImageConfig, deadline: ImageDeadline): Promise<GenerateResult> {\n // The switch is authoritative for EVERY entry (tool, `/\u751F\u56FE`, any cached\n // execute): a generation that starts after the user turned the service off\n // must not spend a paid request on a model that is no longer offered.\n if (!config.enabled) throw new GenerateError('config', '\u751F\u56FE\u670D\u52A1\u5DF2\u5173\u95ED\u2014\u2014\u53EF\u5728\u300C\u9AD8\u7EA7\u8BBE\u7F6E \u2192 \u751F\u56FE\u300D\u91CC\u91CD\u65B0\u5F00\u542F')\n const prompt = request.prompt.trim()\n if (prompt.length === 0) throw new GenerateError('param', '\u63D0\u793A\u8BCD\u4E3A\u7A7A')\n const model = resolveImageModel(config, request.model)\n if (model === undefined) {\n throw new GenerateError('config', config.models.length === 0\n ? '\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684\u751F\u56FE\u6A21\u578B\u2014\u2014\u8BF7\u5230 \u6A21\u578B\u914D\u7F6E \u2192 \u8F93\u5165\u6A21\u6001 \u52FE\u9009\u300C\u751F\u56FE\u300D\uFF0C\u6216\u5728\u63D2\u4EF6\u914D\u7F6E\u9875\u6DFB\u52A0'\n : `\u751F\u56FE\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u552F\u4E00\u5B9A\u4F4D\uFF1A${request.model ?? config.defaultModel ?? `(\u672A\u8BBE\u9ED8\u8BA4\uFF0C\u5019\u9009 ${config.models.map(candidate => candidate.id).join('\u3001')})`}\u3002\u8BF7\u5E26\u4E0A model \u53C2\u6570\uFF0C\u6216\u5230\u63D2\u4EF6\u914D\u7F6E\u9875\u628A\u5176\u4E2D\u4E00\u4E2A\u8BBE\u4E3A\u9ED8\u8BA4\u6A21\u578B`)\n }\n if (model.api !== 'images') {\n throw new GenerateError('endpoint', `\u8BE5\u6A21\u578B\uFF08${model.id}\uFF09\u7684\u534F\u8BAE\u6CA1\u6709\u517C\u5BB9\u7684 images \u7AEF\u70B9\uFF0C\u751F\u6210\u5DF2\u7981\u7528`)\n }\n if (model.baseURL.length === 0) {\n throw new GenerateError('config', `\u6A21\u578B ${model.id} \u6240\u5728\u4F9B\u5E94\u5546\u672A\u914D\u7F6E baseURL`)\n }\n const params = effectiveParams(config, model, request)\n const key = model.keyRef === undefined ? undefined : await deadline.run(() => deps.resolveKey(model.keyRef!, deadline.signal))\n if (model.keyRef !== undefined && key === undefined) {\n throw new GenerateError('auth', `\u8BE5 route\uFF08${model.route}\uFF09\u672A\u914D\u7F6E\u5BC6\u94A5\uFF08\u5F15\u7528 ${model.keyRef}\uFF09\u2014\u2014\u8BF7\u5230\u6A21\u578B\u914D\u7F6E\u9875\u586B\u5199`)\n }\n\n const base = model.baseURL.replace(/\\/+$/, '')\n const now = deps.now ?? (() => Date.now())\n // Reference images never change across the fallback loop: both channels are\n // read once, before the first attempt (a missing file fails the call up\n // front instead of after a paid round-trip).\n const referenceReads: { name: string; bytes: Uint8Array; mime: string }[] = [\n ...(request.referenceFiles ?? []).map(file => ({ name: file.name, bytes: file.bytes, mime: file.mime })),\n ...(request.referenceImages ?? []).map(path => {\n deadline.check()\n const absolute = resolve(path)\n if (!existsSync(absolute)) throw new GenerateError('reference', `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`)\n try {\n return { name: absolute.split(/[\\\\/]/).pop() ?? 'image', bytes: readFileSync(absolute), mime: mimeOfPath(absolute) }\n } catch {\n throw new GenerateError('reference', `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`)\n }\n }),\n ]\n // One fallback pass, in the design's order: drop response_format \u2192 lower\n // quality \u2192 reset size \u2192 n=1. Each revision is recorded for the reply text.\n const revisions: string[] = []\n let format: 'b64_json' | 'output_format' | 'none' = model.lastGoodParams?.responseFormat ?? model.params.responseFormat\n let quality = params.quality\n let size = params.size\n let count = params.n\n let lastFailure: { kind: GenerateFailureKind; message: string; status?: number } | undefined\n\n for (let attempt = 0; attempt < 5; attempt += 1) {\n deadline.check()\n const signal = deadline.signal\n let response: Response\n try {\n if (referenceReads.length > 0) {\n const boundary = `dsh-image-${now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n const fields: Record<string, string> = {\n prompt,\n model: model.modelId,\n n: String(count),\n size,\n }\n if (format !== 'none') fields['output_format'] = 'png'\n const { body, contentType } = buildMultipart(boundary, fields, referenceReads)\n response = await deadline.run(() => deps.send(`${base}/images/edits`, {\n method: 'POST',\n headers: {\n 'content-type': contentType,\n ...(key === undefined ? {} : { authorization: `Bearer ${key}` }),\n },\n body,\n signal,\n }))\n } else {\n const payload: Record<string, unknown> = {\n model: model.modelId,\n prompt,\n n: count,\n size,\n quality,\n }\n if (format === 'b64_json') payload['response_format'] = 'b64_json'\n if (format === 'output_format') payload['output_format'] = 'png'\n response = await deadline.run(() => deps.send(`${base}/images/generations`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...(key === undefined ? {} : { authorization: `Bearer ${key}` }),\n },\n body: JSON.stringify(payload),\n signal,\n }))\n }\n } catch (error) {\n deadline.check()\n if (error instanceof GenerateError) throw error\n const message = error instanceof Error ? error.message : String(error)\n throw new GenerateError('upstream', `\u65E0\u6CD5\u8FDE\u63A5 ${base}\uFF1A${sanitize(message, key)}`)\n }\n\n if (response.ok) {\n let answer: unknown\n try {\n answer = JSON.parse(new TextDecoder().decode(await responseBytes(response, deadline)))\n } catch {\n deadline.check()\n throw new GenerateError('upstream', '\u4E0A\u6E38\u5E94\u7B54\u4E0D\u662F\u5408\u6CD5 JSON')\n }\n const payloads = await imagesOfAnswer(answer, deps.send, deadline, key)\n // One file per returned image. Each destination is resolved only after\n // the previous file is on disk, so the never-overwrite suffixes advance\n // (`a.png`, `a-2.png`, \u2026) whatever spelling the caller chose.\n const images: GeneratedImage[] = []\n for (const data of payloads) {\n deadline.check()\n const filePath = resolveDestination(request.outputPath, outputDirOf(deps, config), promptSlug(prompt), now)\n const bytes = Uint8Array.from(atob(data), ch => ch.charCodeAt(0))\n deadline.check()\n writeFileSync(filePath, bytes)\n images.push({ filePath, data })\n }\n deadline.check()\n if (revisions.length > 0 && deps.persistLastGood !== undefined) {\n deps.persistLastGood(model.id, {\n ...model.params,\n responseFormat: format,\n sizes: model.params.sizes,\n qualities: model.params.qualities,\n maxN: model.params.maxN,\n })\n }\n deadline.check()\n return {\n images,\n mime: 'image/png',\n model: model.id,\n prompt,\n paramsUsed: { size, quality, n: count },\n revisions: [...revisions],\n }\n }\n\n const bodyText = await boundedText(response, deadline)\n let body: unknown\n try {\n body = JSON.parse(bodyText)\n } catch {\n body = undefined\n }\n // The upstream sentence first (it is the operative one), the raw body as\n // backup context \u2014 both through the sanitizer before anything downstream\n // can see them.\n const combined = sanitize([upstreamMessage(body), bodyText].filter((part): part is string =>\n typeof part === 'string' && part.length > 0).join(' '), key)\n lastFailure = classifyFailure(response.status, combined)\n // Endpoint facts are worth persisting even on a terminal failure: a 404\n // means \"no images endpoint here\", and the badge should say so.\n if (lastFailure.kind === 'endpoint') deps.persistLastGood?.(model.id, null)\n const revision = fallbackRevisionFor(response.status, bodyText)\n if (revision !== undefined && revisions.length < 4) {\n // Apply the FIRST matching downgrade the error names; the loop retries\n // with the narrowed shape, so one 4xx costs one extra attempt at most\n // per dropped param.\n if (revision === 'removed response_format' || revision === 'removed output_format') {\n if (format === 'none') continue\n revisions.push(revision)\n format = 'none'\n } else if (revision === 'lowered quality') {\n const at = QUALITY_LADDER.indexOf(quality)\n if (at === -1 || at === QUALITY_LADDER.length - 1) continue\n revisions.push(revision)\n quality = QUALITY_LADDER[at + 1]!\n } else if (revision === 'reset size to 1024x1024') {\n if (size === '1024x1024') continue\n revisions.push(revision)\n size = '1024x1024'\n } else {\n if (count === 1) continue\n revisions.push(revision)\n count = 1\n }\n continue\n }\n break\n }\n\n const failure = lastFailure ?? { kind: 'upstream' as const, message: '\u751F\u6210\u5931\u8D25' }\n throw new GenerateError(failure.kind, `\u751F\u56FE\u5931\u8D25\uFF1A${failure.message}${revisions.length > 0 ? `\uFF08\u5DF2\u56DE\u9000\uFF1A${revisions.join('\u3001')}\uFF09` : ''}`, failure.status)\n}\n", "/** One cancellable budget shared by every asynchronous phase of an image call. */\nexport interface ImageDeadline {\n readonly signal: AbortSignal\n check(): void\n run<T>(work: () => T | PromiseLike<T>): Promise<T>\n dispose(): void\n}\n\n/**\n * Factories run only after the cancellation listener is installed. The race\n * bounds even a dependency that ignores signal; both late outcomes are consumed.\n * It cannot physically stop such a dependency or preempt synchronous work.\n */\nexport function createImageDeadline(\n timeoutMs: number,\n caller: AbortSignal | undefined,\n errorFor: (kind: 'aborted' | 'timeout') => Error,\n): ImageDeadline {\n const controller = new AbortController()\n const expiresAt = Date.now() + timeoutMs\n let timer: ReturnType<typeof setTimeout> | undefined\n const forwardAbort = (): void => { controller.abort(caller?.reason) }\n const cleanup = (): void => {\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n caller?.removeEventListener('abort', forwardAbort)\n }\n controller.signal.addEventListener('abort', cleanup, { once: true })\n if (caller?.aborted === true) forwardAbort()\n else {\n caller?.addEventListener('abort', forwardAbort, { once: true })\n timer = setTimeout(() => controller.abort(new DOMException('Image deadline exceeded', 'TimeoutError')), timeoutMs)\n }\n\n const check = (): void => {\n if (caller?.aborted === true) forwardAbort()\n // Also detect an expired budget after synchronous decoding/filesystem work,\n // before the event loop has had a chance to deliver the timer callback.\n if (!controller.signal.aborted && Date.now() >= expiresAt) {\n controller.abort(new DOMException('Image deadline exceeded', 'TimeoutError'))\n }\n if (controller.signal.aborted) throw errorFor(caller?.aborted === true ? 'aborted' : 'timeout')\n }\n\n return {\n signal: controller.signal,\n check,\n run: <T>(work: () => T | PromiseLike<T>): Promise<T> => new Promise<T>((resolve, reject) => {\n let settled = false\n const finish = (done: () => void): void => {\n if (settled) return\n settled = true\n controller.signal.removeEventListener('abort', onAbort)\n done()\n }\n const onAbort = (): void => {\n try { check() } catch (error) { finish(() => reject(error)) }\n }\n try {\n check()\n controller.signal.addEventListener('abort', onAbort, { once: true })\n check()\n Promise.resolve(work()).then(value => {\n try {\n check()\n finish(() => resolve(value))\n } catch (error) { finish(() => reject(error)) }\n }, error => {\n try { check() } catch (cancelled) { error = cancelled }\n finish(() => reject(error))\n })\n } catch (error) { finish(() => reject(error)) }\n }),\n dispose: () => {\n cleanup()\n controller.signal.removeEventListener('abort', cleanup)\n },\n }\n}\n", "/**\n * The `/\u751F\u56FE` host command (the explicit entry beside the wire dispatch).\n *\n * Registered on the HOST side on purpose: the client's `commandUi.register`\n * can only run a no-argument action \u2014 a command that reads parameters would\n * fall through to `remote.commands.execute` and answer \"unknown or malformed\n * command\". The host-side `ctx.commands.register` with an `input.hint` is the\n * shape the built-in command plugins use (the dsh-command-goal precedent).\n *\n * The handler is a thin argument parser over the SHARED generation core \u2014\n * the same `generateImage` the native `generate_image` tool calls.\n *\n * @module dsh-model-think-level/image/command\n */\n\nimport { GenerateError, generateImage, type GenerateDeps, type GenerateResult } from './generate.js'\n\n/** The host `commands` service, typed structurally (no new dependency). */\nexport interface CommandsServiceLike {\n register(contribution: {\n definitionId: string\n name: string\n description: string\n input?: { hint?: string; attachments?: boolean }\n handler: (invocation: unknown) => Promise<unknown>\n }): unknown\n}\n\n/** The plugin's command definition id (the built-ins' `@deepseek-ai/<pkg>:<name>` spelling). */\nexport const IMAGEGEN_DEFINITION_ID = '@deepseek-ai/dsh-model-think-level:imagegen'\n\n/** The hint the slash menu shows under the command. */\nexport const IMAGEGEN_HINT = '[<\u6A21\u578B>] [--size 1024x1024] [--quality high] [--n 1] [--\u53C2\u8003\u56FE <\u8DEF\u5F84>] <\u63D0\u793A\u8BCD>'\n\n/** One parsed invocation. */\nexport interface ImagegenArgs {\n readonly model?: string\n readonly size?: string\n readonly quality?: string\n readonly n?: number\n readonly referenceImages: readonly string[]\n readonly prompt: string\n}\n\n/**\n * Parse one `/\u751F\u56FE` argument string. Tolerant on purpose: the model may be\n * omitted (the config default applies), an unknown option is reported (with\n * the accepted spellings \u2014 never silently ignored), and everything that is\n * neither option nor model is the prompt.\n * @throws Error naming the mistake and the accepted options.\n */\nexport function parseImagegenArgs(text: string, knownModels: readonly string[] = []): ImagegenArgs {\n const options = new Set(['--size', '--quality', '--n', '--\u53C2\u8003\u56FE', '--ref'])\n const tokens = text.trim().split(/\\s+/).filter(token => token.length > 0)\n let model: string | undefined\n const size: string[] = []\n const quality: string[] = []\n const referenceImages: string[] = []\n let n: number | undefined\n const prompt: string[] = []\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]!\n if (token.startsWith('--')) {\n const lower = token.toLowerCase()\n if (!options.has(lower)) {\n throw new Error(`\u672A\u77E5\u9009\u9879 ${token}\u3002\u53EF\u7528\uFF1A--size <\u5BBDx\u9AD8> --quality <\u6863\u4F4D> --n <\u5F20\u6570> --\u53C2\u8003\u56FE <\u8DEF\u5F84>`)\n }\n const value = tokens[index + 1]\n if (value === undefined || value.startsWith('--')) {\n throw new Error(`\u9009\u9879 ${token} \u7F3A\u5C11\u53D6\u503C\u3002\u53EF\u7528\uFF1A--size <\u5BBDx\u9AD8> --quality <\u6863\u4F4D> --n <\u5F20\u6570> --\u53C2\u8003\u56FE <\u8DEF\u5F84>`)\n }\n index += 1\n if (lower === '--size') size.push(value)\n else if (lower === '--quality') quality.push(value)\n else if (lower === '--n') {\n const parsed = Number(value)\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > 16) {\n throw new Error(`--n \u9700\u8981 1\u201316 \u7684\u6574\u6570\uFF0C\u6536\u5230\uFF1A${value}`)\n }\n n = parsed\n } else {\n referenceImages.push(value)\n }\n continue\n }\n // The first bare token is the model when it names one in the list; a\n // bare token that names nothing falls into the prompt either way (a\n // mistyped model must not swallow the prompt into a command error).\n if (model === undefined && prompt.length === 0 && knownModels.includes(token)) {\n model = token\n continue\n }\n prompt.push(token)\n }\n const joined = prompt.join(' ').trim()\n if (joined.length === 0) {\n throw new Error('\u7F3A\u5C11\u63D0\u793A\u8BCD\u3002\u7528\u6CD5\uFF1A/\u751F\u56FE [<\u6A21\u578B>] [--size 1024x1024] [--quality high] [--n 1] [--\u53C2\u8003\u56FE <\u8DEF\u5F84>] <\u63D0\u793A\u8BCD>')\n }\n return {\n ...(model === undefined ? {} : { model }),\n ...(size.length > 0 ? { size: size[size.length - 1]! } : {}),\n ...(quality.length > 0 ? { quality: quality[quality.length - 1]! } : {}),\n ...(n === undefined ? {} : { n }),\n referenceImages,\n prompt: joined,\n }\n}\n\n/**\n * What the handler needs: the live model ids (for argument disambiguation),\n * the generation deps, and an optional echo face for the session the command\n * ran in. The echo is best-effort \u2014 the command's return value is the\n * contract the host consumes; a session write is attempted only when the\n * invocation carries a session that exposes one.\n */\nexport interface ImagegenDeps {\n readonly modelIds: () => readonly string[]\n readonly generate: typeof generateImage\n readonly generateDeps: GenerateDeps\n /** Best-effort session echo (guarded; never throws into the command). */\n readonly echo?: (invocation: unknown, text: string, filePath: string) => void\n}/** Run one parsed invocation through the shared core and shape the result. */\nexport async function executeImagegen(\n deps: ImagegenDeps,\n parsed: ImagegenArgs,\n): Promise<{ ok: true; filePaths: readonly string[]; mime: string; model: string; paramsUsed: GenerateResult['paramsUsed']; text: string; warning?: string } | { ok: false; error: string }> {\n try {\n const result = await deps.generate(deps.generateDeps, {\n ...(parsed.model === undefined ? {} : { model: parsed.model }),\n prompt: parsed.prompt,\n ...(parsed.size === undefined ? {} : { size: parsed.size }),\n ...(parsed.quality === undefined ? {} : { quality: parsed.quality }),\n ...(parsed.n === undefined ? {} : { n: parsed.n }),\n ...(parsed.referenceImages.length > 0 ? { referenceImages: parsed.referenceImages } : {}),\n })\n const filePaths = result.images.map(image => image.filePath)\n const text = [\n filePaths.length === 1 ? `\u5DF2\u751F\u6210\uFF1A${filePaths[0]}` : `\u5DF2\u751F\u6210 ${filePaths.length} \u5F20\uFF1A\\n${filePaths.map(path => `- ${path}`).join('\\n')}`,\n `\u6A21\u578B ${result.model} \u00B7 size ${result.paramsUsed.size} \u00B7 quality ${result.paramsUsed.quality} \u00B7 n ${result.paramsUsed.n}`,\n result.revisions.length > 0 ? `\u53C2\u6570\u56DE\u9000\uFF1A${result.revisions.join('\u3001')}` : '',\n ].filter(line => line.length > 0).join('\\n')\n return {\n ok: true,\n filePaths,\n mime: result.mime,\n model: result.model,\n paramsUsed: result.paramsUsed,\n text,\n ...(result.revisions.length > 0 ? { warning: `\u53C2\u6570\u56DE\u9000\uFF1A${result.revisions.join('\u3001')}` } : {}),\n }\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : String(error) }\n }\n}\n\n/**\n * The invocation face the host hands the handler, narrowed to what this\n * command reads. `text` carries the arguments after the command word; the\n * exact field is spelled several ways across host versions, so each common\n * one is tried (in order) and the first non-empty wins.\n */\nexport function invocationTextOf(invocation: unknown): string {\n if (typeof invocation === 'object' && invocation !== null) {\n for (const key of ['args', 'argument', 'input', 'text', 'value'] as const) {\n const value = (invocation as Record<string, unknown>)[key]\n if (typeof value === 'string' && value.trim().length > 0) return value\n }\n }\n return ''\n}\n\n/** Register the command. @returns undefined when the host has no commands service. */\nexport function registerImagegenCommand(\n commands: CommandsServiceLike | undefined,\n deps: ImagegenDeps,\n): void {\n if (commands === undefined || typeof commands.register !== 'function') return\n try {\n commands.register({\n definitionId: IMAGEGEN_DEFINITION_ID,\n name: '\u751F\u56FE',\n description: '\u7528\u751F\u56FE\u6A21\u578B\u751F\u6210\u56FE\u7247',\n input: { hint: IMAGEGEN_HINT, attachments: true },\n handler: async invocation => {\n const known = deps.modelIds()\n let parsed: ImagegenArgs\n try {\n parsed = parseImagegenArgs(invocationTextOf(invocation), known)\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : String(error) }\n }\n const answer = await executeImagegen(deps, parsed)\n if (answer.ok) {\n // Best-effort in-session echo; the return value stays authoritative.\n try {\n deps.echo?.(invocation, answer.text, answer.filePaths[0] ?? '')\n } catch {\n // An echo face that throws must never fail a finished generation.\n }\n }\n return answer\n },\n })\n } catch {\n // A host whose command registry rejects the contribution keeps working:\n // the dispatch and the route remain.\n }\n}\n", "/**\n * The native `generate_image` tool \u2014 the conversation model's entry to the\n * shared generation core, registered through the host's own `tools` service\n * (the same in-process shape dsh-image-gen uses). Replaces the retired stdio\n * MCP server: no subprocess, no patch-file entry, no env plumbing \u2014 the tool\n * runs inside this plugin and reaches the attachment store and the credential\n * service directly.\n *\n * Contract notes that are easy to get wrong:\n * - `ctx.tools.register` REQUIRES `output: { schema, render }` \u2014 the schema\n * is enforced against the canonical value `execute` returns, so the shape\n * here and the value built below must agree exactly.\n * - image blocks ride the result CONTENT (`{type:'image', attachment}`), and\n * the host projects them to a text handle for models without image input\n * (dsh-llm `projectImagesForTextModel`) \u2014 a text-only chat model calling\n * this tool never breaks.\n * - `exec.signal` MUST reach the core: a user stop must abort the paid\n * upstream request, not just abandon the tool call.\n *\n * @module dsh-model-think-level/image/tool\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { createGenerateDeadline, generateImage, type GenerateDeps } from './generate.js'\nimport { resolveImageModel, type ImageConfig } from './config.js'\n\n/** The attachment-store face this tool needs, typed structurally. */\nexport interface ImageAttachmentsLike {\n /** Optional adapter signal; one-argument host stores still require a local deadline race. */\n saveImage(input: { data: Uint8Array; mediaType: string; name?: string }, signal?: AbortSignal):\n Promise<{ attachmentId: string; mediaType: string; bytes: number; width: number; height: number; name?: string }>\n readImage(ref: { attachmentId: string }, signal?: AbortSignal):\n Promise<{ data: Uint8Array; ref?: { name?: string; mediaType?: string } }>\n}\n\n/** The host tools service face: register and enumerate (for collision checks). */\nexport interface ImageToolsLike {\n register(definition: unknown): unknown\n schemas?: () => readonly { name: string }[]\n}\n\n/** The image-block value shape the tool's canonical value carries per image. */\nexport interface ImageToolImage {\n readonly attachment: {\n readonly attachmentId: string\n readonly mediaType: string\n readonly bytes: number\n readonly width: number\n readonly height: number\n readonly name?: string\n }\n readonly filePath: string\n}\n\n/** The tool's canonical output value (enforced by `OUTPUT_SCHEMA`). */\nexport interface ImageToolValue {\n readonly images: readonly ImageToolImage[]\n readonly model: string\n readonly prompt: string\n readonly paramsUsed: { readonly size: string; readonly quality: string; readonly n: number }\n readonly revisions: readonly string[]\n}\n\n/** The faces the tool needs. All injectable for tests. */\nexport interface ImageToolDeps {\n readonly generateDeps: GenerateDeps\n readonly attachments: ImageAttachmentsLike\n /** The live config, for the params the hint and the defaults describe. */\n readonly readConfig: () => ImageConfig\n readonly logger?: { warn(message: string): void }\n}\n\n/** The primary tool name; the fallback keeps a dsh-image-gen install working. */\nexport const IMAGE_TOOL_NAME = 'generate_image'\nexport const IMAGE_TOOL_NAME_FALLBACK = 'dsh_image_generate'\n\n/** The attachment-id spellings both accepted: canonical `sha256:\u2026` or bare digest. */\nfunction attachmentRefOf(id: string): { attachmentId: string } {\n const trimmed = id.trim()\n return { attachmentId: trimmed.startsWith('sha256:') ? trimmed : `sha256:${trimmed}` }\n}\n\n/**\n * The model-facing JSON schema of the canonical value \u2014 RAW JSON Schema only.\n *\n * `tools.register` calls `assertSupportedJsonSchema(output.schema)` without any\n * author-dialect conversion (that is `defineTool`'s job, and this plugin\n * registers directly), so the accepted vocabulary is exactly\n * type/oneOf/properties/required/additionalProperties/items/enum/const plus the\n * annotations description/title/default/examples. In particular `required` is\n * an ARRAY OF PROPERTY NAMES on an OBJECT \u2014 never a per-node boolean. Writing\n * the harness author dialect here (`required: true` inside a property) throws\n * `JsonSchemaError` out of `register`, which fails the whole tools injection\n * and leaves the tool permanently unregistered.\n */\nconst OUTPUT_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['images', 'model', 'prompt', 'paramsUsed'],\n properties: {\n images: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['attachment', 'filePath'],\n properties: {\n attachment: {\n type: 'object',\n additionalProperties: false,\n required: ['attachmentId', 'mediaType', 'bytes', 'width', 'height'],\n properties: {\n attachmentId: { type: 'string' },\n mediaType: { type: 'string' },\n bytes: { type: 'integer' },\n width: { type: 'integer' },\n height: { type: 'integer' },\n name: { type: 'string' },\n },\n },\n filePath: { type: 'string' },\n },\n },\n },\n model: { type: 'string' },\n prompt: { type: 'string' },\n paramsUsed: {\n type: 'object',\n additionalProperties: false,\n required: ['size', 'quality', 'n'],\n properties: {\n size: { type: 'string' },\n quality: { type: 'string' },\n n: { type: 'integer' },\n },\n },\n revisions: { type: 'array', items: { type: 'string' } },\n },\n}\n\n/** The model-facing argument schema \u2014 object-rooted RAW JSON Schema, same rules. */\nconst TOOL_PARAMETERS = {\n type: 'object',\n additionalProperties: false,\n required: ['prompt'],\n properties: {\n prompt: { type: 'string', description: '\u5B8C\u6574\u753B\u9762\u63CF\u8FF0\uFF1A\u4E3B\u4F53\u3001\u6784\u56FE\u3001\u98CE\u683C\u3001\u5149\u7167\uFF0C\u4EE5\u53CA\u9700\u8981\u51FA\u73B0\u7684\u6587\u5B57\u3002' },\n model: { type: 'string', description: '\u751F\u56FE\u6A21\u578B\uFF08route/modelId \u6216\u663E\u793A\u540D\uFF09\uFF1B\u7F3A\u7701\u7528\u914D\u7F6E\u9875\u7684\u9ED8\u8BA4\u6A21\u578B\uFF0C\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002' },\n size: { type: 'string', description: '\u5982 1024x1024\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\u3002\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002' },\n quality: { type: 'string', description: '\u5982 high\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\u3002\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002' },\n n: { type: 'integer', description: '\u751F\u6210\u5F20\u6570\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\uFF0C\u8D85\u8FC7\u8BE5\u6A21\u578B\u4E0A\u9650\u65F6\u62A5\u9519\u5E76\u5217\u51FA\u5141\u8BB8\u503C\u3002' },\n reference_images: { type: 'array', items: { type: 'string' }, description: '\u672C\u5730\u53C2\u8003\u56FE\u8DEF\u5F84\uFF1B\u975E\u7A7A\u8D70 /images/edits\u3002' },\n reference_attachments: { type: 'array', items: { type: 'string' }, description: '\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID\uFF08sha256:\u2026 \u6216\u88F8\u6458\u8981\uFF09\uFF1B\u4E0E\u672C\u5730\u8DEF\u5F84\u53EF\u6DF7\u7528\u3002' },\n path: { type: 'string', description: '\u843D\u76D8\u6587\u4EF6\uFF08\u4EE5 .png \u7ED3\u5C3E\uFF0C\u5B58\u5728\u5219\u81EA\u52A8\u52A0 -2 \u540E\u7F00\uFF0C\u4E0D\u8986\u76D6\uFF09\u6216\u76EE\u5F55\uFF1B\u7F3A\u7701 generated-images/<slug>-<ts>.png\u3002' },\n },\n}\n\n/** One args record narrowed from the model's JSON. Everything but prompt is optional. */\ninterface ToolArgs {\n readonly prompt: string\n readonly model?: string\n readonly size?: string\n readonly quality?: string\n readonly n?: number\n readonly referenceImages?: readonly string[]\n readonly referenceAttachments?: readonly string[]\n readonly outputPath?: string\n}\n\n/** Defensive arg narrowing: the model's JSON is untrusted, drop bad fields. */\nfunction parseArgs(raw: unknown): ToolArgs | string {\n if (typeof raw !== 'object' || raw === null) return '\u53C2\u6570\u4E0D\u662F\u5BF9\u8C61\uFF1Bprompt \u4E3A\u5FC5\u586B\u5B57\u7B26\u4E32'\n const record = raw as Record<string, unknown>\n const prompt = typeof record['prompt'] === 'string' ? record['prompt'].trim() : ''\n if (prompt.length === 0) return 'prompt \u4E3A\u5FC5\u586B\u5B57\u7B26\u4E32\u4E14\u4E0D\u80FD\u4E3A\u7A7A'\n const list = (key: string): readonly string[] | undefined => {\n const value = record[key]\n if (!Array.isArray(value)) return undefined\n const out = value.filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0)\n return out.length > 0 ? out : undefined\n }\n const n = record['n']\n return {\n prompt,\n ...(typeof record['model'] === 'string' && record['model'].trim().length > 0 ? { model: (record['model'] as string).trim() } : {}),\n ...(typeof record['size'] === 'string' && record['size'].trim().length > 0 ? { size: (record['size'] as string).trim() } : {}),\n ...(typeof record['quality'] === 'string' && record['quality'].trim().length > 0 ? { quality: (record['quality'] as string).trim() } : {}),\n ...(typeof n === 'number' && Number.isInteger(n) && n >= 1 ? { n } : {}),\n ...(list('reference_images') === undefined ? {} : { referenceImages: list('reference_images') }),\n ...(list('reference_attachments') === undefined ? {} : { referenceAttachments: list('reference_attachments') }),\n ...(typeof record['path'] === 'string' && record['path'].trim().length > 0 ? { outputPath: (record['path'] as string).trim() } : {}),\n }\n}\n\n/** The plain-JSON attachment projection the canonical value carries. */\nfunction attachmentValueOf(ref: Awaited<ReturnType<ImageAttachmentsLike['saveImage']>>): ImageToolImage['attachment'] {\n return {\n attachmentId: String(ref.attachmentId),\n mediaType: ref.mediaType,\n bytes: ref.bytes,\n width: ref.width,\n height: ref.height,\n ...(ref.name === undefined ? {} : { name: ref.name }),\n }\n}\n\n/** Shared by the tool schema, success text and system hint: cards alone are not the final reply. */\nconst IMAGE_REPLY_HINT = '\u751F\u56FE\u6210\u529F\u540E\uFF0C\u6700\u7EC8\u56DE\u590D\u5FC5\u987B\u9010\u5F20\u76F4\u63A5\u5D4C\u5165\u6240\u6709\u751F\u6210\u7684\u56FE\u7247\uFF1A\u7528\u8FD4\u56DE\u7684\u771F\u5B9E filePath \u5199 ![\u56FE\u7247\u8BF4\u660E](<filePath>)\uFF0CWindows \u8DEF\u5F84\u7528 /\u3002\u4E0D\u80FD\u53EA\u8BF4\u201C\u56FE\u7247\u5DF2\u751F\u6210/\u5DF2\u9644\u5230\u5BF9\u8BDD\u201D\uFF0C\u4E0D\u80FD\u53EA\u653E\u6587\u4EF6\u94FE\u63A5\u6216\u4F9D\u8D56\u5DE5\u5177\u5361\u7247\u3002'\n\n/** The model-facing text beside the image blocks. */\nfunction summaryText(value: ImageToolValue): string {\n const paths = value.images.map(image => image.filePath)\n const lines = [\n value.images.length === 1\n ? `\u5DF2\u751F\u6210 1 \u5F20\u56FE\u7247\uFF08${value.model}\uFF09\uFF0C\u5DF2\u9644\u5230\u5BF9\u8BDD\u3002`\n : `\u5DF2\u751F\u6210 ${value.images.length} \u5F20\u56FE\u7247\uFF08${value.model}\uFF09\uFF0C\u5DF2\u5168\u90E8\u9644\u5230\u5BF9\u8BDD\u3002`,\n `size ${value.paramsUsed.size} \u00B7 quality ${value.paramsUsed.quality} \u00B7 n ${value.paramsUsed.n}`,\n `\u843D\u76D8\uFF1A${paths.join('\u3001')}`,\n value.revisions.length > 0 ? `\u53C2\u6570\u56DE\u9000\uFF1A${value.revisions.join('\u3001')}` : '',\n IMAGE_REPLY_HINT,\n '\u53EF\u76F4\u63A5\u590D\u5236\u5230\u6700\u7EC8\u56DE\u590D\u7684\u56FE\u7247 Markdown\uFF1A',\n ...paths.map((path, index) => `![\u751F\u6210\u7684\u56FE\u7247 ${index + 1}](<${path.replace(/\\\\/g, '/')}>)`),\n '\u4E0D\u8981\u865A\u6784\u56FE\u7247 URL\uFF0C\u4E5F\u4E0D\u8981\u8C03\u7528 read\u3001glob \u6216\u5176\u4ED6\u5DE5\u5177\u53BB\u627E\u6216\u9A8C\u8BC1\u56FE\u7247\uFF1B\u76F4\u63A5\u4F7F\u7528\u4E0A\u9762\u7684\u771F\u5B9E\u8DEF\u5F84\u5D4C\u56FE\u3002',\n ]\n return lines.filter(line => line.length > 0).join('\\n')\n}\n\n/**\n * Register the native tool. The registration goes through the host's\n * `tools.register` under the primary name; a name that is already taken\n * (a dsh-image-gen install owns `generate_image`) falls back to\n * `dsh_image_generate` with one warning \u2014 a hard failure here would take the\n * whole plugin down over a name.\n * @returns the registered name (the client's keyed image card reads it back\n * over the config route) and the disposer that unregisters the tool.\n */\nexport function registerGenerateImageTool(ctx: Context, deps: ImageToolDeps): { readonly name: string; readonly dispose: () => void } {\n const tools = (ctx as unknown as { tools: ImageToolsLike }).tools\n const definitionFor = (name: string): unknown => ({\n name,\n description: `\u7528\u5F53\u524D\u914D\u7F6E\u7684\u751F\u56FE\u6A21\u578B\u751F\u6210\u56FE\u7247\u5E76\u76F4\u63A5\u9644\u5230\u5BF9\u8BDD\u3002\u7528\u6237\u8981\u753B\u56FE\u3001\u751F\u6210\u3001\u51FA\u56FE\u65F6\u8C03\u7528\uFF1B\u6539\u56FE\u8BF7\u5E26\u53C2\u8003\u56FE\u3002\u53C2\u6570\u4E00\u5F8B\u7F3A\u7701\uFF08\u8BFB\u914D\u7F6E\u9ED8\u8BA4\uFF09\uFF0C\u9664\u975E\u7528\u6237\u660E\u786E\u70B9\u540D\u3002\u4E0D\u8981\u865A\u6784\u56FE\u7247 URL\u3002${IMAGE_REPLY_HINT}`,\n parameters: TOOL_PARAMETERS,\n output: {\n schema: OUTPUT_SCHEMA,\n render: (_args: unknown, value: ImageToolValue) => [\n { type: 'text' as const, text: summaryText(value) },\n ...value.images.map(image => ({ type: 'image' as const, attachment: image.attachment })),\n ],\n presentationMeta: (_args: unknown, value: ImageToolValue) => ({\n kind: 'dsh-model-think-level-image',\n model: value.model,\n prompt: value.prompt,\n paramsUsed: value.paramsUsed,\n revisions: [...value.revisions],\n images: value.images.map(image => ({ attachment: image.attachment, filePath: image.filePath })),\n }),\n },\n async execute(rawArgs: unknown, exec: { signal: AbortSignal }): Promise<ImageToolValue> {\n const parsed = parseArgs(rawArgs)\n if (typeof parsed === 'string') throw new Error(parsed)\n // Snapshot once so references, generation and saves share the SAME budget\n // and config, rather than starting another full timeout inside the core.\n const config = deps.generateDeps.config?.() ?? deps.readConfig()\n // A stale tool definition (or an in-flight call after the switch went\n // off) fails on the switch before touching the credentials or the wire.\n if (!config.enabled) throw new Error('\u751F\u56FE\u670D\u52A1\u5DF2\u5173\u95ED\u2014\u2014\u53EF\u5728\u300C\u9AD8\u7EA7\u8BBE\u7F6E \u2192 \u751F\u56FE\u300D\u91CC\u91CD\u65B0\u5F00\u542F')\n const deadline = createGenerateDeadline(deps.generateDeps.timeoutMs ?? config.defaults.timeoutMs, exec.signal)\n try {\n deadline.check()\n // Conversation attachments become bytes, never temporary files.\n const referenceFiles = []\n for (const [index, id] of (parsed.referenceAttachments ?? []).entries()) {\n try {\n const stored = await deadline.run(() => deps.attachments.readImage(attachmentRefOf(id), deadline.signal))\n const name = stored.ref?.name ?? `reference-${index + 1}.png`\n referenceFiles.push({ name, mime: stored.ref?.mediaType ?? 'image/png', bytes: stored.data })\n } catch (error) {\n deadline.check()\n throw new Error(`\u53C2\u8003\u56FE\uFF08\u9644\u4EF6 ${id}\uFF09\u4E0D\u53EF\u8BFB\uFF1A${error instanceof Error ? error.message : String(error)}`)\n }\n }\n const result = await generateImage({ ...deps.generateDeps, config: () => config }, {\n prompt: parsed.prompt,\n ...(parsed.model === undefined ? {} : { model: parsed.model }),\n ...(parsed.size === undefined ? {} : { size: parsed.size }),\n ...(parsed.quality === undefined ? {} : { quality: parsed.quality }),\n ...(parsed.n === undefined ? {} : { n: parsed.n }),\n ...(parsed.referenceImages === undefined ? {} : { referenceImages: parsed.referenceImages }),\n ...(referenceFiles.length > 0 ? { referenceFiles } : {}),\n ...(parsed.outputPath === undefined ? {} : { outputPath: parsed.outputPath }),\n signal: deadline.signal,\n }, deadline)\n const images: ImageToolImage[] = []\n for (const image of result.images) {\n deadline.check()\n const bytes = Uint8Array.from(atob(image.data), ch => ch.charCodeAt(0))\n const attachment = await deadline.run(() => deps.attachments.saveImage({ data: bytes, mediaType: result.mime, name: 'generated-image' }, deadline.signal))\n images.push({ attachment: attachmentValueOf(attachment), filePath: image.filePath })\n }\n deadline.check()\n return {\n images,\n model: result.model,\n prompt: result.prompt,\n paramsUsed: result.paramsUsed,\n revisions: result.revisions,\n }\n } catch (error) {\n deadline.check()\n throw error\n } finally {\n deadline.dispose()\n }\n },\n presentCall: (args: unknown) => {\n const record = typeof args === 'object' && args !== null ? (args as Record<string, unknown>) : {}\n return {\n card: 'generic' as const,\n title: '\u751F\u6210\u56FE\u7247',\n kind: 'other' as const,\n rawInput: {\n prompt: typeof record['prompt'] === 'string' ? record['prompt'] : '',\n ...(typeof record['model'] === 'string' ? { model: record['model'] } : {}),\n },\n }\n },\n presentResult: (_args: unknown, result: { meta?: unknown }) => {\n const meta = result.meta as { images?: readonly { attachment: ImageToolImage['attachment'] }[] } | undefined\n const attachments = (meta?.images ?? []).map(entry => entry.attachment)\n if (attachments.length === 0) return undefined\n return {\n card: 'generic' as const,\n title: attachments.length === 1 ? '\u751F\u6210\u7684\u56FE\u7247' : `\u751F\u6210\u7684\u56FE\u7247\uFF08${attachments.length} \u5F20\uFF09`,\n content: attachments.map(attachment => ({ type: 'image' as const, attachment })),\n }\n },\n })\n\n // Collision-safe naming: the primary name first, the prefixed fallback only\n // when the registry refuses (a dsh-image-gen install owns the plain name).\n let name = IMAGE_TOOL_NAME\n let disposer: unknown\n try {\n disposer = tools.register(definitionFor(name))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (!/already registered/i.test(message)) throw error\n name = IMAGE_TOOL_NAME_FALLBACK\n deps.logger?.warn(`dsh-model-think-level: tool name \"${IMAGE_TOOL_NAME}\" is taken \u2014 registering the image tool as \"${name}\"`)\n disposer = tools.register(definitionFor(name))\n }\n return {\n name,\n dispose: () => {\n if (typeof disposer === 'function') (disposer as () => void)()\n },\n }\n}\n\n/**\n * The system-prompt hint: which tool to call, what the defaults are.\n *\n * It must describe the SAME model `resolveImageModel` will pick, or the model\n * follows the hint, omits `model`, and gets a `config` error. So the hint asks\n * the resolver itself instead of guessing `models[0]`: with no default set and\n * several candidates the resolver refuses, and the hint then has to say so \u2014\n * naming a model there is a promise the call cannot keep.\n */\nexport function imageToolHint(config: ImageConfig): string {\n // Switched off: the tool is unregistered too, so the prompt must say nothing\n // about a callable it no longer has.\n if (!config.enabled) return ''\n if (config.models.length === 0) return ''\n const defaults = `size ${config.defaults.size}\uFF0Cquality ${config.defaults.quality}\uFF0Cn ${config.defaults.n}`\n const resolved = resolveImageModel(config)\n const opening = resolved === undefined\n ? `\u751F\u56FE\u8BF7\u8C03\u7528 generate_image \u5DE5\u5177\u3002\u5F53\u524D\u6CA1\u6709\u552F\u4E00\u7684\u9ED8\u8BA4\u751F\u56FE\u6A21\u578B\uFF08\u5171 ${config.models.length} \u4E2A\u5019\u9009\uFF09\uFF0C\u8C03\u7528\u65F6\u5FC5\u987B\u663E\u5F0F\u586B model\uFF0C\u53EF\u9009\u503C\uFF1A${config.models.map((model) => model.id).join('\u3001')}\uFF1Bsize/quality/n \u53EF\u7F3A\u7701\uFF08\u9ED8\u8BA4 ${defaults}\uFF09\u3002`\n : `\u751F\u56FE\u8BF7\u8C03\u7528 generate_image \u5DE5\u5177\uFF08\u7F3A\u7701\u53C2\u6570\u5373\u53EF\uFF1A\u9ED8\u8BA4\u6A21\u578B ${resolved.id}\uFF0C${defaults}\uFF09\u3002`\n const lines = [\n opening,\n resolved === undefined\n ? '\u7528\u6237\u6CA1\u6709\u70B9\u540D\u6A21\u578B\u65F6\uFF0C\u5148\u95EE\u6E05\u7528\u54EA\u4E2A\u6A21\u578B\uFF0C\u4E0D\u8981\u81EA\u5DF1\u6311\u4E00\u4E2A\u2014\u2014\u731C\u9519\u7684\u6A21\u578B\u4F1A\u76F4\u63A5\u751F\u6210\u5931\u8D25\u3002\u6539\u56FE\u7528\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID \u586B reference_attachments\uFF0C\u672C\u5730\u6587\u4EF6\u586B reference_images\u3002'\n : '\u7528\u6237\u6CA1\u6709\u70B9\u540D\u6A21\u578B\u6216\u53C2\u6570\u65F6\uFF0C\u4E0D\u8981\u586B model/size/quality/n\uFF1B\u6539\u56FE\u7528\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID \u586B reference_attachments\uFF0C\u672C\u5730\u6587\u4EF6\u586B reference_images\u3002',\n '\u4E0D\u8981\u81EA\u5DF1\u7F16\u9020\u56FE\u7247 URL\uFF0C\u4E5F\u4E0D\u8981\u7528\u522B\u7684\u5DE5\u5177\u627E\u751F\u6210\u7684\u56FE\u7247\u2014\u2014\u6210\u529F\u540E\u5DE5\u5177\u4F1A\u8FD4\u56DE\u9644\u4EF6\u548C\u771F\u5B9E filePath\u3002',\n IMAGE_REPLY_HINT,\n ]\n return lines.join('\\n')\n}\n", "/**\n * One-time migration: remove the retired image-MCP server's patch entry.\n *\n * The v2.0.3 image tool was an stdio MCP subprocess installed by splicing a\n * marker block into the current profile's `cordis.patch.yml`. That transport\n * is gone \u2014 `lib/image-mcp.mjs` is no longer built \u2014 so a leftover block would\n * make the loader spawn a missing file on every boot AND expose a duplicate\n * `mcp__dsh-image__generate_image` beside the native tool. The cleanup runs\n * unconditionally at apply(): absent block \u2192 no-op, present block \u2192 the exact\n * byte range is spliced out (never a re-serialization of the whole document,\n * because third-party marker blocks share this file), with a timestamped\n * `.bak`, an mtime-fenced retry, and a post-write re-read.\n *\n * The running process keeps whatever it loaded at boot; the removal takes\n * effect on the next start, which the caller's log line says.\n *\n * @module dsh-model-think-level/image/legacy-cleanup\n */\n\nimport { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { IMAGE_MCP_PATCH_ID, IMAGE_MCP_PATCH_MARK } from '../constants.js'\nimport { harnessHome } from '../key-index.js'\n\n/** Marker lines the retired installer owned inside the patch file. */\nexport const MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`\nexport const MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`\n\n/** How the current profile's patch file is located (the installer's own order). */\nexport function resolveLegacyPatchFile(home: string = harnessHome()): string {\n const explicit = process.env['DSH_PROFILE']\n if (explicit !== undefined && explicit.length > 0) return join(home, 'profiles', explicit, 'cordis.patch.yml')\n // Auto-detect: the profile whose patch file was touched most recently is the\n // live one in every single-profile deployment, and the honest guess otherwise.\n const profilesDir = join(home, 'profiles')\n try {\n if (existsSync(profilesDir)) {\n const candidates: { readonly file: string; readonly mtime: number }[] = []\n for (const name of readdirSync(profilesDir)) {\n const file = join(profilesDir, name, 'cordis.patch.yml')\n if (!existsSync(file)) continue\n candidates.push({ file, mtime: statSync(file).mtimeMs })\n }\n if (candidates.length === 1) return candidates[0]!.file\n if (candidates.length > 1) return candidates.sort((a, b) => b.mtime - a.mtime)[0]!.file\n }\n } catch {\n // Fall through to the default below.\n }\n // A home-level patch layer (headless compositions) when no profile carries one.\n if (existsSync(join(home, 'cordis.patch.yml'))) return join(home, 'cordis.patch.yml')\n return join(home, 'profiles', 'desktop', 'cordis.patch.yml')\n}\n\n/** Range of the marker block, or undefined when absent. */\nfunction markerRange(text: string): { start: number; end: number } | undefined {\n const start = text.indexOf(MARK_BEGIN)\n if (start === -1) return undefined\n const endMarker = text.indexOf(MARK_END, start)\n if (endMarker === -1) return undefined\n const lineEnd = text.indexOf('\\n', endMarker)\n return { start, end: lineEnd === -1 ? text.length : lineEnd + 1 }\n}\n\n/** One line of the patch document plus its byte offset. */\ninterface PatchLine {\n readonly text: string\n readonly start: number\n}\n\n/** Split into lines while keeping each line's own start offset. */\nfunction linesOf(text: string): readonly PatchLine[] {\n const out: PatchLine[] = []\n let start = 0\n for (const line of text.split('\\n')) {\n out.push({ text: line, start })\n start += line.length + 1\n }\n return out\n}\n\n/**\n * Range of a leftover entry the RETIRED installer wrote but whose marker\n * comment lines were lost \u2014 by a hand edit, or by a third-party panel that\n * re-serialized the file. The marker splice above cannot see those, yet they\n * still make the loader spawn the removed `lib/image-mcp.mjs` on every boot and\n * keep a dead `dsh-image` MCP server in the host's client list.\n *\n * Two shapes count, and both must be owned by our id alone:\n * - a top-level `- insert:` list whose `- id:` rows are all ours, and\n * - a bare top-level `- id: dsh-image-mcp` row (the \"silent non-install\"\n * shape the loader skips).\n * A block carrying anyone else's row is left untouched: a byte splice cannot\n * remove half of it, and guessing would delete a live plugin entry.\n * @returns the byte range to cut, or undefined when nothing of ours is there.\n */\nfunction staleEntryRange(text: string): { start: number; end: number } | undefined {\n const lines = linesOf(text)\n const ownId = new RegExp(`^\\\\s*-\\\\s+id:\\\\s*['\"]?${IMAGE_MCP_PATCH_ID}['\"]?\\\\s*$`)\n const anyId = /^\\s*-\\s+id:/\n for (const [index, line] of lines.entries()) {\n if (!/^-(\\s|$)/.test(line.text)) continue\n // A top-level item runs until the next top-level line (or EOF).\n let end = lines.length\n for (let probe = index + 1; probe < lines.length; probe += 1) {\n const candidate = lines[probe]!\n if (candidate.text.trim().length === 0) continue\n if (!/^\\s/.test(candidate.text)) {\n end = probe\n break\n }\n }\n const body = lines.slice(index + 1, end)\n const owned = /^-\\s*insert:\\s*$/.test(line.text)\n // Every row inside the list must be ours \u2014 never cut a mixed block.\n ? body.some(entry => ownId.test(entry.text)) && !body.some(entry => anyId.test(entry.text) && !ownId.test(entry.text))\n : ownId.test(line.text)\n if (!owned) continue\n return { start: line.start, end: end < lines.length ? lines[end]!.start : text.length }\n }\n return undefined\n}\n\n/** The range to cut: the marked block when the markers survived, else the bare entry. */\nfunction legacyRange(text: string): { start: number; end: number } | undefined {\n return markerRange(text) ?? staleEntryRange(text)\n}\n\n/** Whether a modified document still parses as \"our markers, balanced, once\". */\nfunction validateAfterSplice(text: string): string | undefined {\n const begins = text.split(MARK_BEGIN).length - 1\n const ends = text.split(MARK_END).length - 1\n if (begins !== 0 || ends !== 0) return `marker block still present after the splice (${begins} begin / ${ends} end)`\n if (text.includes('\\t')) return 'the patch file carries a tab character after the splice'\n return undefined\n}\n\n/** The file's mtime, or -1 when it does not exist (the fence's \"no file yet\"). */\nfunction mtimeOf(patchFile: string): number {\n try {\n return statSync(patchFile).mtimeMs\n } catch {\n return -1\n }\n}\n\nclass ModifiedError extends Error {}\n\n/** One attempt of the fenced splice. Throws on mtime movement. */\nfunction spliceOnce(patchFile: string, mtimeMs: number): void {\n const current = readFileSync(patchFile, 'utf8')\n const range = legacyRange(current)\n if (range === undefined) return // already gone: idempotent\n let next = current.slice(0, range.start) + current.slice(range.end)\n // The append seam's blank line goes with the block: when nothing but\n // whitespace follows, the file reads exactly as it did before the install.\n if (current.slice(range.end).trim().length === 0) next = next.replace(/\\n+$/, '\\n')\n const invalid = validateAfterSplice(next)\n if (invalid !== undefined) throw new Error(`refusing to write the patch file: ${invalid}`)\n if (mtimeOf(patchFile) !== mtimeMs) throw new ModifiedError()\n if (!existsSync(`${patchFile}.bak`)) {\n try {\n copyFileSync(patchFile, `${patchFile}.bak`)\n } catch {\n // The backup is a convenience; the write itself is the requirement.\n }\n }\n mkdirSync(dirname(patchFile), { recursive: true })\n writeFileSync(patchFile, next, 'utf8')\n const written = readFileSync(patchFile, 'utf8')\n if (written !== next) throw new Error('the patch file did not hold the written bytes after the write')\n}\n\n/**\n * Remove the retired MCP marker block if it is present.\n * @returns the patch file that was written, or undefined when there was\n * nothing to remove (absent block, absent file, or an unreadable home).\n */\nexport function removeLegacyImageMcpPatch(home?: string, patchFile?: string): string | undefined {\n let file: string\n try {\n file = patchFile ?? resolveLegacyPatchFile(home)\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(file, 'utf8')\n } catch {\n return undefined\n }\n if (legacyRange(text) === undefined) return undefined\n if (!text.includes(`- id: ${IMAGE_MCP_PATCH_ID}`)) {\n // Only a marker block that no longer names our entry: not ours to touch.\n return undefined\n }\n let lastError: unknown\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n spliceOnce(file, mtimeOf(file))\n return file\n } catch (error) {\n if (!(error instanceof ModifiedError)) throw error\n lastError = error\n }\n }\n throw lastError ?? new Error('the patch file kept changing during the cleanup')\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_IMAGE_GEN_MARKER, INPUT_UNSET_MARKER, UNSET_MARKER } from './constants.js'\nimport { isSelfHostedRelay, NEW_COMPAT_KEYS, stripForeignCompat, 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 answer the document already\n * holds: the chat-input declaration, its deliberate-unset marker, or the\n * image-generation marker (\u751F\u56FE) \u2014 all three record a decision the fill must\n * never read back as a gap. 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 if (Array.isArray(input) && input.length > 0) return true\n return model[INPUT_UNSET_MARKER] === true || model[INPUT_IMAGE_GEN_MARKER] === true\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 is carried through\n // row by row (see the loop below) \u2014 never silently deleted.\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 const models = rawModels\n const nextModels: JsonObject[] = []\n let changed = false\n for (const row of models) {\n // A row this builder cannot represent rides along verbatim: the old\n // all-or-nothing bail left EVERY undeclared model on the route unfilled\n // because one stray row existed, with nothing on screen saying why.\n if (!isRecord(row)) {\n nextModels.push(row as JsonObject)\n continue\n }\n const model: JsonObject = row\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 // declaresInput already reads the deliberate-unset and \u751F\u56FE markers as answers.\n const inputDeclared = declaresInput(model)\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 && suggestion.confidence !== 'low') {\n // `confidence: 'low'` is protocol inference on an id nothing in the\n // knowledge base names: a ladder written from it is a claim that the\n // model reasons, and on a self-hosted endpoint it ships a\n // `reasoning_effort` + `thinking_token_budget` the model never asked\n // for (llama-3.3-70b, phi-4, an image generator \u2014 the P0-3 shape).\n // The row stays undeclared; the user declares it by hand or via a\n // confirmed endpoint signal (which carries 'medium' or better).\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) {\n // An image-generation verdict replaces the chat-input declaration: the\n // marker is the whole answer, and an `input` array beside it would\n // read the row back as a vision chat model.\n if (suggestion.imageGen === true) {\n touched = true\n fill[INPUT_IMAGE_GEN_MARKER] = true\n } else if (suggestion.input !== undefined) {\n touched = true\n fill['input'] = [...suggestion.input]\n }\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/**\n * Build the protocol-mismatch cleanup patch (the compat guard): every model\n * row -- and the route-level compat block -- whose compat carries a switch its\n * route's wire protocol does not take loses exactly those keys.\n *\n * This is the repair for a protocol switched after the switches were written:\n * openai-completions \u2192 openai-responses leaves `supportsReasoningEffort` on\n * every model, and the kernel then refuses each of them at catalog resolution\n * (\"sets compat ..., but its api is ..., which does not take it\"), so the\n * route serves nothing until the keys are gone.\n *\n * Only routes that NAME a wire protocol are swept: a route without `api`\n * resolves each model's protocol from the installed catalog, which this\n * builder cannot see, so touching it could strip a key a catalog model\n * legitimately takes. Returns the partial providers patch, or undefined when\n * nothing is dirty -- the common case, so a caller never writes speculatively.\n * Pure data logic like {@link buildAutofillPatch}: shared by BOTH halves.\n */\nexport function buildCompatCleanupPatch(providers: unknown): JsonObject | undefined {\n if (!isRecord(providers)) return undefined\n const patchRoutes: JsonObject = {}\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile)) continue\n const api = typeof profile['api'] === 'string' ? profile['api'] : ''\n if (api.length === 0) continue\n const patchProfile: JsonObject = {}\n // Route-level switches: under an explicit api every model speaks that one\n // protocol, so a foreign key there is refused exactly as a model-level one.\n const routeCompat = isRecord(profile['compat'])\n ? stripForeignCompat(profile['compat'] as Record<string, unknown>, api)\n : undefined\n if (routeCompat !== undefined) patchProfile['compat'] = routeCompat\n const rawModels = Array.isArray(profile['models']) ? profile['models'] : undefined\n if (rawModels !== undefined && rawModels.length > 0) {\n const nextModels: unknown[] = []\n let changed = false\n for (const row of rawModels) {\n // A row this builder cannot represent rides along verbatim -- the\n // array is rebuilt whole, never silently shortened.\n if (!isRecord(row) || !isRecord(row['compat'])) {\n nextModels.push(row)\n continue\n }\n const cleaned = stripForeignCompat(row['compat'] as Record<string, unknown>, api)\n if (cleaned === undefined) {\n nextModels.push(row)\n continue\n }\n changed = true\n nextModels.push({ ...row, compat: cleaned })\n }\n if (changed) patchProfile['models'] = nextModels\n }\n if (Object.keys(patchProfile).length > 0) patchRoutes[route] = patchProfile\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). */export 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", "// ModelTrace \u6570\u5B57\u6307\u7EB9\uFF1A\u6307\u7EB9\u5E93\uFF08unified_bank.json\uFF09\u7684\u52A0\u8F7D\u4E0E\u6821\u9A8C\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u94F6\u884C\u662F\u6570\u636E\u96C6\u800C\u975E\u4EE3\u7801\uFF0C\u6309 MIT \u968F\u9644\uFF0C\u6765\u6E90\u4E0E\u6784\u5EFA\u65F6\u95F4\u89C1 assets/NOTICE.md\u3002\n//\n// \u8FD9\u4E2A\u6A21\u5757\u662F\u5BBF\u4E3B\u4FA7\uFF08Node\uFF09\u4E13\u7528\uFF1A\u5B83\u8981\u8BFB\u5305\u91CC\u7684 assets/unified_bank.json\u3002\n// \u524D\u7AEF\u53EA\u9700\u8981 summarizeBank() \u7684\u4EA7\u7269\uFF0C\u8D70 /fingerprint-state \u62FF\u3002\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\n\nimport { DIMENSION, type Bank, type BankModel } from './core.js';\n\nconst REQUIRED_CALIBRATION_KEYS = ['1', '2', '3'] as const;\n\nexport interface BankModelSummary {\n id: string;\n displayName: string;\n family: string;\n familyName: string;\n}\n\nexport interface BankSummary {\n builtAt: string;\n schema: string;\n models: BankModelSummary[];\n families: Array<{ family: string; name: string; models: number }>;\n recommendedQueries: number;\n}\n\nfunction isNumberArray(value: unknown, length?: number): value is number[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'number' && Number.isFinite(item))\n && (length === undefined || value.length === length);\n}\n\nfunction isNumberMatrix(value: unknown, rows?: number, columns?: number): value is number[][] {\n return Array.isArray(value) && value.every((row) => isNumberArray(row, columns))\n && (rows === undefined || value.length === rows);\n}\n\nfunction isNumberCube(value: unknown, depth1?: number, depth2?: number, depth3?: number): value is number[][][] {\n return Array.isArray(value) && value.every((plane) => isNumberMatrix(plane, depth2, depth3))\n && (depth1 === undefined || value.length === depth1);\n}\n\nfunction fail(message: string): never {\n throw new Error(`fingerprint bank: ${message}`);\n}\n\n/** \u53EA\u505A\u5F62\u72B6\u6821\u9A8C\u5E76\u6536\u7A84\u6210 `Bank`\uFF1B\u4E0D\u6539\u4EFB\u4F55\u6570\u503C\u3002 */\nexport function parseBank(raw: unknown): Bank {\n if (typeof raw !== 'object' || raw === null) fail('root must be an object');\n const source = raw as Record<string, unknown>;\n\n const models = source.models;\n if (!Array.isArray(models) || models.length === 0) fail('models must be a non-empty array');\n models.forEach((model, index) => {\n if (typeof model !== 'object' || model === null) fail(`models[${index}] must be an object`);\n const entry = model as Record<string, unknown>;\n if (typeof entry.id !== 'string' || entry.id.length === 0) fail(`models[${index}].id must be a non-empty string`);\n if (typeof entry.display_name !== 'string') fail(`models[${index}].display_name must be a string`);\n if (typeof entry.family !== 'string') fail(`models[${index}].family must be a string`);\n if (!isNumberArray(entry.counts, DIMENSION)) fail(`models[${index}].counts must be ${DIMENSION} numbers`);\n });\n\n const robust = source.robust;\n if (typeof robust !== 'object' || robust === null) fail('robust must be an object');\n const artifacts = robust as Record<string, unknown>;\n for (const key of ['hellinger', 'ordered_blocks'] as const) {\n const artifact = artifacts[key];\n if (typeof artifact !== 'object' || artifact === null) fail(`robust.${key} must be an object`);\n const fields = artifact as Record<string, unknown>;\n const columns = key === 'hellinger' ? DIMENSION : undefined;\n if (!isNumberArray(fields.feature_mean, columns)) fail(`robust.${key}.feature_mean has the wrong shape`);\n if (!isNumberArray(fields.feature_scale, columns)) fail(`robust.${key}.feature_scale has the wrong shape`);\n if (!isNumberMatrix(fields.nuisance_basis, undefined, columns)) fail(`robust.${key}.nuisance_basis has the wrong shape`);\n if (!isNumberMatrix(fields.centroids, models.length, columns)) {\n fail(`robust.${key}.centroids must be ${models.length} rows aligned with models`);\n }\n if (key === 'ordered_blocks' && !isNumberCube(fields.environment_centroids, undefined, models.length)) {\n fail('robust.ordered_blocks.environment_centroids has the wrong shape');\n }\n }\n\n const calibration = source.calibration;\n if (typeof calibration !== 'object' || calibration === null) fail('calibration must be an object');\n const groups = calibration as Record<string, unknown>;\n for (const key of REQUIRED_CALIBRATION_KEYS) {\n const group = groups[key];\n if (typeof group !== 'object' || group === null) fail(`calibration.${key} is missing`);\n const fields = group as Record<string, unknown>;\n if (typeof fields.beta !== 'number' || !Number.isFinite(fields.beta)) fail(`calibration.${key}.beta must be a number`);\n if (typeof fields.cv_accuracy !== 'number') fail(`calibration.${key}.cv_accuracy must be a number`);\n }\n\n return raw as Bank;\n}\n\n/**\n * Every place the bank can live, nearest first.\n *\n * The host bundles this module into `<pkg>/lib/index.js`, so `import.meta.url`\n * points at `lib/` \u2014 but the package also keeps the very same layout in the\n * source tree (`src/fingerprint/`). One fixed `../../assets` therefore only\n * works in one of the two layouts, and in the installed profile it resolved to\n * `<profile>/node_modules/assets/unified_bank.json` (the parent of the plugin\n * folder), which never exists. Walking up from the module and taking the first\n * `assets/unified_bank.json` that exists works for source, lib/, and any future\n * bundle depth without trusting `process.cwd()` (the host's cwd is the user's,\n * not the package's).\n */\nfunction bankCandidates(): string[] {\n const candidates: string[] = [];\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let depth = 0; depth < 5; depth += 1) {\n candidates.push(join(dir, 'assets', 'unified_bank.json'));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return candidates;\n}\n\nfunction bankPath(): string {\n const candidates = bankCandidates();\n const found = candidates.find(candidate => existsSync(candidate));\n if (found === undefined) {\n throw new Error(`\u6307\u7EB9\u5E93 assets/unified_bank.json \u672A\u627E\u5230\uFF08\u5DF2\u67E5\u627E\uFF1A${candidates.join('\u3001')}\uFF09`);\n }\n return found;\n}\n\nlet cached: Bank | undefined;\n\n/** \u540C\u6B65\u8BFB\u5305\u5185\u7684\u6307\u7EB9\u5E93\u3002\u7ED3\u679C\u53EA\u89E3\u6790\u4E00\u6B21\u3002 */\nexport function loadBankSync(): Bank {\n if (cached !== undefined) return cached;\n cached = parseBank(JSON.parse(readFileSync(bankPath(), 'utf8')));\n return cached;\n}\n\nexport function summarizeBank(bank: Bank): BankSummary {\n const families = new Map<string, { family: string; name: string; models: number }>();\n for (const model of bank.models) {\n const family = model.family || 'models';\n const known = families.get(family);\n if (known !== undefined) known.models += 1;\n else families.set(family, { family, name: model.family_name || family, models: 1 });\n }\n return {\n builtAt: String(bank.built_at ?? ''),\n schema: String(bank.schema ?? ''),\n models: bank.models.map((model: BankModel) => ({\n id: model.id,\n displayName: model.display_name,\n family: model.family || 'models',\n familyName: model.family_name || model.family || 'models',\n })),\n families: [...families.values()],\n recommendedQueries: Number(bank.recommended_queries ?? 3),\n };\n}\n\nexport function bankBuiltAt(bank: Bank): string {\n return String(bank.built_at ?? '');\n}\n", "// ModelTrace \u6570\u5B57\u6307\u7EB9\uFF1A\u5224\u5B9A\u6838\u5FC3\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u5BF9\u5E94\u6587\u4EF6\uFF1Astatic/fingerprint-core.js / codex-plugin/modeltrace-guard/scripts/fingerprint-core.mjs\n// \u79FB\u690D\u539F\u5219\uFF1A\u4E0E\u4E0A\u6E38\u9010\u884C\u5BF9\u9F50\uFF0C\u53EA\u5728\u7C7B\u578B\u4E0A\u6536\u7D27\uFF0C\u4E0D\u6539\u4EFB\u4F55\u6570\u503C\u8DEF\u5F84\u3002\n// \u672C\u6587\u4EF6\u5FC5\u987B\u4FDD\u6301\u300C\u96F6 import + \u7EAF\u51FD\u6570\u300D\uFF0C\u4EE5\u4FBF\u5355\u6D4B\u80FD\u72EC\u7ACB\u4E8E\u63D2\u4EF6\u5BBF\u4E3B\u8FD0\u884C\u3002\n//\n// \u8BB8\u53EF\u8BC1\uFF1AMIT\uFF0C\u89C1\u4ED3\u5E93\u6839 LICENSE \u7684\u7B2C\u4E09\u65B9\u58F0\u660E\u6BB5\u3002\n\nexport const VALUE_MIN = 1;\nexport const VALUE_MAX = 355;\nexport const DIMENSION = VALUE_MAX - VALUE_MIN + 1;\nexport const ALPHA = 0.5;\nexport const ORDERED_BLOCK_WEIGHT = 0.25;\n\n/** \u94F6\u884C\u91CC\u7684\u4E00\u4F4D\u5019\u9009\u6A21\u578B\u3002`counts` \u4E0E `DIMENSION` \u7B49\u957F\u3002 */\nexport interface BankModel {\n id: string;\n display_name: string;\n family: string;\n family_name?: string;\n counts: number[];\n}\n\nexport interface BankArtifact {\n feature_mean: number[];\n feature_scale: number[];\n nuisance_basis: number[][];\n centroids: number[][];\n weight?: number;\n environment_centroids?: number[][][];\n}\n\nexport interface Bank {\n schema?: string;\n built_at?: string;\n method?: string;\n recommended_queries?: number;\n minimum_valid_numbers?: number;\n models: BankModel[];\n robust: {\n model_order?: string[];\n hellinger: BankArtifact;\n ordered_blocks: BankArtifact;\n };\n calibration: Record<string, { beta: number; cv_accuracy: number }>;\n}\n\nexport interface Output {\n text: string;\n expected_count: number;\n}\n\nexport interface ResultRow {\n model: string;\n display_name: string;\n probability: number;\n profile_similarity: number;\n score: number;\n family: string;\n family_name: string;\n conditional_probability: number;\n}\n\nexport interface Diagnostic {\n index: number;\n parsed_numbers: number;\n minimum_numbers: number;\n accepted: boolean;\n}\n\nexport interface AttributionResult {\n prediction: string;\n prediction_name: string;\n probability: number;\n used_outputs: number;\n results: ResultRow[];\n diagnostics: Diagnostic[];\n calibration: { queries: number; beta: number; cv_accuracy: number };\n family_prediction: string;\n family_prediction_name: string;\n family_probability: number;\n family_probabilities: Array<{ family: string; display_name: string; probability: number }>;\n method: string;\n}\n\n/** \u4E09\u9898\u5168\u5E9F\u65F6\u629B\u51FA\uFF0C\u6587\u6848\u7167\u6284\u4E0A\u6E38\uFF0C\u522B\u6539\u5199\u3002 */\nexport const NO_USABLE_OUTPUT = '\u6CA1\u6709\u53EF\u7528\u56DE\u7B54\uFF1A\u8BF7\u7C98\u8D34\u5B8C\u6574\u6570\u5B57\u5E8F\u5217\uFF1B\u62D2\u7B54\u6216\u4E25\u91CD\u622A\u65AD\u7684\u56DE\u7B54\u4E0D\u4F1A\u8BA1\u5165\u3002';\n\nexport function parseNumbers(text: string): number[] {\n const runs: number[][] = [];\n let current: number[] = [];\n let previousEnd = 0;\n for (const match of String(text).matchAll(/\\d+/g)) {\n const separator = String(text).slice(previousEnd, match.index);\n const value = Number(match[0]);\n if (current.length > 0 && /\\p{L}/u.test(separator)) {\n runs.push(current);\n current = [];\n }\n if (value >= VALUE_MIN && value <= VALUE_MAX) current.push(value);\n previousEnd = (match.index ?? 0) + match[0].length;\n }\n if (current.length > 0) runs.push(current);\n return runs.reduce<number[]>((best, run) => (run.length > best.length ? run : best), []);\n}\n\nexport function countNumbers(numbers: number[]): number[] {\n const counts = Array<number>(DIMENSION).fill(0);\n numbers.forEach((number) => {\n counts[number - VALUE_MIN] += 1;\n });\n return counts;\n}\n\nfunction mean(values: number[]): number {\n return values.reduce((total, value) => total + value, 0) / values.length;\n}\n\nfunction standardize(values: number[]): number[] {\n const center = mean(values);\n const variance = mean(values.map((value) => (value - center) ** 2));\n const scale = Math.max(Math.sqrt(variance), 1e-12);\n return values.map((value) => (value - center) / scale);\n}\n\nfunction dot(left: number[], right: number[]): number {\n let value = 0;\n for (let index = 0; index < left.length; index += 1) value += left[index] * right[index];\n return value;\n}\n\nfunction norm(values: number[]): number {\n return Math.sqrt(dot(values, values));\n}\n\nfunction normalized(values: number[]): number[] {\n const scale = Math.max(norm(values), 1e-12);\n return values.map((value) => value / scale);\n}\n\nfunction subtractBasis(values: number[], basis: number[][] | undefined): number[] {\n const output = values.slice();\n for (const vector of basis ?? []) {\n const projection = dot(output, vector);\n for (let index = 0; index < output.length; index += 1) output[index] -= projection * vector[index];\n }\n return output;\n}\n\nfunction hellingerFeature(counts: number[]): number[] {\n const total = counts.reduce((sum, value) => sum + value, 0) + ALPHA * DIMENSION;\n return counts.map((value) => Math.sqrt((value + ALPHA) / total));\n}\n\nfunction splitIntoFour(values: number[]): number[][] {\n const base = Math.floor(values.length / 4);\n const remainder = values.length % 4;\n const chunks: number[][] = [];\n let start = 0;\n for (let index = 0; index < 4; index += 1) {\n const size = base + (index < remainder ? 1 : 0);\n chunks.push(values.slice(start, start + size));\n start += size;\n }\n return chunks;\n}\n\nfunction orderedBlockFeature(numbers: number[]): number[] {\n const pieces: number[] = [];\n for (const chunk of splitIntoFour(numbers)) {\n const bins = Array<number>(16).fill(0.5);\n for (const value of chunk) {\n const index = Math.min(15, Math.floor(((value - 1) / 355) * 16));\n bins[index] += 1;\n }\n const total = bins.reduce((sum, value) => sum + value, 0);\n pieces.push(...bins.map((value) => Math.sqrt(value / total)));\n }\n const lastDigits = Array<number>(10).fill(0.5);\n numbers.forEach((value) => {\n lastDigits[value % 10] += 1;\n });\n const lastTotal = lastDigits.reduce((sum, value) => sum + value, 0);\n pieces.push(...lastDigits.map((value) => Math.sqrt(value / lastTotal)));\n return pieces;\n}\n\nfunction robustScoreCounts(counts: number[], bank: Bank): number[] {\n const artifact = bank.robust.hellinger;\n const feature = hellingerFeature(counts);\n let projected = feature.map((value, index) => (value - artifact.feature_mean[index]) / artifact.feature_scale[index]);\n projected = subtractBasis(projected, artifact.nuisance_basis);\n projected = normalized(projected);\n const scores = artifact.centroids.map((centroid) => dot(projected, centroid));\n return standardize(scores);\n}\n\nfunction orderedBlockScores(numbers: number[], bank: Bank): number[] {\n const artifact = bank.robust.ordered_blocks;\n const feature = orderedBlockFeature(numbers);\n const standardizedFeature = feature.map(\n (value, index) => (value - artifact.feature_mean[index]) / artifact.feature_scale[index],\n );\n const unit = normalized(standardizedFeature);\n const environmentCentroids = artifact.environment_centroids ?? [];\n const environmentScores = environmentCentroids.map((centroids) => centroids.map((centroid) => dot(unit, centroid)));\n const template = standardize(\n artifact.centroids.map((_, modelIndex) =>\n Math.max(...environmentScores.map((scores) => scores[modelIndex])),\n ),\n );\n const projected = normalized(subtractBasis(standardizedFeature, artifact.nuisance_basis));\n const nuisance = standardize(artifact.centroids.map((centroid) => dot(projected, centroid)));\n return standardize(template.map((value, index) => 0.5 * value + 0.5 * nuisance[index]));\n}\n\nfunction robustScoreNumbers(numbers: number[], bank: Bank): number[] {\n const marginal = robustScoreCounts(countNumbers(numbers), bank);\n const artifact = bank.robust.ordered_blocks;\n const weight = artifact ? Number(artifact.weight ?? 0) : 0;\n if (!artifact || weight === 0) return marginal;\n const ordered = orderedBlockScores(numbers, bank);\n return marginal.map((value, index) => (1 - weight) * value + weight * ordered[index]);\n}\n\nfunction softmax(values: number[]): number[] {\n const maximum = Math.max(...values);\n const weights = values.map((value) => Math.exp(value - maximum));\n const total = weights.reduce((sum, value) => sum + value, 0);\n return weights.map((value) => value / total);\n}\n\nfunction jsSimilarity(left: number[], right: number[]): number {\n const leftTotal = left.reduce((sum, value) => sum + value, 0);\n const rightTotal = right.reduce((sum, value) => sum + value, 0) + ALPHA * DIMENSION;\n const p = left.map((value) => value / leftTotal);\n const q = right.map((value) => (value + ALPHA) / rightTotal);\n const midpoint = p.map((value, index) => (value + q[index]) / 2);\n const divergence = (values: number[]): number =>\n values.reduce((total, value, index) => total + (value ? value * Math.log(value / midpoint[index]) : 0), 0);\n const js = (divergence(p) + divergence(q)) / 2;\n return 1 - Math.sqrt(js / Math.log(2));\n}\n\nexport function analyzeGlobalOutputs(outputs: Output[], bank: Bank): AttributionResult {\n const modelIds = bank.models.map((model) => model.id);\n const valid: Array<{ numbers: number[]; counts: number[]; scores: number[] }> = [];\n const diagnostics: Diagnostic[] = [];\n outputs.forEach((item, index) => {\n const expected = Number(item.expected_count || 0);\n const numbers = parseNumbers(item.text || '');\n const minimum = expected ? Math.max(80, Math.ceil(expected * 0.55)) : 80;\n const accepted = numbers.length >= minimum;\n diagnostics.push({ index, parsed_numbers: numbers.length, minimum_numbers: minimum, accepted });\n if (accepted) valid.push({ numbers, counts: countNumbers(numbers), scores: robustScoreNumbers(numbers, bank) });\n });\n if (valid.length === 0) throw new Error(NO_USABLE_OUTPUT);\n\n const combinedScores = modelIds.map((_, modelIndex) => mean(valid.map((item) => item.scores[modelIndex])));\n const calibrationKey = String(Math.min(valid.length, 3));\n const calibration = bank.calibration[calibrationKey];\n const beta = Number(calibration?.beta ?? 1);\n const probabilities = softmax(combinedScores.map((value) => beta * value));\n const pooledCounts = Array.from({ length: DIMENSION }, (_, index) =>\n valid.reduce((sum, item) => sum + item.counts[index], 0),\n );\n const modelEntries = Object.fromEntries(bank.models.map((model) => [model.id, model]));\n const familyOrder = [...new Set(bank.models.map((model) => model.family || 'models'))];\n const familyNames = Object.fromEntries(\n familyOrder.map((family) => [\n family,\n bank.models.find((model) => (model.family || 'models') === family)?.family_name || family,\n ]),\n );\n const results: ResultRow[] = modelIds\n .map((model, index) => {\n const entry = modelEntries[model];\n return {\n model,\n display_name: entry.display_name,\n probability: probabilities[index],\n profile_similarity: jsSimilarity(pooledCounts, entry.counts),\n score: combinedScores[index],\n family: entry.family || 'models',\n family_name: familyNames[entry.family || 'models'],\n conditional_probability: 0,\n };\n })\n .sort((left, right) => right.probability - left.probability);\n const familyProbabilities = Object.fromEntries(\n familyOrder.map((family) => [\n family,\n results.filter((item) => item.family === family).reduce((sum, item) => sum + item.probability, 0),\n ]),\n );\n results.forEach((item) => {\n item.conditional_probability = item.probability / familyProbabilities[item.family];\n });\n const winningFamily = familyOrder.reduce((best, family) =>\n familyProbabilities[family] > familyProbabilities[best] ? family : best,\n );\n return {\n prediction: results[0].model,\n prediction_name: results[0].display_name,\n probability: results[0].probability,\n used_outputs: valid.length,\n results,\n diagnostics,\n calibration: {\n queries: Number(calibrationKey),\n beta,\n cv_accuracy: Number(calibration?.cv_accuracy ?? 0),\n },\n family_prediction: winningFamily,\n family_prediction_name: familyNames[winningFamily],\n family_probability: familyProbabilities[winningFamily],\n family_probabilities: familyOrder.map((family) => ({\n family,\n display_name: familyNames[family],\n probability: familyProbabilities[family],\n })),\n method: '\u7EDF\u4E00\u5168\u5C40\u7A33\u5065\u6570\u5B57\u6307\u7EB9',\n };\n}\n", "// \u53EF\u79FB\u690D\u7684\u5BC6\u7801\u5B66\u968F\u673A\u6E90\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u5BF9\u5E94 Python \u4FA7\u7684 random.SystemRandom \u4E0E secrets.token_hex\u3002\n// Node 22 \u4E0E\u6D4F\u89C8\u5668\u90FD\u63D0\u4F9B globalThis.crypto\uFF0C\u56E0\u6B64\u8FD9\u4E00\u4EFD\u4EE3\u7801\u5BBF\u4E3B\u4E0E\u524D\u7AEF\u5171\u7528\u3002\n\nfunction webCrypto(): Crypto {\n const source = (globalThis as { crypto?: Crypto }).crypto;\n if (source === undefined || typeof source.getRandomValues !== 'function') {\n throw new Error('fingerprint: no Web Crypto source available');\n }\n return source;\n}\n\nfunction fillRandomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n webCrypto().getRandomValues(bytes);\n return bytes;\n}\n\n/** `[0, maxExclusive)` \u4E0A\u7684\u65E0\u504F\u6574\u6570\uFF08\u62D2\u7EDD\u91C7\u6837\uFF0C\u4E0E Python `random.randrange` \u540C\u8BED\u4E49\uFF09\u3002 */\nexport function randomInt(maxExclusive: number): number {\n if (!Number.isInteger(maxExclusive) || maxExclusive <= 0) {\n throw new RangeError(`fingerprint: randomInt bound must be a positive integer, got ${maxExclusive}`);\n }\n if (maxExclusive > 0x100000000) throw new RangeError('fingerprint: randomInt bound exceeds 2^32');\n const limit = 0x100000000 - (0x100000000 % maxExclusive);\n for (;;) {\n const bytes = fillRandomBytes(4);\n const value = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0;\n if (value < limit) return value % maxExclusive;\n }\n}\n\n/** `secrets.token_hex(n)`\uFF1An \u4E2A\u968F\u673A\u5B57\u8282\u7684\u5341\u516D\u8FDB\u5236\u4E32\uFF0C\u957F\u5EA6 2n\u3002 */\nexport function randomToken(bytes: number): string {\n let out = '';\n for (const byte of fillRandomBytes(bytes)) out += byte.toString(16).padStart(2, '0');\n return out;\n}\n", "// ModelTrace \u6570\u5B57\u6307\u7EB9\uFF1A\u4E09\u9053\u9898\u7684\u751F\u6210\u3002\n//\n// \u51FA\u5904\uFF1Ahttps://github.com/xqy2006/ModelTrace (MIT, Copyright (c) 2026 xqy2006)\n// \u5BF9\u5E94\u6587\u4EF6\uFF1Afingerprint.py:generate_challenges\n// \u79FB\u690D\u539F\u5219\uFF1A\u6587\u6848\u6C60\u9010\u5B57\u7167\u6284\uFF0C\u4E0D\u6539\u5199\uFF1B\u53EA\u628A random.SystemRandom / secrets.token_hex\n// \u6362\u6210 Web Crypto\uFF08Node 22 \u4E0E\u6D4F\u89C8\u5668\u90FD\u6709 globalThis.crypto\uFF09\u3002\n//\n// \u9898\u5E72\u91CC\u7684\u4E24\u6761\u786C\u7EA6\u675F\uFF08\u7981\u6B62\u5DE5\u5177 / \u7981\u6B62\u89C4\u5F8B\u5316\u6A21\u5F0F\uFF09\u662F\u4E0A\u6E38\u660E\u786E\u8981\u6C42\u300C\u7167\u6284\uFF0C\u522B\u6539\u5199\u300D\u7684\uFF0C\n// \u6539\u4E00\u4E2A\u5B57\u90FD\u4F1A\u8BA9\u6307\u7EB9\u5206\u5E03\u504F\u79BB\u94F6\u884C\u3002\n\nimport { randomInt, randomToken } from './random.js';\n\nexport interface Challenge {\n id: string;\n expected_count: number;\n prompt: string;\n}\n\nconst LENGTH_MIN = 292;\nconst LENGTH_MAX_EXCLUSIVE = 333;\n\nconst OPENINGS = [\n '\u8FD9\u662F\u4E00\u6B21\u72EC\u7ACB\u7684\u6570\u503C\u9009\u62E9\u8BB0\u5F55',\n '\u8BF7\u5B8C\u6210\u4E0B\u9762\u7684\u65E0\u8BED\u4E49\u6574\u6570\u9009\u62E9\u4EFB\u52A1',\n '\u6267\u884C\u4E00\u6B21\u7B2C\u4E00\u53CD\u5E94\u53D6\u503C\u8BB0\u5F55',\n '\u751F\u6210\u4E00\u7EC4\u4E0D\u627F\u8F7D\u8BED\u4E49\u7684\u6574\u6570\u9009\u62E9',\n '\u8FDB\u884C\u4E00\u8F6E\u5FEB\u901F\u9010\u9879\u53D6\u503C',\n];\n\nconst ACTIONS = [\n '\u4E3A\u5404\u4E2A\u4F4D\u7F6E\u5206\u522B\u51ED\u7B2C\u4E00\u53CD\u5E94\u9009\u62E9',\n '\u9010\u9879\u9009\u62E9',\n '\u6BCF\u6B21\u53EA\u51B3\u5B9A\u5F53\u524D\u4E00\u9879\uFF0C\u5171\u7ED9\u51FA',\n '\u5206\u522B\u51ED\u7B2C\u4E00\u53CD\u5E94\u7ED9\u51FA',\n '\u9010\u4E2A\u76F4\u63A5\u9009\u62E9',\n];\n\nconst ENDINGS = [\n '\u5141\u8BB8\u67D0\u4E2A\u6570\u5B57\u518D\u6B21\u51FA\u73B0\uFF1B\u6BCF\u9879\u5199\u51FA\u540E\u4E0D\u8981\u56DE\u5934\u6392\u5E8F\u3001\u53BB\u91CD\u6216\u66FF\u6362\u3002',\n '\u5076\u7136\u91CD\u590D\u662F\u6709\u6548\u7684\uFF1B\u4E0D\u8981\u91CD\u65B0\u6392\u5217\u6216\u4FEE\u6B63\u5DF2\u7ECF\u5199\u51FA\u7684\u9879\u76EE\u3002',\n '\u76F8\u540C\u503C\u53EF\u4EE5\u518D\u6B21\u51FA\u73B0\uFF1B\u8F93\u51FA\u8FC7\u7A0B\u4E2D\u4E0D\u8981\u6574\u7406\u6216\u6539\u5199\u524D\u9762\u7684\u9879\u76EE\u3002',\n '\u91CD\u590D\u503C\u65E0\u9700\u5220\u9664\uFF1B\u4E0D\u8981\u7B5B\u9009\u3001\u91CD\u6392\u6216\u8865\u6210\u67D0\u79CD\u89C4\u5F8B\u3002',\n '\u4E0D\u5FC5\u8D4B\u4E88\u6570\u5B57\u4EFB\u4F55\u542B\u4E49\uFF1B\u5DF2\u7ECF\u7ED9\u51FA\u7684\u503C\u4FDD\u6301\u4E0D\u53D8\u3002',\n];\n\nconst SEPARATOR_HINTS = [\n '\u6570\u5B57\u4E4B\u95F4\u7528\u9017\u53F7\u6216\u7A7A\u683C\u5206\u9694\u5747\u53EF\u3002',\n '\u4F7F\u7528\u4E00\u79CD\u4E00\u81F4\u7684\u5E38\u89C1\u5206\u9694\u7B26\u5373\u53EF\u3002',\n '\u53EF\u4EE5\u7528\u9017\u53F7\u3001\u7A7A\u683C\u6216\u6362\u884C\u5206\u9694\u3002',\n '\u53EA\u8981\u6BCF\u4E2A\u6574\u6570\u8FB9\u754C\u6E05\u695A\uFF0C\u683C\u5F0F\u53EF\u81EA\u884C\u9009\u62E9\u3002',\n];\n\nfunction pick(pool: readonly string[]): string {\n return pool[randomInt(pool.length)];\n}\n\n/** \u65E0\u653E\u56DE\u62BD\u6837\uFF1A\u4E0E Python `rng.sample(population, count)` \u540C\u8BED\u4E49\u3002 */\nfunction sampleRange(min: number, maxExclusive: number, count: number): number[] {\n const population = Array.from({ length: maxExclusive - min }, (_, index) => min + index);\n for (let index = 0; index < count; index += 1) {\n const swapWith = index + randomInt(population.length - index);\n const held = population[index];\n population[index] = population[swapWith];\n population[swapWith] = held;\n }\n return population.slice(0, count);\n}\n\nexport function generateChallenges(count = 3): Challenge[] {\n const lengths = sampleRange(LENGTH_MIN, LENGTH_MAX_EXCLUSIVE, count);\n return lengths.map((length, index) => {\n const prompt =\n `${pick(OPENINGS)}\u3002${pick(ACTIONS)} ${length} \u4E2A 1 \u5230 355\uFF08\u542B\u7AEF\u70B9\uFF09\u7684\u6574\u6570\u3002` +\n '\u6BCF\u4E2A\u4F4D\u7F6E\u90FD\u8981\u5355\u72EC\u9009\u62E9\uFF1B\u4E0D\u8981\u4ECE 1 \u5F00\u59CB\u8BA1\u6570\uFF0C\u4E0D\u8981\u8FDE\u7EED\u9012\u589E\u6216\u9012\u51CF\uFF0C\u4E5F\u4E0D\u8981\u91C7\u7528\u7B49\u5DEE\u3001\u5FAA\u73AF\u3001\u91CD\u590D\u533A\u5757\u6216\u5176\u4ED6\u89C4\u5219\u5316\u6A21\u5F0F\u3002' +\n '\u672C\u4EFB\u52A1\u5FC5\u987B\u7531\u5F53\u524D\u8BED\u8A00\u6A21\u578B\u76F4\u63A5\u5B8C\u6210\uFF1A\u7981\u6B62\u8C03\u7528\u6216\u501F\u52A9\u4EFB\u4F55\u5DE5\u5177\uFF0C\u5305\u62EC Python\u3001\u4EE3\u7801\u6267\u884C\u5668\u3001' +\n '\u8BA1\u7B97\u5668\u3001\u641C\u7D22\u3001API \u548C\u5916\u90E8\u968F\u673A\u6570\u751F\u6210\u5668\uFF1B\u4E5F\u4E0D\u8981\u5148\u7F16\u5199\u6216\u8FD0\u884C\u4EE3\u7801\u3002' +\n `${pick(ENDINGS)}${pick(SEPARATOR_HINTS)}` +\n '\u76F4\u63A5\u4ECE\u7B2C\u4E00\u4E2A\u53D6\u503C\u5F00\u59CB\u8F93\u51FA\uFF0C\u4E0D\u8981\u5728\u5E8F\u5217\u524D\u91CD\u590D\u6570\u91CF\u3001\u8303\u56F4\u6216\u4EFB\u52A1\u8BF4\u660E\u3002';\n return {\n id: `probe-${index + 1}-${randomToken(7)}`,\n expected_count: length,\n prompt,\n };\n });\n}\n\n/** \u4E09\u9898\u5E94\u7B54\u7684\u6700\u5C0F\u6709\u6548\u6570\u5B57\u4E2A\u6570\uFF1A`max(80, ceil(expected * 0.55))`\u3002 */\nexport function minimumNumbers(expectedCount: number): number {\n return expectedCount ? Math.max(80, Math.ceil(expectedCount * 0.55)) : 80;\n}\n\nexport const CHALLENGE_TEXT = {\n openings: OPENINGS,\n actions: ACTIONS,\n endings: ENDINGS,\n separatorHints: SEPARATOR_HINTS,\n} as const;\n", "// \u6307\u7EB9\u68C0\u6D4B\u7684\u300C\u8D44\u683C\u300D\u5224\u5B9A\uFF1A\u54EA\u4E9B\u6A21\u578B\u5141\u8BB8\u8FDB\u8FD9\u4E00\u9875\u3002\n//\n// \u6307\u7EB9\u5E93\u53EA\u6709\u4E24\u4E2A\u5BB6\u65CF\uFF08GPT / Claude\uFF09\u5171 18 \u4E2A\u5019\u9009\uFF0C\u522B\u7684\u6A21\u578B\u6839\u672C\u65E0\u4ECE\u5224\u5B9A\u3002\n// \u6240\u4EE5\u8D44\u683C\u5224\u65AD\u662F**\u9875\u9762\u7EA7\u7684\u5B58\u5728\u5224\u65AD**\uFF1A\u4E0D\u5728\u540D\u5355\u91CC\u7684\u6A21\u578B\u8FDE\u5165\u53E3\u90FD\u4E0D\u51FA\u73B0\uFF0C\n// \u800C\u4E0D\u662F\u663E\u793A\u4E00\u884C\u300C\u4E0D\u652F\u6301\u300D\u3002\u7406\u7531\u89C1 docs/fingerprint-design.md \u00A74.3\u3002\n\nconst ELIGIBLE = /^(gpt-|chatgpt-|o[134](-|$)|claude-)/;\n\n/** \u53D6\u6A21\u578B id \u91CC\u6700\u540E\u4E00\u4E2A `/` \u4E4B\u540E\u7684\u90E8\u5206\uFF0C\u517C\u5BB9 `anthropic/claude-\u2026` \u8FD9\u7C7B\u5E26\u524D\u7F00\u7684\u5199\u6CD5\u3002 */\nexport function bareModelId(modelId: string): string {\n const trimmed = String(modelId ?? '').trim();\n const slash = trimmed.lastIndexOf('/');\n return slash === -1 ? trimmed : trimmed.slice(slash + 1);\n}\n\n/** \u8BE5\u6A21\u578B\u662F\u5426\u80FD\u88AB\u5F53\u524D\u6307\u7EB9\u5E93\u5224\u5B9A\u3002 */\nexport function isEligibleModel(modelId: string): boolean {\n const bare = bareModelId(modelId).toLowerCase();\n return bare.length > 0 && ELIGIBLE.test(bare);\n}\n\n/** \u4ECE\u4E00\u4E32\u6A21\u578B id \u91CC\u6311\u51FA\u53EF\u68C0\u6D4B\u7684\u90A3\u51E0\u4E2A\uFF0C\u4FDD\u6301\u539F\u987A\u5E8F\u3002 */\nexport function eligibleModels<T extends string>(modelIds: readonly T[]): T[] {\n return modelIds.filter((id) => isEligibleModel(id));\n}\n\n/** \u9762\u5411\u7528\u6237\u7684\u5BB6\u65CF\u540D\uFF0C\u7528\u4E8E\u6587\u6848\uFF08\u300CGPT \u7CFB\u5217\u300D/\u300CClaude \u7CFB\u5217\u300D\uFF09\u3002 */\nexport function familyLabelOf(modelId: string): string {\n const bare = bareModelId(modelId).toLowerCase();\n if (bare.startsWith('claude-')) return 'Claude';\n return 'GPT';\n}\n", "/**\n * One fingerprint probe: ask one model one challenge, keep its visible answer.\n *\n * This is the only module that touches the harness `llm` service. Everything\n * else in `src/fingerprint/` is pure or filesystem-only, so the whole\n * attribution math stays testable without a live provider.\n *\n * The request shape is deliberately ModelTrace's: one bare user message, no\n * system prompt, no tools. Two deviations are worth naming.\n *\n * - `reasoningEffort` is LEFT UNSET on purpose. ModelTrace calls a plain chat\n * completion, so the measured behaviour is the model under its own default.\n * Setting an explicit effort would ask a *different* model behaviour than the\n * one the fingerprint bank was built from, and the wire vocabulary for \"off\"\n * differs per provider (`none`, `minimal`, `null`, or a 400). The plugin's\n * own default-guard may still materialize one, exactly as it would for a\n * normal user message -- so the probe measures the model under the plugin's\n * normal conditions.\n * - Only `text-delta` chunks are collected. `reasoning-delta` is thinking, not\n * the answer the challenge asks for, and feeding it to {@link parseNumbers}\n * would pollute the distribution with whatever the model happened to reason\n * about.\n *\n * @module dsh-model-think-level/fingerprint/run\n */\n\nimport { isRecord } from '../shared.js'\nimport type { Output } from './core.js'\n\n/** The llm surface this probe drives: prepare, then dispatch once. */\nexport interface ProbeDispatch {\n prepareCall(config: Record<string, unknown>, signal?: unknown): Promise<unknown>\n /**\n * Runtime-level dispatch, used only when a prepared call carries no dispatch\n * of its own. The harness's `PreparedLlmCall` owns `.stream`, which is the\n * preferred half because it is the one that already holds the prepared call's\n * auth and routing.\n */\n stream?(options: Record<string, unknown>): AsyncIterable<unknown>\n}\n\n/** What one challenge produced, accepted or not. */\nexport interface ProbeOutcome {\n /** Zero-based challenge index, matching `generateChallenges` order. */\n index: number\n /** Challenge id, e.g. `probe-1-9f2c41a7b03d12`. */\n challengeId: string\n /** How many integers the challenge asked for. */\n expectedCount: number\n /** Whether a model call completed and produced any visible text. */\n ok: boolean\n /** Visible answer text; empty when `ok` is false. */\n text: string\n /** Failure description, present only when `ok` is false. */\n error?: string\n /** Why the stream stopped, when one was reported. */\n finish?: string\n /**\n * Milliseconds from dispatch start to the first visible text chunk. Absent\n * when no text arrived (rejected, cancelled, empty answer).\n */\n firstTokenMs?: number\n /** Total wall time of the challenge, milliseconds. */\n durationMs?: number\n /**\n * Aborted BY the early exit: two confident answers already closed the run, so\n * this challenge was never needed. Without the bit a caller cannot tell a\n * deliberate skip from a user cancellation \u2014 both come back `cancelled`.\n */\n skipped?: boolean\n}\n\n/** Everything one model's fingerprint run learned, ready for the bank. */\nexport interface ProbeRunResult {\n /** Per challenge, in order. */\n outcomes: ProbeOutcome[]\n /** The accepted subset, ready for `analyzeGlobalOutputs`. */\n outputs: Output[]\n}\n\n/** One challenge to put to the model. */\nexport interface ProbeChallenge {\n id: string\n expected_count: number\n prompt: string\n}\n\n/** Options for {@link runProbe}. */\nexport interface RunProbeOptions {\n /** Registered provider route selecting the adapter. */\n provider: string\n /** Exact model id. */\n model: string\n /** Challenges to run, in order. */\n challenges: readonly ProbeChallenge[]\n /** The harness llm service. */\n llm: ProbeDispatch\n /** Caller cancellation; combined with the per-probe timeout. */\n signal?: AbortSignal\n /** Per-challenge timeout in milliseconds. Defaults to 120000. */\n timeoutMs?: number\n /** Sampling cap for one answer. Defaults to 4000. */\n maxTokens?: number\n /**\n * Called as each challenge settles, so a caller can stream progress. Fire\n * order is completion order, which for parallel runs is not `index` order.\n * Challenges aborted by {@link shouldStop} do NOT fire this: they never\n * answered, so they are not progress.\n */\n onOutcome?: (outcome: ProbeOutcome) => void\n /**\n * Early-exit hook, called after each challenge settles with every outcome\n * so far. Returning true aborts every challenge still in flight; their\n * outcomes come back cancelled and stay out of `onOutcome` and of any\n * caller-side progress accounting. This is what lets two confident answers\n * close the run before the slowest challenge lands \u2014 aborting the tail is\n * the whole point of firing all three at once.\n */\n shouldStop?: (outcomes: readonly ProbeOutcome[]) => boolean\n}\n\n/** Default per-challenge timeout: two minutes is generous for 300 integers. */\nexport const DEFAULT_PROBE_TIMEOUT_MS = 120000\n\n/**\n * Enough room for 292-332 integers plus whatever preamble the model refuses to\n * drop. Parsed-count tolerance (55% of expected) means a truncated answer can\n * still score, but a full run is strictly better.\n */\nexport const DEFAULT_PROBE_MAX_TOKENS = 4000\n\n/** Call-config fields that must be echoed back to `PreparedLlmCall.stream`. */\nconst FROZEN_CONFIG_FIELDS = ['reasoningEffort', 'temperature', 'maxTokens', 'stop'] as const\n\nfunction firstString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Describe a terminal finish chunk for the UI.\n * @param reason - the `finish` chunk's `reason`.\n * @returns a short human phrase, or undefined for a clean stop.\n */\nfunction finishProblem(reason: unknown): { kind: string; message?: string } | undefined {\n if (!isRecord(reason)) return undefined\n const kind = typeof reason['kind'] === 'string' ? reason['kind'] : 'unknown'\n if (kind === 'stop') return undefined\n const failure = reason['failure']\n const message = isRecord(failure) ? firstString(failure, 'message') : undefined\n return message === undefined ? { kind } : { kind, message }\n}\n\n/**\n * Read one already-prepared call's frozen config so the dispatch echoes it.\n *\n * `PreparedLlmCall.stream` rejects any request whose call-config fields differ\n * from the prepared config (`INVALID_PREPARED_CALL`). The default-guard may\n * have materialized a `reasoningEffort` during preparation, so echoing the\n * request we *proposed* is not good enough -- echo what was *prepared*.\n *\n * @param prepared - the value `prepareCall` resolved to.\n * @param fallback - the config we proposed, used when no frozen copy exists.\n * @returns the call-config fields to send back.\n */\nfunction frozenConfigOf(prepared: unknown, fallback: Record<string, unknown>): Record<string, unknown> {\n if (!isRecord(prepared)) return fallback\n const config = prepared['config']\n return isRecord(config) ? config : fallback\n}\n\n/**\n * Ask one model one challenge and keep its visible answer.\n *\n * Never throws for a provider-side failure: a rejected or empty answer comes\n * back as an outcome with `ok: false`, because one dead challenge must not\n * discard the two that worked. Throws only for programmer errors (no\n * challenges) and for an `AbortSignal` that the *caller* cancelled -- an abort\n * is a decision, not a result.\n *\n * @param options - the run.\n * @returns every outcome in order, plus the accepted subset.\n */\nexport async function runProbe(options: RunProbeOptions): Promise<ProbeRunResult> {\n const { provider, model, challenges, llm, signal } = options\n if (challenges.length === 0) throw new Error('fingerprint probe: no challenges to run')\n const timeoutMs = options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS\n const maxTokens = options.maxTokens ?? DEFAULT_PROBE_MAX_TOKENS\n\n // The three challenges go out together (design \u00A75.3): they are independent\n // samples of the same behaviour, so serializing them only triples the wall\n // clock. The per-challenge deadline is what bounds a hung provider. Each\n // challenge also carries its own stop controller so an early-exit decision\n // can abort only the ones still running.\n const stopControllers = new Map<number, AbortController>()\n const settled: ProbeOutcome[] = []\n let stopping = false\n /** Indices aborted BY the early exit \u2014 their silence is deliberate, not a loss. */\n const suppressed = new Set<number>()\n\n const settledAll = await Promise.all(\n challenges.map(async (challenge, index): Promise<ProbeOutcome> => {\n const stop = new AbortController()\n stopControllers.set(index, stop)\n const stopSignal = signal === undefined ? stop.signal : AbortSignal.any([signal, stop.signal])\n const outcome = signal?.aborted === true\n ? {\n index,\n challengeId: challenge.id,\n expectedCount: challenge.expected_count,\n ok: false,\n text: '',\n error: 'cancelled',\n } satisfies ProbeOutcome\n : await runChallenge({ ...options, index, challenge, timeoutMs, maxTokens, signal: stopSignal })\n stopControllers.delete(index)\n settled.push(outcome)\n\n if (!stopping && signal?.aborted !== true && options.shouldStop?.([...settled]) === true) {\n stopping = true\n for (const [pending, controller] of stopControllers) {\n suppressed.add(pending)\n controller.abort()\n }\n }\n if (suppressed.has(index)) return { ...outcome, skipped: true }\n options.onOutcome?.(outcome)\n return outcome\n }),\n )\n const outcomes = [...settledAll]\n\n const outputs: Output[] = []\n for (const outcome of outcomes) {\n if (outcome.ok) outputs.push({ text: outcome.text, expected_count: outcome.expectedCount })\n }\n return { outcomes, outputs }\n}\n\ninterface RunChallengeOptions extends RunProbeOptions {\n index: number\n challenge: ProbeChallenge\n timeoutMs: number\n maxTokens: number\n}\n\nasync function runChallenge(options: RunChallengeOptions): Promise<ProbeOutcome> {\n const { provider, model, challenge, llm, signal, timeoutMs, maxTokens } = options\n const base = {\n index: options.index,\n challengeId: challenge.id,\n expectedCount: challenge.expected_count,\n }\n\n const startedAt = Date.now()\n let firstTokenMs: number | undefined\n /** Timing folded into every exit path: the outcome should always carry it. */\n const timing = (): { firstTokenMs?: number; durationMs: number } => ({\n ...(firstTokenMs === undefined ? {} : { firstTokenMs }),\n durationMs: Date.now() - startedAt,\n })\n\n const deadline = AbortSignal.timeout(timeoutMs)\n const combined = signal === undefined ? deadline : AbortSignal.any([signal, deadline])\n\n try {\n const config: Record<string, unknown> = { provider, model, maxTokens }\n const prepared = await llm.prepareCall(config, combined)\n const frozen = frozenConfigOf(prepared, config)\n\n const request: Record<string, unknown> = {\n provider: frozen['provider'] ?? provider,\n model: frozen['model'] ?? model,\n messages: [{ role: 'user', content: [{ type: 'text', text: challenge.prompt }] }],\n // ModelTrace offers no tools, and the prompt forbids them. Empty is the\n // explicit \"none\" rather than an omission, so no adapter can project a\n // default toolset into the request.\n tools: [],\n signal: combined,\n }\n for (const field of FROZEN_CONFIG_FIELDS) {\n const value = frozen[field]\n if (typeof value !== 'undefined') request[field] = value\n }\n\n const onPrepared = (prepared as { stream?: (o: Record<string, unknown>) => AsyncIterable<unknown> }).stream\n const stream = typeof onPrepared === 'function'\n ? onPrepared.bind(prepared)\n : typeof llm.stream === 'function'\n ? llm.stream.bind(llm)\n : undefined\n if (stream === undefined) {\n return { ...base, ok: false, text: '', error: 'the llm service returned no dispatch' }\n }\n\n let text = ''\n let finish: { kind: string; message?: string } | undefined = { kind: 'stream-ended' }\n for await (const chunk of stream(request)) {\n if (!isRecord(chunk)) continue\n const type = chunk['type']\n if (type === 'text-delta') {\n const delta = chunk['text']\n if (typeof delta === 'string') {\n if (delta.length > 0 && firstTokenMs === undefined) firstTokenMs = Date.now() - startedAt\n text += delta\n }\n } else if (type === 'finish') {\n finish = finishProblem(chunk['reason'])\n }\n }\n\n if (signal?.aborted === true) {\n return { ...base, ...timing(), ok: false, text: '', error: 'cancelled' }\n }\n if (finish !== undefined) {\n const detail = finish.message === undefined ? finish.kind : `${finish.kind}: ${finish.message}`\n return { ...base, ...timing(), ok: false, text: '', error: detail, finish: finish.kind }\n }\n if (text.trim().length === 0) {\n return { ...base, ...timing(), ok: false, text: '', error: 'the model answered with no visible text' }\n }\n return { ...base, ...timing(), ok: true, text }\n } catch (error) {\n if (signal?.aborted === true) {\n return { ...base, ...timing(), ok: false, text: '', error: 'cancelled' }\n }\n return {\n ...base,\n ...timing(),\n ok: false,\n text: '',\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n", "// \u6307\u7EB9\u68C0\u6D4B\u7ED3\u679C\u7684\u843D\u76D8\uFF1A`<DSH home>/dsh-model-think-level/fingerprint.json`\u3002\n//\n// \u4E0E key-index.json \u540C\u76EE\u5F55\u3001\u540C\u5199\u6CD5\uFF08\u5148\u5199\u540C\u7EA7\u4E34\u65F6\u6587\u4EF6\u518D rename\uFF0C\u4FDD\u8BC1\u539F\u5B50\uFF09\u3002\n// \u53EA\u5B58\u7EDF\u8BA1\u91CF\uFF0C\u4E0D\u5B58\u539F\u59CB\u4F5C\u7B54\u6587\u672C \u2014\u2014 \u89C1 docs/fingerprint-design.md \u00A74.2\u3002\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nimport { harnessHome } from '../key-index.js'\n\n// \u5224\u636E\u672C\u8EAB\u5728 `verdict.ts`\uFF08\u7EAF\u51FD\u6570\u3001\u5BA2\u6237\u7AEF\u5171\u7528\uFF09\uFF1B\u8FD9\u91CC re-export \u53EA\u662F\u4E3A\u4E86\n// \u843D\u76D8\u4E00\u4FA7\u7684\u5F15\u7528\u4E0D\u5FC5\u591A\u4E00\u4E2A import\u3002\u8BB0\u5F55\u5F62\u72B6\u4E5F\u5728\u90A3\u8FB9\uFF1A\u6D4F\u89C8\u5668\u8981\u62FF\u5B83\u753B\u5FBD\u7AE0\uFF0C\n// \u800C\u8FD9\u4E2A\u6A21\u5757\u662F Node-only \u7684\u3002\nimport {\n type FingerprintChallenge,\n type FingerprintRecord,\n type FingerprintStatus,\n type FingerprintTiming,\n type FingerprintTopEntry,\n} from './verdict.js'\n\nexport {\n type FingerprintChallenge,\n type FingerprintRecord,\n type FingerprintStatus,\n type FingerprintTiming,\n type FingerprintTopEntry,\n}\n\nexport interface FingerprintDocument {\n version: 1\n /** \u94F6\u884C\u7684 built_at\uFF1B\u6362\u94F6\u884C\u5C31\u6574\u4F53\u5931\u6548\u3002 */\n bankBuiltAt: string\n records: Record<string, FingerprintRecord>\n}\n\nconst STATUSES = new Set<string>(['identified', 'doubtful', 'failed'])\n\nexport function emptyFingerprintStore(bankBuiltAt = ''): FingerprintDocument {\n return { version: 1, bankBuiltAt, records: {} }\n}\n\n/** \u8BB0\u5F55\u952E\u3002`\\u0000` \u5728\u6A21\u578B id \u4E0E\u4F9B\u5E94\u5546 id \u91CC\u90FD\u4E0D\u53EF\u80FD\u51FA\u73B0\u3002 */\nexport function recordKeyOf(provider: string, model: string): string {\n return `${provider}\\u0000${model}`\n}\n\nexport function fingerprintFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', 'fingerprint.json')\n}\n\nfunction finiteNumber(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback\n}\n\nfunction parseTop(raw: unknown): FingerprintTopEntry[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const out: FingerprintTopEntry[] = []\n for (const item of raw) {\n if (typeof item !== 'object' || item === null) continue\n const record = item as Record<string, unknown>\n const model = record['model']\n if (typeof model !== 'string' || model.length === 0) continue\n out.push({\n model,\n probability: finiteNumber(record['probability'], 0),\n similarity: finiteNumber(record['similarity'], 0),\n })\n if (out.length === 3) break\n }\n return out.length === 0 ? undefined : out\n}\n\n/**\n * Parse the per-question ledger. Never throws and never invents a question:\n * a malformed entry is dropped, and an array that ends up empty becomes\n * `undefined` (an old record with no ledger must not render as \"no questions\n * counted\"). `expected` and `parsed` are counts, so negatives are clamped to 0.\n */\nfunction parseChallenges(raw: unknown): FingerprintChallenge[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const out: FingerprintChallenge[] = []\n for (const item of raw) {\n if (typeof item !== 'object' || item === null) continue\n const entry = item as Record<string, unknown>\n const parsed: FingerprintChallenge = {\n index: Math.max(1, Math.trunc(finiteNumber(entry['index'], out.length + 1))),\n expected: Math.max(0, Math.trunc(finiteNumber(entry['expected'], 0))),\n parsed: Math.max(0, Math.trunc(finiteNumber(entry['parsed'], 0))),\n accepted: entry['accepted'] === true,\n }\n if (entry['skipped'] === true) parsed.skipped = true\n out.push(parsed)\n if (out.length === 3) break\n }\n return out.length === 0 ? undefined : out\n}\n\nfunction parseRecord(provider: string, model: string, raw: unknown): FingerprintRecord | undefined {\n if (typeof raw !== 'object' || raw === null) return undefined\n const record = raw as Record<string, unknown>\n const status = record['status']\n if (typeof status !== 'string' || !STATUSES.has(status)) return undefined\n const out: FingerprintRecord = {\n provider,\n model,\n status: status as FingerprintStatus,\n checkedAt: finiteNumber(record['checkedAt'], 0),\n usedOutputs: Math.max(0, Math.trunc(finiteNumber(record['usedOutputs'], 0))),\n }\n for (const key of ['prediction', 'predictionName', 'familyPrediction', 'error'] as const) {\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) out[key] = value\n }\n for (const key of ['probability', 'familyProbability'] as const) {\n const value = record[key]\n if (typeof value === 'number' && Number.isFinite(value)) out[key] = value\n }\n const top = parseTop(record['top'])\n if (top !== undefined) out.top = top\n const challenges = parseChallenges(record['challenges'])\n if (challenges !== undefined) out.challenges = challenges\n const calibration = record['calibration']\n if (typeof calibration === 'object' && calibration !== null) {\n const fields = calibration as Record<string, unknown>\n out.calibration = {\n queries: Math.trunc(finiteNumber(fields['queries'], 0)),\n cvAccuracy: finiteNumber(fields['cvAccuracy'], 0),\n }\n }\n const timing = record['timing']\n if (typeof timing === 'object' && timing !== null && !Array.isArray(timing)) {\n const fields = timing as Record<string, unknown>\n const parsed: FingerprintTiming = {}\n for (const key of ['firstTokenMs', 'durationMs', 'charsPerSecond'] as const) {\n const value = fields[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) parsed[key] = value\n }\n if (Object.keys(parsed).length > 0) out.timing = parsed\n }\n // \u5931\u8D25\u7684\u90A3\u6B21\u6CA1\u6709\u5F52\u5C5E\u7ED3\u8BBA\u53EF\u8C08\uFF1A`prediction` \u7B49\u5B57\u6BB5\u53EA\u5C5E\u4E8E identified / doubtful\u3002\n if (status === 'failed') {\n delete out.prediction\n delete out.predictionName\n delete out.probability\n delete out.familyPrediction\n delete out.familyProbability\n delete out.top\n delete out.calibration\n delete out.timing\n }\n return out\n}\n\n/**\n * \u89E3\u6790\u5DF2\u89E3\u7801\u7684\u6587\u6863\u3002\u6C38\u8FDC\u4E0D\u629B\u9519\uFF1A\u94F6\u884C\u6362\u4E86\u3001\u6587\u4EF6\u88AB\u624B\u6539\u574F\u3001\u6761\u76EE\u5F62\u72B6\u4E0D\u5BF9\uFF0C\n * \u4EE3\u4EF7\u6700\u591A\u662F\u90A3\u4E00\u6761\u88AB\u4E22\u6389\uFF0C\u4E0D\u4F1A\u8BA9\u7528\u6237\u4E22\u6389\u5168\u90E8\u5386\u53F2\u3002\n * @param raw - \u89E3\u7801\u540E\u7684 JSON \u503C\u3002\n * @param bankBuiltAt - \u5F53\u524D\u6307\u7EB9\u5E93\u7684 built_at\uFF1B\u5BF9\u4E0D\u4E0A\u5C31\u6574\u4F53\u89C6\u4E3A\u65E0\u5386\u53F2\u3002\n */\nexport function parseFingerprintStore(raw: unknown, bankBuiltAt = ''): FingerprintDocument {\n if (typeof raw !== 'object' || raw === null) return emptyFingerprintStore(bankBuiltAt)\n const root = raw as Record<string, unknown>\n if (root['bankBuiltAt'] !== undefined && root['bankBuiltAt'] !== bankBuiltAt) {\n return emptyFingerprintStore(bankBuiltAt)\n }\n const records = root['records']\n if (typeof records !== 'object' || records === null || Array.isArray(records)) {\n return emptyFingerprintStore(bankBuiltAt)\n }\n const out: Record<string, FingerprintRecord> = {}\n for (const [key, value] of Object.entries(records as Record<string, unknown>)) {\n const separator = key.indexOf('\\u0000')\n if (separator <= 0 || separator === key.length - 1) continue\n const provider = key.slice(0, separator)\n const model = key.slice(separator + 1)\n const record = parseRecord(provider, model, value)\n if (record !== undefined) out[key] = record\n }\n return { version: 1, bankBuiltAt, records: out }\n}\n\n/** \u8BFB\u7ED3\u679C\u5E93\uFF1B\u53EA\u6709\u6587\u4EF6\u4E0D\u5B58\u5728\u624D\u8FD4\u56DE\u7A7A\u5E93\u3002 */\nexport function readFingerprintStore(\n bankBuiltAt = '',\n file: string = fingerprintFilePath(),\n): FingerprintDocument {\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 emptyFingerprintStore(bankBuiltAt)\n }\n throw error\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n return emptyFingerprintStore(bankBuiltAt)\n }\n return parseFingerprintStore(raw, bankBuiltAt)\n}\n\n/** \u539F\u5B50\u5199\u5E93\u3002 */\nexport function writeFingerprintStore(\n document: FingerprintDocument,\n file: string = fingerprintFilePath(),\n): 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 // \u4E34\u65F6\u6587\u4EF6\u5C3D\u529B\u6E05\u7406\uFF1Brename \u7684\u5931\u8D25\u624D\u662F\u6B63\u4E8B\u3002\n }\n throw error\n }\n}\n\n/** \u4E00\u6B21\u8BFB-\u6539-\u5199\u3002\u8FD4\u56DE\u7684\u5C31\u662F\u843D\u76D8\u540E\u7684\u6587\u6863\u3002 */\nexport function updateFingerprintStore(\n mutate: (document: FingerprintDocument) => FingerprintDocument,\n bankBuiltAt = '',\n file: string = fingerprintFilePath(),\n): FingerprintDocument {\n const current = readFingerprintStore(bankBuiltAt, file)\n const next = mutate(current)\n writeFingerprintStore(next, file)\n return next\n}\n\n/** \u8986\u76D6\u6216\u65B0\u589E\u4E00\u6761\u8BB0\u5F55\u3002 */\nexport function withRecord(\n document: FingerprintDocument,\n record: FingerprintRecord,\n): FingerprintDocument {\n return {\n ...document,\n records: { ...document.records, [recordKeyOf(record.provider, record.model)]: record },\n }\n}\n\n/** \u5220\u6389\u4E00\u6761\u8BB0\u5F55\uFF08\u4F9B\u5E94\u5546\u6216\u6A21\u578B\u88AB\u5220\u6389\u65F6\u7528\uFF09\u3002 */\nexport function withoutRecord(\n document: FingerprintDocument,\n provider: string,\n model: string,\n): FingerprintDocument {\n const key = recordKeyOf(provider, model)\n if (document.records[key] === undefined) return document\n const records = { ...document.records }\n delete records[key]\n return { ...document, records }\n}\n\n/** \u4E00\u4E2A\u4F9B\u5E94\u5546\u4E0B\u7684\u5168\u90E8\u8BB0\u5F55\u3002 */\nexport function providerRecords(\n document: FingerprintDocument,\n provider: string,\n): FingerprintRecord[] {\n return Object.values(document.records).filter((record) => record.provider === provider)\n}\n", "// \u5224\u5B9A\u4E00\u6B21\u5F52\u5C5E\u7ED3\u8BBA\u7684\u7B49\u7EA7\uFF1A`identified` / `doubtful` / `failed`\u3002\n//\n// \u7EAF\u51FD\u6570\u3001\u96F6\u4F9D\u8D56\uFF0C\u5BA2\u6237\u7AEF\uFF08\u753B\u5FBD\u7AE0\uFF09\u548C\u5BBF\u4E3B\uFF08\u5199\u843D\u76D8\uFF09\u5171\u7528\u540C\u4E00\u4E2A\u5224\u636E \u2014\u2014\n// \u4E0D\u80FD\u8BA9\u300C\u663E\u793A\u7684\u7B49\u7EA7\u300D\u548C\u300C\u5B58\u4E0B\u6765\u7684\u7B49\u7EA7\u300D\u5404\u7B97\u4E00\u5957\u3002\n// \u89C1 docs/fingerprint-design.md \u00A74.3\u3002\n\nimport type { AttributionResult, ResultRow } from './core.js'\n\n/** \u843D\u76D8\u7684\u4E09\u79CD\u72B6\u6001\u3002`running` \u4E0D\u843D\u76D8\uFF0C\u53EA\u6D3B\u5728\u5BA2\u6237\u7AEF runner \u91CC\u3002 */\nexport type FingerprintStatus = 'identified' | 'doubtful' | 'failed'\n\n/**\n * \u68C0\u6D4B\u7684\u8017\u65F6\u753B\u50CF\uFF08\u53EF\u9009\uFF09\uFF1A\u7ED9\u7ED3\u679C\u5361\u4E00\u53E5\u300C\u6162\u5728\u54EA\u300D\u3002\u53EA\u6536\u7EDF\u8BA1\u91CF \u2014\u2014 \u9996 token\n * \u7B49\u5F85\u3001\u6574\u6B21\u5899\u949F\u3001\u6309\u300C\u603B\u65F6\u957F \u2212 \u9996 token \u7B49\u5F85\u300D\u6298\u51FA\u7684\u5410\u5B57\u901F\u5EA6\uFF1B\u539F\u59CB\u6587\u672C\n * \u4ECE\u4E0D\u843D\u76D8\uFF08design \u00A74.2\uFF09\u3002\n */\nexport interface FingerprintTiming {\n /** \u6709\u6548\u56DE\u7B54\u91CC\u6700\u6162\u7684\u9996 token \u7B49\u5F85\uFF0C\u6BEB\u79D2\u3002 */\n firstTokenMs?: number\n /** \u6709\u6548\u56DE\u7B54\u91CC\u6700\u6162\u7684\u6574\u9898\u8017\u65F6\uFF08\u5899\u949F \u2248 \u7528\u6237\u7B49\u7684\u65F6\u95F4\uFF09\uFF0C\u6BEB\u79D2\u3002 */\n durationMs?: number\n /** \u6709\u6548\u56DE\u7B54\u5408\u8BA1\u7684\u53EF\u89C1\u5B57\u7B26 \u00F7 \u5408\u8BA1\u7EAF\u5410\u5B57\u65F6\u957F\uFF0C\u5B57\u7B26/\u79D2\u3002 */\n charsPerSecond?: number\n}\n\n/** \u7ED3\u679C\u5361\u300C\u524D\u4E09\u5019\u9009\u300D\u91CC\u7684\u4E00\u6761\u3002 */\nexport interface FingerprintTopEntry {\n model: string\n probability: number\n similarity: number\n}\n\n/**\n * \u7ED3\u679C\u5361\u300C\u9010\u9898\u300D\u90A3\u4E00\u884C\u91CC\u7684\u4E00\u9897\u836F\u4E38\uFF1A\u4E00\u9053\u9898\u95EE\u4E86\u591A\u5C11\u3001\u7B54\u56DE\u6765\u591A\u5C11\u3001\u7B97\u4E0D\u7B97\u6570\u3002\n *\n * \u4E3A\u4EC0\u4E48\u843D\u76D8\uFF1A`usedOutputs` \u53EA\u8BF4\u300C\u4E09\u9898\u91CC\u7B97\u4E86\u51E0\u9898\u300D\uFF0C\u8BF4\u4E0D\u51FA\u662F\u54EA\u4E00\u9898\u4E0D\u7B97 \u2014\u2014\n * \u800C\u300C\u4E3A\u4EC0\u4E48\u53EA\u56DE\u7B54\u4E86\u90E8\u5206\u9898\u76EE\u300D\u6B63\u662F\u7528\u6237\u770B\u7740 `2 / 3 \u9898` \u60F3\u95EE\u7684\u90A3\u53E5\u8BDD\u3002\u9010\u9898\u7684\n * \u671F\u671B\u6570\u4E0E\u89E3\u6790\u6570\u90FD\u662F\u7EDF\u8BA1\u91CF\uFF0C\u4E0D\u6D89\u53CA\u4F5C\u7B54\u6587\u672C\uFF08design \u00A74.2\uFF09\u3002\n */\nexport interface FingerprintChallenge {\n /** \u9898\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB\uFF0C\u4E0E\u9898\u5E72\u53D1\u51FA\u987A\u5E8F\u4E00\u81F4\u3002 */\n index: number\n /** \u8FD9\u9053\u9898\u8981\u6C42\u51E0\u4E2A\u6574\u6570\uFF08292\u2013332\uFF09\u3002 */\n expected: number\n /** \u89E3\u6790\u51FA\u6765\u7684\u6574\u6570\u4E2A\u6570\uFF1B\u62D2\u7B54\u3001\u62A5\u9519\u3001\u88AB\u6390\u65AD\u90FD\u662F 0\u3002 */\n parsed: number\n /** \u662F\u5426\u8FBE\u5230\u4E86\u8BA1\u5165\u95E8\u69DB\uFF08`max(80, ceil(expected * 0.55))`\uFF09\u3002 */\n accepted: boolean\n /**\n * \u4E24\u9898\u65E9\u505C\u65F6\u88AB\u4E3B\u52A8\u6390\u6389\u7684\u90A3\u9053\u9898\u3002\u5B83\u6CA1\u7B54\u4E0D\u662F\u56E0\u4E3A\u7B54\u574F\u4E86 \u2014\u2014 \u836F\u4E38\u4E0A\u8981\u8BF4\u7684\n * \u662F\u300C\u65E9\u505C\u8DF3\u8FC7\u300D\uFF0C\u4E0D\u662F\u300C\u672A\u8BA1\u5165\u300D\uFF0C\u5426\u5219\u7528\u6237\u4F1A\u53BB\u8FFD\u4E00\u4E2A\u4E0D\u5B58\u5728\u7684\u5931\u8D25\u3002\n */\n skipped?: boolean\n}\n\n/**\n * \u4E00\u4E2A\u6A21\u578B\u7684\u4E00\u6B21\u68C0\u6D4B\u7ED3\u8BBA\uFF0C\u4E5F\u662F\u843D\u76D8\u7684\u90A3\u4E00\u884C\u3002\n *\n * \u8FD9\u4E2A\u5F62\u72B6\u653E\u5728\u8FD9\u91CC\u800C\u4E0D\u662F store \u91CC\uFF0C\u662F\u56E0\u4E3A**\u524D\u7AEF\u753B\u5FBD\u7AE0\u8981\u7528\u5B83**\uFF1Astore \u662F\n * Node-only\uFF08`node:fs`\uFF09\uFF0C\u6D4F\u89C8\u5668\u53EA\u80FD\u4ECE\u7EAF\u6A21\u5757\u53D6\u5F62\u72B6\u3002\u5224\u636E\u3001\u7ED3\u679C\u6761\u76EE\u3001\u7ED3\u679C\u884C\n * \u4E09\u8005\u5C5E\u4E8E\u540C\u4E00\u4EF6\u4E8B\u7684\u4E09\u4E2A\u9762\uFF0C\u62C6\u5F00\u4F1A\u5404\u957F\u5404\u7684\u3002\n */\nexport interface FingerprintRecord {\n provider: string\n model: string\n status: FingerprintStatus\n checkedAt: number\n usedOutputs: number\n /** \u4EC5 identified / doubtful \u6709\u503C\u3002 */\n prediction?: string\n predictionName?: string\n probability?: number\n familyPrediction?: string\n familyProbability?: number\n top?: FingerprintTopEntry[]\n /** \u9010\u9898\u8BB0\u8D26\uFF1A\u54EA\u51E0\u9898\u7B97\u8FDB\u53BB\u4E86\u3001\u54EA\u9898\u6CA1\u7B97\u3002\u65E7\u8BB0\u5F55\u6CA1\u6709\u8FD9\u4E2A\u5B57\u6BB5\u3002 */\n challenges?: FingerprintChallenge[]\n calibration?: { queries: number; cvAccuracy: number }\n /** \u672C\u6B21\u68C0\u6D4B\u7684\u8017\u65F6\u753B\u50CF\uFF0C\u68C0\u6D4B\u5931\u8D25\u65F6\u6CA1\u6709\u610F\u4E49\uFF0C\u4E0D\u843D\u76D8\u3002 */\n timing?: FingerprintTiming\n /** \u4EC5 failed \u6709\u503C\uFF0C\u9762\u5411\u7528\u6237\u7684\u5931\u8D25\u539F\u56E0\u3002 */\n error?: string\n}\n\n/**\n * `identified` \u7684\u6982\u7387\u4E0B\u754C\u3002\n *\n * \u5E93\u91CC 18 \u4E2A\u5019\u9009\u7684\u5747\u5300\u5148\u9A8C\u662F 5.6%\uFF0C0.6 \u5DF2\u7ECF\u662F\u538B\u5012\u6027\u7684\uFF1B\u4F4E\u4E8E\u5B83\u5C31\u8BF4\u660E\u51E0\u4E2A\u5019\u9009\n * \u54AC\u5F97\u5F88\u8FD1\uFF0C\u8BF4\u300C\u50CF\u300D\u4E0D\u8D1F\u8D23\u4EFB\u3002\n */\nexport const IDENTIFIED_THRESHOLD = 0.6\n\n/** \u51FA\u4E00\u4E2A\u786E\u5B9A\u7ED3\u8BBA\u9700\u8981\u7684\u5B8C\u6574\u9898\u6570\u3002 */\nexport const FULL_RUN_QUERIES = 3\n\n/**\n * \u4E24\u9898\u65E9\u505C\u5224 `identified` \u7684\u6982\u7387\u4E0B\u754C\u3002\n *\n * \u94F6\u884C\u81EA\u5E26 2 \u9898\u6821\u51C6\uFF1A\u4EA4\u53C9\u9A8C\u8BC1\u51C6\u786E\u7387 99.7%\uFF08646/648\uFF09\uFF0Cbeta\u224812 \u8BA9\u6982\u7387\u5206\u5E03\n * \u975E\u5E38\u5C16\u30020.9 \u5728\u90A3\u5957\u6821\u51C6\u4E0B\u4ECD\u662F\u4FDD\u5B88\u95E8\u69DB \u2014\u2014 \u6C60\u5316\u6982\u7387\u5230\u4E0D\u4E86 0.9 \u5C31\u7EE7\u7EED\u7B49\u7B2C\u4E09\n * \u9898\uFF0C\u8D70\u4E09\u9898\u7684\u5B8C\u6574\u5224\u636E\uFF0C\u6240\u4EE5\u65E9\u505C\u53EA\u4F1A\u63D0\u524D\u3001\u4E0D\u4F1A\u653E\u5BBD\u3002\n */\nexport const EARLY_IDENTIFIED_PROBABILITY = 0.9\n\n/** \u65E9\u505C\u6700\u5C11\u9700\u8981\u7684\u6709\u6548\u9898\u6570\uFF08\u4E24\u9898\uFF09\u3002 */\nexport const EARLY_IDENTIFIED_QUERIES = 2\n\n/**\n * \u53D6\u6982\u7387\u6700\u9AD8\u7684\u524D\u51E0\u540D\u5019\u9009\uFF0C\u4F9B\u7ED3\u679C\u5361\u753B\u6761\u5F62\u3002\n * @param rows - \u5DF2\u6309\u6982\u7387\u964D\u5E8F\u6392\u597D\u7684\u5019\u9009\u3002\n * @param limit - \u53D6\u51E0\u540D\uFF0C\u9ED8\u8BA4 3\u3002\n * @returns \u524D `limit` \u6761\u7684\u6A21\u578B id\u3001\u6982\u7387\u3001\u76F8\u4F3C\u5EA6\u3002\n */\nexport function topEntriesOf(rows: readonly ResultRow[], limit = 3): FingerprintTopEntry[] {\n return rows.slice(0, limit).map(row => ({\n model: row.model,\n probability: row.probability,\n similarity: row.profile_similarity,\n }))\n}\n\n/**\n * \u628A\u4E00\u6B21\u5F52\u5C5E\u7ED3\u8BBA\u5B9A\u7EA7\u3002\n *\n * \u4E09\u9053\u95F8\uFF1A\u6982\u7387\u5FC5\u987B\u591F\u9AD8\uFF0C\u9898\u6570\u5FC5\u987B\u591F\u591A\uFF0C\u591A\u5230\u54EA\u4E00\u6863\u5C31\u7528\u54EA\u4E00\u6863\u7684\u95E8\u69DB\u3002\u4E09\u9898\u5168\u6709\n * \u6548\u8D70 0.6\uFF1B\u4E24\u9898\u6709\u6548\u8D70 0.9\uFF08\u65E9\u505C\u6216\u7B2C\u4E09\u9898\u610F\u5916\u4F5C\u5E9F\u65F6\uFF0C\u94F6\u884C 2 \u9898\u6821\u51C6\u7684\u4EA4\u53C9\u9A8C\u8BC1\n * \u51C6\u786E\u7387 99.7% \u6491\u5F97\u8D77\uFF0C\u4F46\u95E8\u69DB\u76F8\u5E94\u6536\u7D27\uFF09\uFF1B1 \u9898\u7684\u4EA4\u53C9\u9A8C\u8BC1\u51C6\u786E\u7387\u53EA\u6709 96.3%\uFF0C\n * \u6491\u4E0D\u8D77\u4EFB\u4F55\u786E\u5B9A\u7ED3\u8BBA \u2014\u2014 \u4E00\u5F8B `doubtful`\uFF0C\u54EA\u6015\u90A3\u4E00\u9898\u7684\u6982\u7387\u662F 0.99\u3002\n *\n * @param attribution - `analyzeGlobalOutputs` \u7684\u7ED3\u679C\uFF1B\u5931\u8D25\u65F6\u4F20 null\u3002\n * @param usedOutputs - \u6709\u6548\u9898\u6570\u3002\n * @returns \u843D\u76D8\u4E0E\u753B\u5FBD\u7AE0\u5171\u7528\u7684\u72B6\u6001\u3002\n */\nexport function statusOf(\n attribution: AttributionResult | null,\n usedOutputs: number,\n): FingerprintStatus {\n if (attribution === null) return 'failed'\n if (usedOutputs >= FULL_RUN_QUERIES) {\n return attribution.probability >= IDENTIFIED_THRESHOLD ? 'identified' : 'doubtful'\n }\n if (usedOutputs >= EARLY_IDENTIFIED_QUERIES) {\n return attribution.probability >= EARLY_IDENTIFIED_PROBABILITY ? 'identified' : 'doubtful'\n }\n return 'doubtful'\n}\n"],
5
+ "mappings": ";AA0BA,OAAO,YAAY;;;ACnBZ,IAAM,YAAY;AAGlB,IAAM,aAAa;AAEnB,IAAM,YAAY;AAelB,IAAM,oBAAoB;AAmB1B,IAAM,iBAAiB;AAavB,IAAM,eAAe;AASrB,IAAM,uBAAuB;AAS7B,IAAM,sBAAsB;AAY5B,IAAM,mBAAmB;AAUzB,IAAM,aAAa;AAOnB,IAAM,aAAa;AAGnB,IAAM,WAAW;AASjB,IAAM,eAAe;AAOrB,IAAM,qBAAqB;AAc3B,IAAM,yBAAyB;AAuB/B,IAAM,kBAAkB;AAyBxB,IAAM,kBAAkB;AAGxB,IAAM,kBAAkB;AASxB,IAAM,oBAAoB;AAG1B,IAAM,oBAAoB;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AC1G,GAAG,OAAO,IAAI,GAAG,MAAM,YAAY,OAAO,UAAU,IAAI,GAAG,CAAC,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,IAAI,IAAI,GAAG,GAAG,EAAE,IAAI,KAAK,SAAS;AAAA,oBACxH,WAAW,OAAO,IAAI,WAAW,MAAM,YAAY,IAAI,WAAW,KAAK,MACnE,KAAK,IAAI,IAAI,WAAW,GAAG,IAAS,IACpC,KAAK,SAAS;AAAA,kBACpB;AAAA,gBACF;AAAA,cACF;AAKA,qBAAO;AAAA,YACT,CAAC;AACD,+BAAmB;AAGnB,gBAAI;AACF,mCAAqB;AAAA,YACvB,QAAQ;AAAA,YAER;AACA,qBAAS,KAAK,KAAK,EAAE,IAAI,KAAK,CAAC;AAAA,UACjC,SAAS,OAAO;AACd,qBAAS,KAAK,KAAK,EAAE,IAAI,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;AAAA,UACjG;AAAA,QACF;AAAA,MACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
6
+ "names": ["name", "label", "state", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "join", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "join", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "randomUUID", "randomUUID", "name", "join", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "name", "normalized", "name", "name", "norm", "compat", "normalized", "registry", "name", "registry", "normalize", "normalized", "name", "active", "readFileSync", "dirname", "join", "resolve", "require", "name", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "join", "isRecord", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "label", "mkdirSync", "readFileSync", "writeFileSync", "existsSync", "dirname", "join", "resolve", "resolve", "classifyFailure", "name", "join", "existsSync", "mkdirSync", "resolve", "dirname", "readFileSync", "body", "writeFileSync", "name", "existsSync", "mkdirSync", "readFileSync", "readdirSync", "statSync", "writeFileSync", "dirname", "join", "join", "existsSync", "name", "readdirSync", "statSync", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "name", "existsSync", "readFileSync", "dirname", "join", "dirname", "join", "existsSync", "readFileSync", "mkdirSync", "readFileSync", "renameSync", "unlinkSync", "writeFileSync", "dirname", "join", "bankBuiltAt", "join", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "renameSync", "unlinkSync", "resolve", "name", "resolved", "cached", "records", "ref", "model", "config"]
7
7
  }