# nodes

id: constant:f1f8528868db30d50b666994d1970499
kind: constant
name: create
qualified_name: create
file_path: .source/browser.ts
language: typescript
signature:
= browser<
  typeof Config,
  import("fumadocs-mdx/runtime/types").InternalTypeConfig & {
    DocData:...


id: constant:e99a015789b28509231ed3a222e9fdee
kind: constant
name: browserCollections
qualified_name: browserCollections
file_path: .source/browser.ts
language: typescript
signature:
= {
  docs: create.doc("docs", {
    "architecture/ARCHITECTURE.md": () =>
      import("../docs/archi...


id: constant:458b66daac46cf83f2ef7f64d5311a0f
kind: constant
name: create
qualified_name: create
file_path: .source/dynamic.ts
language: typescript
signature:
= await dynamic<
  typeof Config,
  import("fumadocs-mdx/runtime/types").InternalTypeConfig & {
    Do...


id: constant:f935c8391d36d821fc9b09b61a855aed
kind: constant
name: create
qualified_name: create
file_path: .source/server.ts
language: typescript
signature:
= server<
  typeof Config,
  import("fumadocs-mdx/runtime/types").InternalTypeConfig & {
    DocData: ...


id: constant:7497dea0319e9d61f673b7f783ceaa17
kind: constant
name: docs
qualified_name: docs
file_path: .source/server.ts
language: typescript
signature:
= await create.docs(
  "docs",
  "docs",
  {
    "meta.json": __fd_glob_54,
    "architecture/meta.jso...


id: constant:c38a35f79b01da186769b9c67476a564
kind: constant
name: featuresSchema
qualified_name: featuresSchema
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
docstring:
Zod schema for plugin options accepted as the second element of the
`plugin: [name, opts]` tuple in opencode.json. Strict by design — unknown
keys are rejected so typos in opencode.json surface immediately at plugin
construction time instead of silently being dropped.
Doc per field:
 - `providerId`     OpenCode provider id this plugin instance binds to.
                    Multiple plugin instances coexist by giving each a
                    different `providerId` ("omniroute", "omniroute-preprod",
                    "omniroute-local"). Maps to `ProviderHook.id` and
                    `AuthHook.provider` in the @opencode-ai/plugin contract.
                    Default: "omniroute".
 - `displayName`    Label rendered in the OpenCode UI. Default derives
                    from providerId.
 - `modelCacheTtl`  `/v1/models` TTL cache duration in milliseconds.
                    Default: 300_000 (5 min).
 - `baseURL`        Override base URL for this OmniRoute instance. When
                    absent, the loader falls back to a credential-attached
                    baseURL set by `/connect`.
Optional feature toggles. Every field is opt-in/out per call; defaults
mirror the v0.1.0 behaviour so existing opencode.json files do not need
to change.
 - `combos`               Discover `/api/combos` and surface them as
                          pseudo-models with LCD capabilities. Default true.
 - `enrichment`           Pull display names + pricing from
                          `/api/pricing/models` and overlay them onto the
                          ModelV2 entries derived from `/v1/models`. Solves
                          the "raw id in UI" complaint without client-side
                          heuristics. Default true.
 - `compressionMetadata`  Pull `/api/context/combos` so combo entries can
                          be tagged with their compression pipeline
                          (e.g. `rtk:standard → caveman:full`). Off by
                          default — adds one network call per refresh and
                          the data is only useful for combo entries.
 - `geminiSanitization`   Strip `$schema`/`$ref`/`additionalProperties`
                          from `tools[].function.parameters` when the
                          model id contains "gemini". Default true.
 - `mcpAutoEmit`          Auto-write an `mcp.<providerId>` remote entry
                          into the OC config pointing at
                          `<baseURL>/api/mcp/stream` with the resolved
                          Bearer token. Default false — keeps opencode.json
                          in control unless explicitly opted in.
 - `mcpToken`             Optional separate Bearer token to use in the
                          auto-emitted MCP entry. Falls back to the
                          provider's API key (from auth.json) when unset.
                          Useful when a narrower-scoped MCP-only key is
                          preferred over the chat/inference key.
 - `fetchInterceptor`     Inject Authorization: Bearer + Content-Type on
                          every outbound request to baseURL. Default true.

signature:
= z
  .object({
    combos: z.boolean().optional(),
    enrichment: z.boolean().optional(),
    compre...


id: constant:4897b85cff67142d6c2df75675648456
kind: constant
name: optionsSchema
qualified_name: optionsSchema
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
= z
  .object({
    providerId: z
      .string()
      .min(1)
      .regex(/^[a-z0-9-]+$/i, "provide...


id: function:03886e63f8f648346888ecd8e4f67426
kind: function
name: trimTrailingSlashes
qualified_name: trimTrailingSlashes
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: (value: string): string
docstring:
Manual trim helpers avoid polynomial-regex CodeQL warnings on
user-supplied baseURL strings (string.replace(/\/+$/, "")). The same
behaviour, no backtracking.


id: function:3fa0017a448553e47953aa26a462893c
kind: function
name: resolveOmniRoutePluginOptions
qualified_name: resolveOmniRoutePluginOptions
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  opts?: OmniRoutePluginOptions
): Required<Pick<OmniRoutePluginOptions, "providerId" | "displayName" | "modelCacheTtl">> &
  Pick<OmniRoutePluginOptions, "baseURL" | "features">


id: function:d622f444fa46b95166f0fe90a7b3035f
kind: function
name: coercePluginOptions
qualified_name: coercePluginOptions
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: (opts?: PluginOptions): OmniRoutePluginOptions
docstring:
Internal coercion shim. Delegates to `parseOmniRoutePluginOptions` to keep
the public surface stable while routing all validation through the Zod
schema. Always returns an object (never undefined) so downstream hooks see
the same shape regardless of whether opencode.json passed `null`,
`undefined`, or an empty bag.


id: constant:4d967e99f00a7b6f82f6a87406e9b938
kind: constant
name: OmniRouteV1Plugin
qualified_name: OmniRouteV1Plugin
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: = { id: "@omniroute/opencode-plugin", server: OmniRoutePlugin, }
docstring:
v1 plugin shape per OC plugin loader (`packages/opencode/src/plugin/shared.ts:readV1Plugin`).
OC checks the default export for an object with `{id, server}` shape FIRST.
If that fails it falls back to legacy `getLegacyPlugins` which walks every
named export and rejects any non-function value — our package has
constants (OMNIROUTE_PROVIDER_KEY, DEFAULT_MODEL_CACHE_TTL_MS) + types +
schemas as named exports, so the legacy path always fails for us.
Using v1 shape skips the legacy walk entirely. The `id` field is the
plugin MODULE identifier (one per published package); per-instance
`providerId` still flows through `options.providerId` as before.


id: function:c160f1b4f8f5f9ed8432c6e595ad809d
kind: function
name: mapComboToModelV2
qualified_name: mapComboToModelV2
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  combo: OmniRouteRawCombo,
  members: OmniRouteRawModelEntry[],
  providerId: string,
  baseURL: string
): ModelV2


id: constant:4908f77347fba29486103614d827867d
kind: constant
name: PROVIDER_LABEL_MAX_CHARS
qualified_name: PROVIDER_LABEL_MAX_CHARS
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: = 12
docstring:
Threshold beyond which `providerDisplayName` is abbreviated. Raised
from 8 → 12 so curated brand casing (`AssemblyAI`, `Antigravity`,
`Pollinations`, `GEMINI-CLI` curated form) wins over a shouty
UPPER(alias) fallback for the common case.


id: constant:0d69071c4bbabfdc5284b966cc05430a
kind: constant
name: ALIAS_UPPER_MAX_CHARS
qualified_name: ALIAS_UPPER_MAX_CHARS
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: = 5
docstring:
Aliases longer than this get title-case fallback instead of UPPER —
keeps short-token UPPER (`cc`→`CC`, `ghm`→`GHM`) but tames long
lowercase aliases (`antigravity`→`Antigravity`).


id: function:472628af31776930da3d27c279e0e3fd
kind: function
name: titleCaseAlias
qualified_name: titleCaseAlias
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: (alias: string): string
docstring:
Title-case a long, lowercase-looking alias (e.g. `antigravity` →
`Antigravity`) so the prefix doesn't shout when neither
`providerDisplayName` nor a short alias is available.


id: function:9fc5cf47e9aae6ae27b59fec1dcc0db8
kind: function
name: lookupEnrichment
qualified_name: lookupEnrichment
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  rawId: string,
  enrichment: OmniRouteEnrichmentMap | undefined,
  canonicalToAlias: Map<string, string>
): OmniRouteEnrichmentEntry | undefined


id: function:7e9ad2d01ec58414bfd19ce90e307b9c
kind: function
name: canonicalDedupSet
qualified_name: canonicalDedupSet
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  rawModels: ReadonlyArray<OmniRouteRawModelEntry>,
  canonicalToAlias: Map<string, string>
): Set<string>


id: function:eef3f1fa546344050d32a63c3b28ef2f
kind: function
name: resolveProviderTagEntry
qualified_name: resolveProviderTagEntry
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  rawId: string,
  direct: OmniRouteEnrichmentEntry | undefined,
  aliasIndex: Map<string, OmniRouteEnrichmentEntry>,
  canonicalToAlias?: Map<string, string>
): OmniRouteEnrichmentEntry | undefined


id: function:6cff4350a65e673d3d60020d023c8b76
kind: function
name: usableProviderAliasSet
qualified_name: usableProviderAliasSet
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  connections: OmniRouteProviderConnection[],
  enrichment: OmniRouteEnrichmentMap | undefined
): { aliases: Set<string>; canonicals: Set<string>; knownAliases: Set<string> }


id: function:bc0647667f0e70311427a0b7c8f783e8
kind: function
name: isUsableRawModelId
qualified_name: isUsableRawModelId
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  id: string,
  usable: { aliases: Set<string>; canonicals: Set<string>; knownAliases: Set<string> },
  enrichment: OmniRouteEnrichmentMap | undefined
): boolean


id: function:a34092c44e54cd6155b83d813c2d46ee
kind: function
name: isUsableCombo
qualified_name: isUsableCombo
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  combo: OmniRouteRawCombo,
  usable: { aliases: Set<string>; canonicals: Set<string>; knownAliases: Set<string> }
): boolean


id: function:5f8f0aa5c4e4a650e012b8c867a37b9c
kind: function
name: modelsCacheKey
qualified_name: modelsCacheKey
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: (baseURL: string, credentialId: string): string
docstring:
Internal cache key: `${baseURL}::sha256(apiKey)`. We hash the apiKey so
the key is safe to log / inspect via debugger without leaking the secret.
Different (baseURL, apiKey) tuples MUST keep independent cache entries:
a single OC user may register prod + preprod OmniRoute side-by-side with
distinct keys, and serving one's catalog from the other's cache would be
a correctness bug, not just a privacy one.
codeql[js/insufficient-password-hash]: the input here is an API-key
identifier we use solely to derive an in-memory cache lookup key — it is
never stored, transmitted, compared against a hash, or used as a password.
SHA-256 is intentional: cheap + deterministic, prevents the raw secret
from sitting in memory dumps alongside the cache map. Slow KDFs (bcrypt/
argon2) would defeat the purpose (sub-ms lookups on every request).


id: function:511a02efef93219668c9b075fa607f65
kind: function
name: createOmniRouteProviderHook
qualified_name: createOmniRouteProviderHook
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  opts?: OmniRoutePluginOptions,
  deps: {
    fetcher?: OmniRouteModelsFetcher;
    combosFetcher?: OmniRouteCombosFetcher;
    enrichmentFetcher?: OmniRouteEnrichmentFetcher;
    compressionMetaFetcher?: OmniRouteCompressionMetaFetcher;
    providersFetcher?: OmniRouteProvidersFetcher;
    now?: () => number;
    cache?: OmniRouteFetchCache;
  } = {}
): ProviderHook


id: constant:6f6ed0f53420d6ad1f9250d176bc0cdc
kind: constant
name: GEMINI_SCHEMA_KEYS_TO_REMOVE
qualified_name: GEMINI_SCHEMA_KEYS_TO_REMOVE
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: = new Set(["$schema", "$ref", "ref", "additionalProperties"])
docstring:
────────────────────────────────────────────────────────────────────────────
Gemini tool-schema sanitisation (T-06) — strip JSON-schema keywords that
the Gemini API rejects from outbound chat-completion / responses bodies
when the target model is a Gemini variant.
────────────────────────────────────────────────────────────────────────────
JSON-Schema keywords that the Gemini API rejects when present anywhere in
a function-calling tool definition. Standard OpenAI / Anthropic clients
happily emit these (they're valid Draft-07 schema) but Gemini's tool
validator throws on them, breaking OmniRoute → Gemini chains transparently.
Source: behavioural reverse-engineering from Alph4d0g's
opencode-omniroute-auth@1.2.1 (dist/src/plugin.js:517).


id: function:3ad63dfe302d39eafbf9e00d903a440e
kind: function
name: stripSchemaKeys
qualified_name: stripSchemaKeys
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: (schema: Record<string, unknown>): boolean
docstring:
Recursively strip `GEMINI_SCHEMA_KEYS_TO_REMOVE` from an arbitrary
JSON-Schema-shaped record. Walks both the record's own properties and
any nested objects / arrays so deeply nested `properties.x.properties.y`
trees are reached without a separate traversal pass. Mutates in place
and reports whether any key was deleted so callers can skip a
`JSON.stringify` round-trip when nothing changed.


id: function:fcafe9f902b8178334a2099a30498f2f
kind: function
name: sanitizeToolSchemaContainer
qualified_name: sanitizeToolSchemaContainer
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: (payload: Record<string, unknown>): boolean
docstring:
Walk every tool definition in the payload and strip Gemini-incompatible
schema keywords. Handles both chat-completion shape
(`tools[].function.parameters`) and Responses-API shape
(`tools[].input_schema`), plus the Gemini-native `function_declaration`
variant some adapters use.
Also strips top-level schema keywords from the payload itself — clients
occasionally attach a top-level `$schema` declaration when re-serialising
tool bundles, and Gemini rejects those too.


id: variable:a9f418a38b856ceb79c6f3382b7283c3
kind: variable
name: geminiStreamingWarningEmitted
qualified_name: geminiStreamingWarningEmitted
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature: = false
docstring:
Module-level latch so the streaming-body warning fires AT MOST once per
Node process. ReadableStream bodies can't be safely cloned + JSON-parsed
without consuming the stream (and re-creating a stream that survives both
read paths is non-trivial), so the sanitiser skips them — but we want
the operator to see one heads-up that schema stripping won't run on
those requests.


id: function:c8185e3ef959e230d6680dbef4983f91
kind: function
name: buildStaticProviderEntry
qualified_name: buildStaticProviderEntry
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  rawModels: OmniRouteRawModelEntry[],
  rawCombos: OmniRouteRawCombo[],
  opts: ReturnType<typeof resolveOmniRoutePluginOptions>,
  baseURL: string,
  apiKey: string,
  enrichment?: OmniRouteEnrichmentMap,
  compressionCombos?: OmniRouteCompressionCombo[],
  connections?: OmniRouteProviderConnection[]
): OmniRouteStaticProviderEntry


id: interface:d0f50140f0ef8b50751610b1fbec410f
kind: interface
name: AuthJsonApiEntry
qualified_name: AuthJsonApiEntry
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
docstring:
Shape we expect inside `auth.json`. The file is keyed by providerId, with
each entry being a flavor-tagged credential. Today only the `api` flavor
is consumed by this plugin (OAuth + WellKnown flavors are passed through
but never decoded into a static block).


id: interface:19e584ef3d5b60afc5116235d00035e7
kind: interface
name: OmniRouteDiskSnapshot
qualified_name: OmniRouteDiskSnapshot
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
docstring:
Read & parse `auth.json` from OC's data dir. The path resolution mirrors
OC core's:
  `${OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode")}/auth.json`
Returns `undefined` when the file is missing (most-common case on a fresh
install — silent no-op). Returns `null` when the file exists but doesn't
parse as JSON (logs ONE warn so the operator sees the corruption).
Exported as a dependency-injectable function on `createOmniRouteConfigHook`
so tests can stub it without monkey-patching `node:fs/promises`.
─────────────────────────────────────────────────────────────────────────
Disk-cache fallback. Persists the last successful raw-fetch snapshot to
`${OPENCODE_DATA_DIR ?? ~/.local/share/opencode}/plugins/omniroute-<providerId>.json`.
When `/v1/models` is unreachable (e.g. IP whitelist drop, offline laptop)
AND the in-memory cache is cold, the config hook reads from disk so the
last-known catalog still surfaces in OC's model picker. Feature-flagged:
`features.diskCache !== false` (default-on).
─────────────────────────────────────────────────────────────────────────
Disk snapshot envelope. Versioned for forward-compat.


id: function:b82d97c4b92c11100ad800dc73f56f88
kind: function
name: createOmniRouteConfigHook
qualified_name: createOmniRouteConfigHook
file_path: @omniroute/opencode-plugin/src/index.ts
language: typescript
signature:
(
  opts?: OmniRoutePluginOptions,
  deps: {
    readAuthJson?: OmniRouteReadAuthJson;
    fetcher?: OmniRouteModelsFetcher;
    combosFetcher?: OmniRouteCombosFetcher;
    enrichmentFetcher?: OmniRouteEnrichmentFetcher;
    compressionMetaFetcher?: OmniRouteCompressionMetaFetcher;
    providersFetcher?: OmniRouteProvidersFetcher;
    diskSnapshotReader?: OmniRouteDiskSnapshotReader;
    diskSnapshotWriter?: OmniRouteDiskSnapshotWriter;
    now?: () => number;
    cache?: OmniRouteFetchCache;
    logger?: { warn: (...args: unknown[]) => void };
  } = {}
): (input: Config) => Promise<void>


id: import:e1eff645664c94b105e791b045a62abc
kind: import
name: ../src/index.js
qualified_name: ../src/index.js
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
signature:
import {
  createOmniRouteProviderHook,
  defaultOmniRouteCombosFetcher,
  mapComboToModelV2,
  type OmniRouteCombosFetcher,
  type OmniRouteModelsFetcher,
  type OmniRouteRawCombo,
  type OmniRouteRawModelEntry,
} from "../src/index.js";


id: constant:66bef5781c7b0d193958270af6d34c98
kind: constant
name: MODEL_PRIMARY
qualified_name: MODEL_PRIMARY
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
docstring:
────────────────────────────────────────────────────────────────────────────
Fixtures
────────────────────────────────────────────────────────────────────────────

signature:
= {
  id: "claude-primary",
  capabilities: {
    tool_calling: true,
    reasoning: true,
    vision:...


id: constant:167ed912f4fd5631e989d4e360bdbc50
kind: constant
name: MODEL_SECONDARY
qualified_name: MODEL_SECONDARY
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
signature:
= {
  id: "claude-secondary",
  capabilities: {
    tool_calling: true,
    reasoning: false,
    visi...


id: constant:04614f25a899b51bd575d23a74874a9a
kind: constant
name: MODEL_NO_TOOLS
qualified_name: MODEL_NO_TOOLS
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
signature:
= {
  id: "gemini-3-flash",
  capabilities: { tool_calling: false, reasoning: false, vision: false, th...


id: constant:85740235f041ac71befe9fefc54bf1f8
kind: constant
name: COMBO_CLAUDE_TIER
qualified_name: COMBO_CLAUDE_TIER
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
signature:
= {
  id: "combo-claude-tier",
  name: "Claude Tier",
  strategy: "priority",
  models: [
    { id: "s...


id: function:b271280e0af77c1c860cc9fc38e912d6
kind: function
name: stubModelsFetcher
qualified_name: stubModelsFetcher
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
signature: ( payload: OmniRouteRawModelEntry[] ): OmniRouteModelsFetcher & { callCount: () => number }
docstring:
────────────────────────────────────────────────────────────────────────────
Helpers
────────────────────────────────────────────────────────────────────────────


id: function:8c049fa3450604b61dd1a865ac3640e1
kind: function
name: stubCombosFetcher
qualified_name: stubCombosFetcher
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
signature:
(
  payload: OmniRouteRawCombo[]
): OmniRouteCombosFetcher & { callCount: () => number; callsBy: () => Array<[string, string]> }


id: function:cd58a6d2e1cc0dfea9238f1210851932
kind: function
name: withWarnCapture
qualified_name: withWarnCapture
file_path: @omniroute/opencode-plugin/tests/combos.test.ts
language: typescript
docstring:
Capture console.warn invocations for the duration of a callback, then
restore the original. Needed because the collision + soft-fail paths
emit warnings we want to assert on.

signature:
(
  fn: (warnings: Array<{ args: unknown[] }>) => Promise<T>
): Promise<{ result: T; warnings: Array<{ args: unknown[] }> }>


id: import:420c3cf6ba585130e3615da512d18071
kind: import
name: ../src/index.js
qualified_name: ../src/index.js
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
import {
  buildStaticProviderEntry,
  createOmniRouteConfigHook,
  createOmniRouteProviderHook,
  OmniRoutePlugin,
  resolveOmniRoutePluginOptions,
  type OmniRouteCombosFetcher,
  type OmniRouteEnrichmentEntry,
  type OmniRouteEnrichmentFetcher,
  type OmniRouteEnrichmentMap,
  type OmniRouteFetchCache,
  type OmniRouteModelsFetcher,
  type OmniRouteProviderConnection,
  type OmniRouteProvidersFetcher,
  type OmniRouteRawCombo,
  type OmniRouteRawModelEntry,
  type OmniRouteReadAuthJson,
  type OmniRouteStaticProviderEntry,
} from "../src/index.js";


id: constant:9666989750e5964b46867efc58c4dfdb
kind: constant
name: MODEL_CLAUDE
qualified_name: MODEL_CLAUDE
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
docstring:
────────────────────────────────────────────────────────────────────────────
Fixtures
────────────────────────────────────────────────────────────────────────────

signature:
= {
  id: "claude-sonnet-4-6",
  capabilities: {
    tool_calling: true,
    reasoning: true,
    visi...


id: constant:cc3f795b2986199b7f3e06c43b8445da
kind: constant
name: MODEL_GEMINI
qualified_name: MODEL_GEMINI
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
= {
  id: "gemini-3-flash",
  capabilities: { tool_calling: true, reasoning: false, vision: true, thin...


id: constant:e33816e62fa73f0b7300e024f1961819
kind: constant
name: COMBO_CLAUDE_TIER
qualified_name: COMBO_CLAUDE_TIER
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
= {
  id: "combo-claude-tier",
  name: "Claude Tier",
  models: [
    { id: "s1", kind: "model", model...


id: function:68c1262c368a07811820eba99affc2ca
kind: function
name: stubReadAuthJson
qualified_name: stubReadAuthJson
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
docstring:
────────────────────────────────────────────────────────────────────────────
Helpers (DI stubs — mirrors patterns in provider.test.ts / combos.test.ts)
────────────────────────────────────────────────────────────────────────────

signature:
(
  value: Record<string, unknown> | undefined | null
): OmniRouteReadAuthJson & { callCount: () => number }


id: function:59345443adbb3d14ea119a2b3e7ede26
kind: function
name: stubModelsFetcher
qualified_name: stubModelsFetcher
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
(
  payload: OmniRouteRawModelEntry[]
): OmniRouteModelsFetcher & { callCount: () => number; callsBy: () => Array<[string, string]> }


id: function:af09ae38d201511c221d8ac82b234ff2
kind: function
name: stubEnrichmentFetcher
qualified_name: stubEnrichmentFetcher
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
(payload: OmniRouteEnrichmentMap): OmniRouteEnrichmentFetcher & {
  callCount: () => number;
  callsBy: () => Array<[string, string]>;
}


id: function:248be71ddca66eb74b8fb45df168dc17
kind: function
name: stubProvidersFetcher
qualified_name: stubProvidersFetcher
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
(payload: OmniRouteProviderConnection[]): OmniRouteProvidersFetcher & {
  callCount: () => number;
}


id: constant:0140d559f031898dce06e393e0ddf954
kind: constant
name: MODEL_CC_OPUS
qualified_name: MODEL_CC_OPUS
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
= {
  id: "cc/claude-opus-4-7",
  capabilities: { tool_calling: true, reasoning: true, temperature: tr...


id: constant:6312a4611be23bc5eebc6ec5ada19382
kind: constant
name: MODEL_NV_LLAMA
qualified_name: MODEL_NV_LLAMA
file_path: @omniroute/opencode-plugin/tests/config-shim.test.ts
language: typescript
signature:
= {
  id: "nvidia/llama-3-70b",
  capabilities: { tool_calling: true, temperature: true },
  context_l...


id: import:c0b7fe11e79001609b0ecef6c7c781cc
kind: import
name: ../src/index.js
qualified_name: ../src/index.js
file_path: @omniroute/opencode-plugin/tests/disk-snapshot-perms.test.ts
language: typescript
signature:
import {
  defaultDiskSnapshotWriter,
  diskSnapshotPath,
  type OmniRouteFetchCacheEntry,
} from "../src/index.js";


id: import:af0a66c89966faa8c5eb3953da1d3fb1
kind: import
name: ../src/index.js
qualified_name: ../src/index.js
file_path: @omniroute/opencode-plugin/tests/features.test.ts
language: typescript
signature:
import {
  applyEnrichment,
  applyProviderTag,
  buildAliasIndex,
  buildCanonicalToAliasMap,
  canonicalDedupSet,
  createOmniRouteConfigHook,
  createOmniRouteProviderHook,
  defaultOmniRouteEnrichmentFetcher,
  defaultOmniRouteCompressionMetaFetcher,
  formatCompressionPipeline,
  lookupEnrichment,
  parseOmniRoutePluginOptions,
  PROVIDER_TAG_SEPARATOR,
  resolveProviderTagEntry,
  type OmniRouteEnrichmentMap,
  type OmniRouteCompressionCombo,
  type OmniRouteRawModelEntry,
} from "../src/index.js";


id: constant:ce13d5acbe96f85731d6d22b71d11a37
kind: constant
name: SAMPLE_RAW
qualified_name: SAMPLE_RAW
file_path: @omniroute/opencode-plugin/tests/features.test.ts
language: typescript
docstring:
─────────────────────────────────────────────────────────────────────────
Provider hook — enrichment applied via injected fetcher
─────────────────────────────────────────────────────────────────────────

signature:
= [
  {
    id: "claude-sonnet-4-6",
    object: "model",
    created: 0,
    owned_by: "anthropic",
 ...


id: function:3369034d2d76a5a01826980872248d3a
kind: function
name: makeEnrichmentMap
qualified_name: makeEnrichmentMap
file_path: @omniroute/opencode-plugin/tests/features.test.ts
language: typescript
docstring:
─────────────────────────────────────────────────────────────────────────
Canonical-twin dedup + alias-fallback lookup
─────────────────────────────────────────────────────────────────────────

signature:
(
  entries: Array<{
    key: string;
    name?: string;
    providerAlias?: string;
    providerCanonical?: string;
    providerDisplayName?: string;
  }>
): OmniRouteEnrichmentMap


id: import:4c9f501c56afc0cb978f7949302cf864
kind: import
name: ../src/index.js
qualified_name: ../src/index.js
file_path: @omniroute/opencode-plugin/tests/gemini-sanitize.test.ts
language: typescript
signature:
import {
  __resetGeminiStreamingWarning,
  createGeminiSanitizingFetch,
  createOmniRouteFetchInterceptor,
  sanitizeGeminiToolSchemas,
  shouldSanitizeForGemini,
} from "../src/index.js";


id: function:b6ae2b5d1e276bdd9197b1c114d06183
kind: function
name: chatCompletionsWithDollarSchema
qualified_name: chatCompletionsWithDollarSchema
file_path: @omniroute/opencode-plugin/tests/gemini-sanitize.test.ts
language: typescript
signature: (): Record<string, unknown>
docstring:
Sample tool payloads — small enough to inline, big enough to cover
chat-completion + Responses-API + nested properties.


id: constant:fb3d7719339b849292d7cdfb7187e5a9
kind: constant
name: URL_CHAT
qualified_name: URL_CHAT
file_path: @omniroute/opencode-plugin/tests/gemini-sanitize.test.ts
language: typescript
signature: = "https://or.example.com/v1/chat/completions"
docstring:
────────────────────────────────────────────────────────────────────────────
createGeminiSanitizingFetch — wrapper
────────────────────────────────────────────────────────────────────────────


id: import:95c46dff48d01980669fce7ef4ee8727
kind: import
name: ../src/index.js
qualified_name: ../src/index.js
file_path: @omniroute/opencode-plugin/tests/provider.test.ts
language: typescript
signature:
import {
  createOmniRouteProviderHook,
  mapRawModelToModelV2,
  type OmniRouteRawModelEntry,
  type OmniRouteModelsFetcher,
} from "../src/index.js";


id: constant:ee31f8a257bb1be1bb1541ee0b1ff715
kind: constant
name: FIXTURE
qualified_name: FIXTURE
file_path: @omniroute/opencode-plugin/tests/provider.test.ts
language: typescript
signature:
= [
  {
    id: "claude-primary",
    object: "model",
    owned_by: "combo",
    capabilities: { tool...


id: function:09161cd4dc5496996964ecc029e68cf3
kind: function
name: stubFetcher
qualified_name: stubFetcher
file_path: @omniroute/opencode-plugin/tests/provider.test.ts
language: typescript
signature:
(payload: OmniRouteRawModelEntry[]): OmniRouteModelsFetcher & {
  callCount: () => number;
  callsBy: () => Array<[string, string]>;
}


id: import:8a6af491ab5550e5190aeaea31a8b459
kind: import
name: ../src/index.js
qualified_name: ../src/index.js
file_path: @omniroute/opencode-plugin/tests/scaffold.test.ts
language: typescript
signature:
import {
  OmniRoutePlugin,
  OMNIROUTE_PROVIDER_KEY,
  DEFAULT_MODEL_CACHE_TTL_MS,
  resolveOmniRoutePluginOptions,
} from "../src/index.js";


id: function:fdc805539e0e3c78369c999db9811878
kind: function
name: buildUsable
qualified_name: buildUsable
file_path: @omniroute/opencode-plugin/tests/usable-combo.test.ts
language: typescript
docstring: Build a `usable` set bundle for the tests.
signature:
(opts: { aliases?: string[]; canonicals?: string[]; known?: string[] }): {
  aliases: Set<string>;
  canonicals: Set<string>;
  knownAliases: Set<string>;
}


id: constant:38ba69c86e32b18fd20135854c4e5571
kind: constant
name: OMNIROUTE_DEFAULT_OPENCODE_MODELS
qualified_name: OMNIROUTE_DEFAULT_OPENCODE_MODELS
file_path: @omniroute/opencode-provider/src/index.ts
language: typescript
signature:
= [
  "cc/claude-opus-4-7",
  "cc/claude-sonnet-4-6",
  "cc/claude-haiku-4-5-20251001",
  "claude-opus...


id: constant:7c524eaeccb4743e8385cbdc388313e5
kind: constant
name: OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS
qualified_name: OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS
file_path: @omniroute/opencode-provider/src/index.ts
language: typescript
signature:
= {
  "cc/claude-opus-4-7": 200_000,
  "cc/claude-sonnet-4-6": 200_000,
  "cc/claude-haiku-4-5-2025100...


id: constant:7433d061af3cc07316a3ec8b8b5c558a
kind: constant
name: OMNIROUTE_DEFAULT_MODEL_CAPABILITIES
qualified_name: OMNIROUTE_DEFAULT_MODEL_CAPABILITIES
file_path: @omniroute/opencode-provider/src/index.ts
language: typescript
signature:
= {
  "cc/claude-opus-4-7": { attachment: true, reasoning: true, temperature: true, tool_call: true },...


id: function:2dea523f5396a48198c56f235937fd33
kind: function
name: mergeIntoExistingConfig
qualified_name: mergeIntoExistingConfig
file_path: @omniroute/opencode-provider/src/index.ts
language: typescript
signature:
(
  existing: Record<string, unknown>,
  options: OmniRouteProviderOptions
): Record<string, unknown>


id: constant:6e37ed53b2ffeb586d011c0bbbcd8ebd
kind: constant
name: OMNIROUTE_MCP_DEFAULT_SCOPES
qualified_name: OMNIROUTE_MCP_DEFAULT_SCOPES
file_path: @omniroute/opencode-provider/src/index.ts
language: typescript
signature:
= [
  "read:health",
  "read:combos",
  "read:quota",
  "read:usage",
  "read:models",
  "read:cache",...


id: constant:b9d84351a464c3721b50af26816c47e2
kind: constant
name: VALID_COMPRESSION_OVERRIDES
qualified_name: VALID_COMPRESSION_OVERRIDES
file_path: @omniroute/opencode-provider/src/index.ts
language: typescript
signature:
= new Set<string>([
  "",
  "off",
  "lite",
  "standard",
  "aggressive",
  "ultra",
  "rtk",
  "stac...


id: import:db104e367af978ea03a211d9c497376e
kind: import
name: ../src/index.ts
qualified_name: ../src/index.ts
file_path: @omniroute/opencode-provider/tests/index.test.ts
language: typescript
signature:
import {
  buildOmniRouteOpenCodeConfig,
  createOmniRouteAgentBlock,
  createOmniRouteComboConfig,
  createOmniRouteMCPEntry,
  createOmniRouteModesBlock,
  createOmniRouteProvider,
  fetchLiveModels,
  listCombos,
  mergeIntoExistingConfig,
  normalizeBaseURL,
  OMNIROUTE_DEFAULT_MODEL_CAPABILITIES,
  OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS,
  OMNIROUTE_DEFAULT_OPENCODE_MODELS,
  OMNIROUTE_MCP_DEFAULT_SCOPES,
  OMNIROUTE_PROVIDER_NPM,
  OPENCODE_CONFIG_SCHEMA,
} from "../src/index.ts";


id: function:74449d462922d8330ca40e236bba1685
kind: function
name: waitForServer
qualified_name: waitForServer
file_path: electron/main.js
language: javascript
signature: (url, timeoutMs = 180000)
docstring:
── Helper: Wait for server readiness (#1, #10) ────────────
Default raised to 180s: the first launch after an upgrade can run long DB
migrations, during which the server accepts the TCP connection but holds the
HTTP response until handlers initialize. The previous 30s cap timed out and
left the window stuck on a hanging connection (#2460).


id: constant:1effe4b18d9be13385a42c795c85d407
kind: constant
name: VALID_CHANNELS
qualified_name: VALID_CHANNELS
file_path: electron/preload.js
language: javascript
docstring: ── Channel Whitelist ──────────────────────────────────────
signature:
= {
  invoke: [
    "get-app-info",
    "open-external",
    "get-data-dir",
    "restart-server",
   ...


id: constant:2134c0ad2c494b4ecd2e07bb87e9173d
kind: constant
name: ANTHROPIC_BETA_BASE
qualified_name: ANTHROPIC_BETA_BASE
file_path: open-sse/config/anthropicHeaders.ts
language: typescript
signature:
= Object.freeze([
  "claude-code-20250219",
  "oauth-2025-04-20",
  "interleaved-thinking-2025-05-14",...


id: constant:42d275a4bf8036aa9a2e9ac61c8d805e
kind: constant
name: ANTHROPIC_BETA_CLAUDE_OAUTH
qualified_name: ANTHROPIC_BETA_CLAUDE_OAUTH
file_path: open-sse/config/anthropicHeaders.ts
language: typescript
signature:
= [
  ...ANTHROPIC_BETA_BASE.slice(0, 3),
  ...CLAUDE_OAUTH_EXTRA_BETAS,
  ...ANTHROPIC_BETA_BASE.slic...


id: constant:b4690198f0be8fe18ab077f2f9e8b3a4
kind: constant
name: ANTIGRAVITY_PUBLIC_MODELS
qualified_name: ANTIGRAVITY_PUBLIC_MODELS
file_path: open-sse/config/antigravityModelAliases.ts
language: typescript
signature:
= Object.freeze([
  // Gemini 3.5 Flash — flagship model in Antigravity 2.0 (May 2026)
  {
    id: "ge...


id: constant:b6a90e3bfc0176e19b751e5558f71616
kind: constant
name: ANTIGRAVITY_MODEL_ALIASES
qualified_name: ANTIGRAVITY_MODEL_ALIASES
file_path: open-sse/config/antigravityModelAliases.ts
language: typescript
signature:
= Object.freeze({
  "gemini-3-pro-preview": "gemini-3.1-pro-high",
  "gemini-3.5-flash-preview": "gemi...


id: constant:0e5bd6a6e09b4cdc35838f2520194182
kind: constant
name: ANTIGRAVITY_REVERSE_MODEL_ALIASES
qualified_name: ANTIGRAVITY_REVERSE_MODEL_ALIASES
file_path: open-sse/config/antigravityModelAliases.ts
language: typescript
signature:
= Object.freeze({
  "gemini-3.1-pro-high": "gemini-3-pro-preview",
  "gemini-3.5-flash-high": "gemini-...


id: constant:ddf5c8d35af7a56a2580725c77ac7703
kind: constant
name: CLIENT_VISIBLE_MODEL_NAMES
qualified_name: CLIENT_VISIBLE_MODEL_NAMES
file_path: open-sse/config/antigravityModelAliases.ts
language: typescript
signature:
= Object.freeze(
  ANTIGRAVITY_PUBLIC_MODELS.reduce<Record<string, string>>((acc, model) => {
    acc[...


id: constant:1131dcd0d8cc1aec8aecfbfef29d11f6
kind: constant
name: ANTIGRAVITY_BASE_URLS
qualified_name: ANTIGRAVITY_BASE_URLS
file_path: open-sse/config/antigravityUpstream.ts
language: typescript
signature:
= Object.freeze([
  "https://daily-cloudcode-pa.googleapis.com",
  "https://cloudcode-pa.googleapis.co...


id: interface:0cd9af5edbba36c9a4ffa51ed834ed24
kind: interface
name: AudioModel
qualified_name: AudioModel
file_path: open-sse/config/audioRegistry.ts
language: typescript
docstring:
Audio Provider Registry
Defines providers that support audio endpoints:
- /v1/audio/transcriptions (Whisper API)
- /v1/audio/speech (TTS API)


id: constant:dcd8bb348242ede71dd31ad7c84ad0b7
kind: constant
name: AUDIO_TRANSCRIPTION_PROVIDERS
qualified_name: AUDIO_TRANSCRIPTION_PROVIDERS
file_path: open-sse/config/audioRegistry.ts
language: typescript
signature:
= {
  openai: {
    id: "openai",
    baseUrl: "https://api.openai.com/v1/audio/transcriptions",
    a...


id: constant:23077a9c9f47d01122754517e293e1b6
kind: constant
name: AUDIO_SPEECH_PROVIDERS
qualified_name: AUDIO_SPEECH_PROVIDERS
file_path: open-sse/config/audioRegistry.ts
language: typescript
signature:
= {
  openai: {
    id: "openai",
    baseUrl: "https://api.openai.com/v1/audio/speech",
    authType:...


id: function:362f84311b8a58b7f5ce1b6b4673b15c
kind: function
name: parseAudioModel
qualified_name: parseAudioModel
file_path: open-sse/config/audioRegistry.ts
language: typescript
signature:
(
  modelStr: string | null,
  registry: Record<string, AudioProvider>,
  dynamicProviders?: AudioProvider[]
): { provider: string | null; model: string | null }


id: import:c15711b54d59045e88437733960ce1b1
kind: import
name: ./providerHeaderProfiles.ts
qualified_name: ./providerHeaderProfiles.ts
file_path: open-sse/config/cliFingerprints.ts
language: typescript
signature:
import {
  getAntigravityUserAgent,
  GITHUB_COPILOT_CHAT_USER_AGENT,
  getQwenOauthHeaders,
} from "./providerHeaderProfiles.ts";


id: constant:a3996c7d0682904766e0b09fd4e85a95
kind: constant
name: CLI_FINGERPRINTS
qualified_name: CLI_FINGERPRINTS
file_path: open-sse/config/cliFingerprints.ts
language: typescript
signature:
= {
  codex: {
    headerOrder: [
      "Host",
      "Content-Type",
      "Authorization",
      "Ac...


id: function:1266c59e61afbe5fff5174f6ed643bff
kind: function
name: stripInternalBodyFields
qualified_name: stripInternalBodyFields
file_path: open-sse/config/cliFingerprints.ts
language: typescript
signature: (body: unknown): unknown
docstring:
Apply a CLI fingerprint to headers and body.
Returns { headers, bodyString } with the correct ordering.


id: function:de9b99cf73cf19e6b645ef86459dadd8
kind: function
name: applyFingerprint
qualified_name: applyFingerprint
file_path: open-sse/config/cliFingerprints.ts
language: typescript
signature:
(
  provider: string,
  headers: Record<string, string>,
  body: unknown
): { headers: Record<string, string>; bodyString: string }


id: variable:450b95a2682dd0e6227fc3d3927a093b
kind: variable
name: _cliCompatProviders
qualified_name: _cliCompatProviders
file_path: open-sse/config/cliFingerprints.ts
language: typescript
signature: = new Set()
docstring:
Runtime cache for CLI compat providers set via Settings UI.
Updated by the settings API when users toggle providers.


id: function:e0e2c91b5376cb0759b081aa966b6679
kind: function
name: createCodexClientIdentity
qualified_name: createCodexClientIdentity
file_path: open-sse/config/codexIdentity.ts
language: typescript
signature:
(
  sessionId: string | null,
  providerSpecificData?: Record<string, unknown> | null
): CodexClientIdentity | null


id: constant:49834cb35faf92e7a9d3e21067032944
kind: constant
name: CODEX_DEFAULT_INSTRUCTIONS
qualified_name: CODEX_DEFAULT_INSTRUCTIONS
file_path: open-sse/config/codexInstructions.ts
language: typescript
signature:
= `You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's compu...


id: constant:0564fe66ffde56fabf5245dfb56636ff
kind: constant
name: ANTIGRAVITY_DEFAULT_SYSTEM
qualified_name: ANTIGRAVITY_DEFAULT_SYSTEM
file_path: open-sse/config/constants.ts
language: typescript
signature:
= "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team wo...


id: constant:5c5d4cd0b75bf9def24bbe49f15b3e10
kind: constant
name: OAUTH_ENDPOINTS
qualified_name: OAUTH_ENDPOINTS
file_path: open-sse/config/constants.ts
language: typescript
signature:
= {
  google: {
    token: "https://oauth2.googleapis.com/token",
    auth: "https://accounts.google.c...


id: constant:67fe0a4a90f2911e0dcbd38b0a028431
kind: constant
name: PROVIDER_MAX_TOKENS
qualified_name: PROVIDER_MAX_TOKENS
file_path: open-sse/config/constants.ts
language: typescript
signature:
= {
  groq: 16384, // Groq strict per-model enforcement
  openai: 16384, // GPT-4/4o standard
  anthro...


id: constant:3b143b150d32ec1bfc38a44953c8c496
kind: constant
name: HTTP_STATUS
qualified_name: HTTP_STATUS
file_path: open-sse/config/constants.ts
language: typescript
signature:
= {
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  PAYMENT_REQUIRED: 402,
  FORBIDDEN: 403,
  NOT_FOUND: 4...


id: constant:51157dfc1ffee799e070949849c2cc8d
kind: constant
name: RateLimitReason
qualified_name: RateLimitReason
file_path: open-sse/config/constants.ts
language: typescript
signature:
= {
  QUOTA_EXHAUSTED: "quota_exhausted", // Daily/monthly quota depleted
  RATE_LIMIT_EXCEEDED: "rate...


id: function:0e81fbdd6377c1a707583211a11e748d
kind: function
name: envInt
qualified_name: envInt
file_path: open-sse/config/constants.ts
language: typescript
signature: (name: string, fallback: number): number
docstring:
─── Provider Resilience Profiles ───────────────────────────────────────────
Separate behavior for OAuth (low-limit, session-based) vs API Key (high-limit, metered)
Circuit-breaker thresholds and reset windows are overridable via
OMNIROUTE_CIRCUIT_BREAKER_* env vars so operators can dampen or harden
behavior without recompiling.


id: constant:1ac3337812000c6b9b3b7f654327b8b1
kind: constant
name: PROVIDER_PROFILES
qualified_name: PROVIDER_PROFILES
file_path: open-sse/config/constants.ts
language: typescript
signature:
= {
  oauth: {
    transientCooldown: 5000, // 5s (session tokens — short recovery)
    rateLimitCoold...


id: constant:009fae6171173827c3747a7f78e6d55b
kind: constant
name: DEFAULT_API_LIMITS
qualified_name: DEFAULT_API_LIMITS
file_path: open-sse/config/constants.ts
language: typescript
signature:
= {
  requestsPerMinute: 100, // 100 RPM (most APIs allow 60-600 RPM)
  minTimeBetweenRequests: 200, /...


id: constant:8fd253ee280f52ccd71732dff14006b6
kind: constant
name: DEFAULT_THINKING_CLAUDE_SIGNATURE
qualified_name: DEFAULT_THINKING_CLAUDE_SIGNATURE
file_path: open-sse/config/defaultThinkingSignature.ts
language: typescript
signature:
= "EpwGCkYIChgCKkCzVUuRrg7CcglSUWEef4rH6o35g9UYS8ZPe0/VomQTBsFx6sttYNj5l8GqgW6ejuHyYqpFToxIbZl0bw17l5d...


id: constant:0a753009d6fdb203a5b819117bb91ad0
kind: constant
name: DEFAULT_THINKING_GEMINI_SIGNATURE
qualified_name: DEFAULT_THINKING_GEMINI_SIGNATURE
file_path: open-sse/config/defaultThinkingSignature.ts
language: typescript
signature:
= "EuwGCukGAXLI2nxwZIq54WWSoL/YN0P3TsDZ7zRnLi8g0S4aVr2HUGxvaHKySuY6HAVzcE0GPGjXrytLIldxthSvfxgUlJh6Qa9...


id: constant:ae902bb14db73d65f807bc64a5d6c653
kind: constant
name: EMBEDDING_PROVIDERS
qualified_name: EMBEDDING_PROVIDERS
file_path: open-sse/config/embeddingRegistry.ts
language: typescript
signature:
= {
  cohere: {
    id: "cohere",
    baseUrl: "https://api.cohere.com/v2/embed",
    authType: "apike...


id: function:5e648fef07fb0e0be141196f3e3cb190
kind: function
name: parseEmbeddingModel
qualified_name: parseEmbeddingModel
file_path: open-sse/config/embeddingRegistry.ts
language: typescript
signature:
(
  modelStr: string | null,
  dynamicProviders?: EmbeddingProvider[]
): { provider: string | null; model: string | null }


id: constant:028e80e651c36ace2a119d4380e9f5e0
kind: constant
name: ERROR_TYPES
qualified_name: ERROR_TYPES
file_path: open-sse/config/errorConfig.ts
language: typescript
signature:
= {
  400: { type: "invalid_request_error", code: "bad_request" },
  401: { type: "authentication_erro...


id: constant:a1c1574e5615c4dac5592d1d1330a151
kind: constant
name: DEFAULT_ERROR_MESSAGES
qualified_name: DEFAULT_ERROR_MESSAGES
file_path: open-sse/config/errorConfig.ts
language: typescript
signature:
= {
  400: "Bad request",
  401: "Invalid API key provided",
  402: "Payment required",
  403: "You ex...


id: constant:ea83262bba07f1b285ed2c81a47cf015
kind: constant
name: COOLDOWN_MS
qualified_name: COOLDOWN_MS
file_path: open-sse/config/errorConfig.ts
language: typescript
signature:
= {
  unauthorized: 2 * 60 * 1000,
  paymentRequired: 2 * 60 * 1000,
  notFound: 2 * 60 * 1000,
  notF...


id: constant:174a0415b7927b44e89bee2724e0d4f5
kind: constant
name: ERROR_RULES
qualified_name: ERROR_RULES
file_path: open-sse/config/errorConfig.ts
language: typescript
signature:
= [
  {
    id: "no_credentials",
    text: "no credentials",
    cooldownMs: COOLDOWN_MS.notFound,
  ...


id: constant:1f22cd4fd934e69b3dabcffbb27f47d9
kind: constant
name: GLM_DEFAULT_BASE_URLS
qualified_name: GLM_DEFAULT_BASE_URLS
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
= Object.freeze({
  international: "https://api.z.ai/api/coding/paas/v4/chat/completions",
  china: "h...


id: constant:ea6417c804857548d54fdb1b4e7cbb62
kind: constant
name: GLM_ANTHROPIC_DEFAULT_BASE_URLS
qualified_name: GLM_ANTHROPIC_DEFAULT_BASE_URLS
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
= Object.freeze({
  international: "https://api.z.ai/api/anthropic/v1/messages",
  china: "https://ope...


id: constant:e4fd6e64b1749d61975598f114fdc48f
kind: constant
name: GLM_SHARED_MODELS
qualified_name: GLM_SHARED_MODELS
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
= Object.freeze([
  {
    id: "glm-5.1",
    name: "GLM 5.1",
    contextLength: 204800,
    maxOutput...


id: constant:14759e0aacfd3d7ad2ac26cdf81fb241
kind: constant
name: GLM_MODELS_URLS
qualified_name: GLM_MODELS_URLS
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
= Object.freeze({
  international: "https://api.z.ai/api/coding/paas/v4/models",
  china: "https://ope...


id: constant:5041ed3c4bb1ae13c7927ff4d97ec663
kind: constant
name: GLM_QUOTA_URLS
qualified_name: GLM_QUOTA_URLS
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
= Object.freeze({
  international: "https://api.z.ai/api/monitor/usage/quota/limit",
  china: "https:/...


id: constant:32bbd5123d922cb569d0f21aa6c98b30
kind: constant
name: GLMT_REQUEST_DEFAULTS
qualified_name: GLMT_REQUEST_DEFAULTS
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
= Object.freeze({
  maxTokens: 65_536,
  temperature: 0.2,
  thinkingBudgetTokens: 24_576,
  thinkingT...


id: constant:3a6cde9d793dce8ff60bbe9c2ef41187
kind: constant
name: GLM_ANTHROPIC_BETA
qualified_name: GLM_ANTHROPIC_BETA
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
= [
  "claude-code-20250219",
  "interleaved-thinking-2025-05-14",
  "context-management-2025-06-27",
...


id: function:08dd5287562d69ce7884e43214f27cc6
kind: function
name: buildGlmModelsUrl
qualified_name: buildGlmModelsUrl
file_path: open-sse/config/glmProvider.ts
language: typescript
signature:
(
  providerSpecificData: unknown,
  transport: GlmTransport = "openai",
  fallbackBaseUrl?: string | null
): string


id: interface:eaa030489cacb217b3ea6143df155a38
kind: interface
name: ImageModelEntry
qualified_name: ImageModelEntry
file_path: open-sse/config/imageRegistry.ts
language: typescript
docstring:
Image Generation Provider Registry
Defines providers that support the /v1/images/generations endpoint.
Each provider has its own request format and endpoint.


id: constant:d256d08ddb7cf560f1a199ba1230c835
kind: constant
name: IMAGE_MODEL_ALIASES
qualified_name: IMAGE_MODEL_ALIASES
file_path: open-sse/config/imageRegistry.ts
language: typescript
signature:
= {
  "gemini-3.1-flash-image-preview": {
    provider: "antigravity",
    model: "gemini-3.1-flash-im...


id: constant:4c44b44ffa6b7d980c2bfe7ba0f4407a
kind: constant
name: IMAGE_PROVIDERS
qualified_name: IMAGE_PROVIDERS
file_path: open-sse/config/imageRegistry.ts
language: typescript
signature:
= {
  openai: {
    id: "openai",
    baseUrl: "https://api.openai.com/v1/images/generations",
    aut...


id: constant:548c6fc6b91587583deb7594bef95d3d
kind: constant
name: MODERATION_PROVIDERS
qualified_name: MODERATION_PROVIDERS
file_path: open-sse/config/moderationRegistry.ts
language: typescript
signature:
= {
  openai: {
    id: "openai",
    baseUrl: "https://api.openai.com/v1/moderations",
    authType: ...


id: constant:0cf4a4203579e87d89cb92e7938824b9
kind: constant
name: MUSIC_PROVIDERS
qualified_name: MUSIC_PROVIDERS
file_path: open-sse/config/musicRegistry.ts
language: typescript
signature:
= {
  kie: {
    id: "kie",
    baseUrl: "https://api.kie.ai",
    statusUrl: "https://api.kie.ai/api/...


id: constant:e476b9ad9ba3720ea1bef67fdb44cad0
kind: constant
name: ollamaModels
qualified_name: ollamaModels
file_path: open-sse/config/ollamaModels.ts
language: typescript
signature:
= {
  models: [
    {
      name: "llama3.2",
      modified_at: "2025-12-26T00:00:00Z",
      size: 2...


id: function:fdf421fbbea91833959988788a6fdd32
kind: function
name: getGitHubCopilotChatHeaders
qualified_name: getGitHubCopilotChatHeaders
file_path: open-sse/config/providerHeaderProfiles.ts
language: typescript
signature:
(
  accept = "application/json",
  initiator = GITHUB_COPILOT_DEFAULT_INITIATOR
): Record<string, string>


id: import:f81a97757de918fede9c268be8d11272
kind: import
name: ./anthropicHeaders.ts
qualified_name: ./anthropicHeaders.ts
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
import {
  ANTHROPIC_BETA_API_KEY,
  ANTHROPIC_BETA_CLAUDE_OAUTH,
  ANTHROPIC_VERSION_HEADER,
  CLAUDE_CLI_STAINLESS_PACKAGE_VERSION,
  CLAUDE_CLI_STAINLESS_RUNTIME_VERSION,
  CLAUDE_CLI_USER_AGENT,
} from "./anthropicHeaders.ts";


id: import:ff5e185f1e402bbc3a8e231064b98bf1
kind: import
name: ./glmProvider.ts
qualified_name: ./glmProvider.ts
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
import {
  GLM_REQUEST_DEFAULTS,
  GLMT_REQUEST_DEFAULTS,
  GLM_TIMEOUT_MS,
  GLMT_TIMEOUT_MS,
  GLM_SHARED_MODELS,
} from "./glmProvider.ts";


id: import:7fd79417c043fa5d6b7c4fef236ff0de
kind: import
name: ./providerHeaderProfiles.ts
qualified_name: ./providerHeaderProfiles.ts
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
import {
  CURSOR_REGISTRY_VERSION,
  getAntigravityProviderHeaders,
  getCursorRegistryHeaders,
  getGitHubCopilotChatHeaders,
  getKiroServiceHeaders,
  getQoderDefaultHeaders,
  getQwenOauthHeaders,
  getRuntimePlatform,
  getRuntimeArch,
} from "./providerHeaderProfiles.ts";


id: constant:d119bdbab2dfbf0d3944697974e37ac0
kind: constant
name: REASONING_UNSUPPORTED
qualified_name: REASONING_UNSUPPORTED
file_path: open-sse/config/providerRegistry.ts
language: typescript
docstring:
Reasoning models reject temperature, top_p, penalties, logprobs, n.
Frozen to prevent accidental mutation (shared across all model entries).

signature:
= Object.freeze([
  "temperature",
  "top_p",
  "frequency_penalty",
  "presence_penalty",
  "logprobs...


id: constant:dbf842b866f3d60b38cab3206780e256
kind: constant
name: KIMI_CODING_SHARED
qualified_name: KIMI_CODING_SHARED
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
= {
  format: "claude",
  executor: "default",
  baseUrl: "https://api.kimi.com/coding/v1/messages",
 ...


id: constant:27050e1b6da15a20e55d48932d7c22fd
kind: constant
name: ALIBABA_DASHSCOPE_MODELS
qualified_name: ALIBABA_DASHSCOPE_MODELS
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
= [
  { id: "qwen-max", name: "Qwen Max" },
  { id: "qwen-max-2025-01-25", name: "Qwen Max (2025-01-25...


id: constant:4daba2a2e08622b488c0cffa95c29edb
kind: constant
name: GPT_5_5_CODEX_CAPABILITIES
qualified_name: GPT_5_5_CODEX_CAPABILITIES
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
= {
  targetFormat: "openai-responses",
  toolCalling: true,
  supportsReasoning: true,
  supportsVisi...


id: constant:9ed38528e8bf9fa99cf07a760dc527ae
kind: constant
name: CHAT_OPENAI_COMPAT_MODELS
qualified_name: CHAT_OPENAI_COMPAT_MODELS
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
= {
  deepinfra: buildModels([
    "anthropic/claude-4-opus",
    "anthropic/claude-4-sonnet",
    "op...


id: constant:3c0312df9d59131f49851624340d3d0d
kind: constant
name: REGISTRY
qualified_name: REGISTRY
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature:
= {
  // ─── OAuth Providers ───────────────────────────────────────────────────
  kie: {
    id: "kie...


id: constant:9ed8ca1f2b365446152d2323ffc5a6d0
kind: constant
name: LOCAL_HOSTNAMES
qualified_name: LOCAL_HOSTNAMES
file_path: open-sse/config/providerRegistry.ts
language: typescript
docstring:
── Local Provider Detection ──────────────────────────────────────────────
Evaluated once at module load time — process restart required for env var changes.

signature:
= new Set([
  "localhost",
  "127.0.0.1",
  ...(typeof process !== "undefined" && process.env.LOCAL_HO...


id: constant:193c8ef4eccd1e85c22feb249262dda2
kind: constant
name: _passthroughProviderIds
qualified_name: _passthroughProviderIds
file_path: open-sse/config/providerRegistry.ts
language: typescript
docstring: Set of provider IDs with passthroughModels enabled — 404s are model-specific, not account-level.
signature:
= (() => {
  try {
    const ids = new Set<string>();
    for (const entry of Object.values(REGISTRY))...


id: constant:df8f73891d2d2ff0ca72f57df124afcb
kind: constant
name: _unsupportedParamsMap
qualified_name: _unsupportedParamsMap
file_path: open-sse/config/providerRegistry.ts
language: typescript
signature: = new Map<string, readonly string[]>()
docstring:
Precomputed map: modelId → unsupportedParams (O(1) lookup instead of O(N×M) scan).
Built once at module load from all registry entries.


id: function:9a9ff31c355ad8b508a4bc76c6f343c6
kind: function
name: parseModelFromRegistry
qualified_name: parseModelFromRegistry
file_path: open-sse/config/registryUtils.ts
language: typescript
signature:
(
  modelStr: string | null,
  registry: Record<string, P>
): { provider: string | null; model: string | null }


id: function:72faa9e52168eb091bb38188ff9b9a7f
kind: function
name: getAllModelsFromRegistry
qualified_name: getAllModelsFromRegistry
file_path: open-sse/config/registryUtils.ts
language: typescript
signature:
(
  registry: Record<string, P>,
  extra?: (providerId: string, config: P) => Record<string, unknown>
): Array<{ id: string; name: string; provider: string } & Record<string, unknown>>


id: constant:6d76f0d41f24a3b1606dcae310ea4a80
kind: constant
name: RERANK_PROVIDERS
qualified_name: RERANK_PROVIDERS
file_path: open-sse/config/rerankRegistry.ts
language: typescript
signature:
= {
  cohere: {
    id: "cohere",
    baseUrl: "https://api.cohere.com/v2/rerank",
    authType: "apik...


id: constant:2106f6b3308aa600ffe76ff39c3062e3
kind: constant
name: RUNWAYML_SUPPORTED_VIDEO_MODELS
qualified_name: RUNWAYML_SUPPORTED_VIDEO_MODELS
file_path: open-sse/config/runway.ts
language: typescript
signature:
= [
  { id: "gen4.5", name: "Gen-4.5" },
  { id: "gen4_turbo", name: "Gen-4 Turbo" },
  { id: "gen3a_t...


id: function:1a4d83d17598162674949470c16a0d4a
kind: function
name: getSapResourceGroup
qualified_name: getSapResourceGroup
file_path: open-sse/config/sap.ts
language: typescript
signature:
(
  providerSpecificData: Record<string, unknown> | null | undefined,
  fallback = "default"
): string


id: constant:c6e965c3f9652be78fb7b7cb0e11cd16
kind: constant
name: SEARCH_PROVIDERS
qualified_name: SEARCH_PROVIDERS
file_path: open-sse/config/searchRegistry.ts
language: typescript
signature:
= {
  "serper-search": {
    id: "serper-search",
    name: "Serper Search",
    baseUrl: "https://goo...


id: constant:10b7be7e330249bed8ad72a7d3fa5877
kind: constant
name: SEARCH_CREDENTIAL_FALLBACKS
qualified_name: SEARCH_CREDENTIAL_FALLBACKS
file_path: open-sse/config/searchRegistry.ts
language: typescript
signature:
= {
  "perplexity-search": "perplexity",
  "ollama-search": "ollama-cloud",
  "zai-search": "zai",
}


id: constant:fd73a994927e25cac7f66a45dbda5723
kind: constant
name: AG_DEFAULT_TOOL_NAMES
qualified_name: AG_DEFAULT_TOOL_NAMES
file_path: open-sse/config/toolCloaking.ts
language: typescript
signature:
= [
  "browser_subagent",
  "command_status",
  "find_by_name",
  "generate_image",
  "grep_search",
 ...


id: constant:79e7b9486e8d76adf39a3fc4d758172f
kind: constant
name: AG_DECOY_TOOLS
qualified_name: AG_DECOY_TOOLS
file_path: open-sse/config/toolCloaking.ts
language: typescript
signature:
= AG_DECOY_TOOL_NAMES.map((name) =>
  Object.freeze({
    name,
    description: "This tool is current...


id: import:9ea73cab0c16016f3628a9ab83d513be
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeAbortSignals,
  mergeUpstreamExtraHeaders,
  type ExecuteInput,
  type ExecutorLog,
  type ProviderCredentials,
} from "./base.ts";


id: import:23323ccd5d181a12df8cd5d09ddb1722
kind: import
name: ../config/constants.ts
qualified_name: ../config/constants.ts
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
import {
  PROVIDERS,
  OAUTH_ENDPOINTS,
  HTTP_STATUS,
  STREAM_READINESS_TIMEOUT_MS,
  ANTIGRAVITY_PRE_RESPONSE_TIMEOUT_CODE,
} from "../config/constants.ts";


id: import:c0250bf3cf1e24ed0628c1645ac880f7
kind: import
name: ../services/antigravityHeaders.ts
qualified_name: ../services/antigravityHeaders.ts
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
import {
  antigravityNativeOAuthUserAgent,
  antigravityUserAgent,
} from "../services/antigravityHeaders.ts";


id: import:80b65f7ba301f6ea167e8f15b53db0b3
kind: import
name: ../services/antigravityCredits.ts
qualified_name: ../services/antigravityCredits.ts
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
import {
  injectCreditsField,
  shouldRetryWithCredits,
  shouldUseCreditsFirst,
  getCreditsMode,
  handleCreditsFailure,
} from "../services/antigravityCredits.ts";


id: import:0e0f407f8a73c18a3ad7e9d7666dd337
kind: import
name: ../services/cloudCodeThinking.ts
qualified_name: ../services/cloudCodeThinking.ts
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
import {
  shouldStripCloudCodeThinking,
  stripCloudCodeThinkingConfig,
} from "../services/cloudCodeThinking.ts";


id: import:3076febda73ec41104f6c20eb9059518
kind: import
name: ../services/antigravityClientProfile.ts
qualified_name: ../services/antigravityClientProfile.ts
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
import {
  applyAntigravityClientProfileHeaders,
  removeHeaderCaseInsensitive,
} from "../services/antigravityClientProfile.ts";


id: import:ef8f48ed8abde357cd930196cc8eeaf6
kind: import
name: ../services/antigravityIdentity.ts
qualified_name: ../services/antigravityIdentity.ts
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
import {
  generateAntigravityRequestId,
  getAntigravityEnvelopeUserAgent,
  getAntigravitySessionId,
} from "../services/antigravityIdentity.ts";


id: constant:17ac3dc3ef242fa415795cdfe0d079c9
kind: constant
name: creditsExhaustedUntil
qualified_name: creditsExhaustedUntil
file_path: open-sse/executors/antigravity.ts
language: typescript
signature: = new Map<string, number>()
docstring:
Per-account GOOGLE_ONE_AI credits-exhausted tracker.
Key: accountId (OAuth subject / email). Value: expiry timestamp.
When credits hit 0 we skip the credit retry for CREDITS_EXHAUSTED_TTL_MS.


id: constant:c4f48be1c23d6078257b6e285ec5a277
kind: constant
name: creditBalanceCache
qualified_name: creditBalanceCache
file_path: open-sse/executors/antigravity.ts
language: typescript
signature: = new Map<string, number>()
docstring:
Per-account GOOGLE_ONE_AI remaining credit balance cache.
Populated from the final SSE chunk's `remainingCredits` field after every
successful credit-injected request. Keyed by accountId.
On first access, hydrated from the DB-persisted balances so values survive restarts.


id: function:5cc8eb70b4241e6e49bb33147d1b077e
kind: function
name: processAntigravitySSEPayload
qualified_name: processAntigravitySSEPayload
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
(
  payload: string,
  collected: AntigravityCollectedStream,
  log?: { debug?: (scope: string, message: string) => void }
)


id: function:4bebc59088351c6c669dfe49b76e924e
kind: function
name: processAntigravitySSEText
qualified_name: processAntigravitySSEText
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
(
  text: string,
  partialLine: { value: string },
  collected: AntigravityCollectedStream,
  log?: { debug?: (scope: string, message: string) => void }
)


id: function:88bf96c734c8393023db1a854e001eab
kind: function
name: flushAntigravitySSEText
qualified_name: flushAntigravitySSEText
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
(
  partialLine: { value: string },
  collected: AntigravityCollectedStream,
  log?: { debug?: (scope: string, message: string) => void }
)


id: function:7d6b2e1496c3413a162470c3da150758
kind: function
name: cleanModelName
qualified_name: cleanModelName
file_path: open-sse/executors/antigravity.ts
language: typescript
signature: (model: string): string
docstring:
Strip provider prefixes (e.g. "antigravity/model" → "model").
Ensures the model name sent to the upstream API never contains a routing prefix.


id: method:a4867f8e3e0af913c561477b14eec2af
kind: method
name: transformRequest
qualified_name: AntigravityExecutor::transformRequest
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
(
    model: string,
    body: unknown,
    _stream: boolean,
    credentials: AntigravityCredentials
  ): Promise<AntigravityRequestEnvelope | Response>


id: method:88ff57fe522a87c86baff914f784e293
kind: method
name: refreshCredentials
qualified_name: AntigravityExecutor::refreshCredentials
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
(
    credentials: AntigravityCredentials,
    log?: ExecutorLog | null
  ): Promise<AntigravityCredentials | null>


id: method:409300bc19e9e2195367c1c85f3bb68d
kind: method
name: parseRetryFromErrorMessage
qualified_name: AntigravityExecutor::parseRetryFromErrorMessage
file_path: open-sse/executors/antigravity.ts
language: typescript
signature: (errorMessage: unknown): number | null
docstring:
Parse retry time from Antigravity error message body
Format: "Your quota will reset after 2h7m23s" or "1h30m" or "45m" or "30s"


id: method:4b3f5e7db36f97a2c206508476d464f4
kind: method
name: collectStreamToResponse
qualified_name: AntigravityExecutor::collectStreamToResponse
file_path: open-sse/executors/antigravity.ts
language: typescript
docstring:
Collect an SSE streaming response into a single non-streaming JSON response.
Parses Gemini-format SSE chunks and assembles text content + usage into one
OpenAI-format chat.completion payload.

signature:
(
    response: Response,
    model: string,
    url: string,
    headers: Record<string, string>,
    transformedBody: Record<string, unknown>,
    log?: ExecutorLog | null,
    signal?: AbortSignal | null
  )


id: method:440c87b4bc82735233cbfb2e818d8093
kind: method
name: execute
qualified_name: AntigravityExecutor::execute
file_path: open-sse/executors/antigravity.ts
language: typescript
signature:
({
    model,
    body,
    stream,
    credentials,
    signal,
    log,
    upstreamExtraHeaders,
  }: ExecuteInput)


id: import:585f2624ec8556817220bb14fd26ca60
kind: import
name: ../services/apiKeyRotator.ts
qualified_name: ../services/apiKeyRotator.ts
file_path: open-sse/executors/base.ts
language: typescript
signature:
import {
  getRotatingApiKey,
  getValidApiKey,
  resolveKeyForRequest,
} from "../services/apiKeyRotator.ts";


id: import:321ff6864eeec2bf6850995c6cf0f9fc
kind: import
name: ../services/claudeCodeCompatible.ts
qualified_name: ../services/claudeCodeCompatible.ts
file_path: open-sse/executors/base.ts
language: typescript
signature:
import {
  appendAnthropicBetaHeader,
  CONTEXT_1M_BETA_HEADER,
  modelSupportsContext1mBeta,
} from "../services/claudeCodeCompatible.ts";


id: import:aee379ce81a14d365f7244b10e81157b
kind: import
name: ../services/contextManager.ts
qualified_name: ../services/contextManager.ts
file_path: open-sse/executors/base.ts
language: typescript
signature:
import {
  fixToolPairs,
  fixToolAdjacency,
  stripTrailingAssistantOrphanToolUse,
} from "../services/contextManager.ts";


id: import:8e5caf2657e656e6976b9c0533eee204
kind: import
name: ./claudeIdentity.ts
qualified_name: ./claudeIdentity.ts
file_path: open-sse/executors/base.ts
language: typescript
signature:
import {
  CLAUDE_CODE_VERSION,
  CLAUDE_CODE_STAINLESS_VERSION,
  buildHashFor,
  buildUserIdJson,
  getSessionId,
  parseUpstreamMetadataUserId,
  passthroughUpstreamSessionId,
  resolveAccountUUID,
  resolveCliUserID,
  selectBetaFlags,
  stainlessArch,
  stainlessOS,
  stainlessRuntimeVersion,
  stripProxyToolPrefix,
} from "./claudeIdentity.ts";


id: function:54445976f109a67d104b9e34c22788c4
kind: function
name: sanitizePath
qualified_name: sanitizePath
file_path: open-sse/executors/base.ts
language: typescript
signature: (path: string): boolean
docstring:
Sanitizes a custom API path to prevent path traversal attacks.
Valid paths must start with '/', contain no '..' segments,
no null bytes, and be reasonable in length.


id: constant:1587505dc02c3fbdce0593a535d70ba5
kind: constant
name: MISTRAL_NO_REASONING_EFFORT_PATTERN
qualified_name: MISTRAL_NO_REASONING_EFFORT_PATTERN
file_path: open-sse/executors/base.ts
language: typescript
signature: = /devstral/i
docstring:
Sanitize reasoning_effort for providers that don't accept all values.
The claude→openai translator emits reasoning_effort=xhigh when the client
sends output_config.effort=max on a Claude-shape request. Combined with
runtime alias remapping (e.g. claude-opus-4-6 → mimo/mimo-v2.5-pro), this
routes xhigh to OpenAI-shape providers that don't accept the value:
  xiaomi-mimo : low|medium|high only — 400 literal_error on xhigh
  mistral     : devstral models reject reasoning_effort entirely
  github      : claude/haiku/oswe models reject reasoning_effort entirely
Each rejection burns a combo fallback attempt before reaching a working
provider. Apply provider-aware sanitation here (after transformRequest, so
reintroductions by per-provider transforms are also caught) before fetch.
Models that genuinely support xhigh (registry flag supportsXHighEffort)
pass through unchanged.


id: function:de35bd30f9c685debe168f7cfba23647
kind: function
name: sanitizeReasoningEffortForProvider
qualified_name: sanitizeReasoningEffortForProvider
file_path: open-sse/executors/base.ts
language: typescript
signature:
(
  body: unknown,
  provider: string,
  model: string | undefined,
  log?: { info?: (tag: string, msg: string) => void } | null
): unknown


id: method:3ec59a16c04b372c9b865809b252d2d1
kind: method
name: buildUrl
qualified_name: BaseExecutor::buildUrl
file_path: open-sse/executors/base.ts
language: typescript
signature:
(
    model: string,
    stream: boolean,
    urlIndex = 0,
    credentials: ProviderCredentials | null = null
  )


id: method:568aacb3a14dee0348b0865d01e473cb
kind: method
name: buildHeaders
qualified_name: BaseExecutor::buildHeaders
file_path: open-sse/executors/base.ts
language: typescript
signature:
(
    credentials: ProviderCredentials,
    stream = true,
    clientHeaders?: Record<string, string> | null,
    model?: string,
    health?: Record<string, KeyHealth>
  ): Record<string, string>


id: method:7d46964dbec99da45895d3aa5c7a503f
kind: method
name: transformRequest
qualified_name: BaseExecutor::transformRequest
file_path: open-sse/executors/base.ts
language: typescript
docstring: Override in subclass for provider-specific transformations
signature:
(
    model: string,
    body: unknown,
    stream: boolean,
    credentials: ProviderCredentials
  ): unknown


id: method:429774204996ae7219f22c1f1f7d22d0
kind: method
name: FETCH_START_TIMEOUT_MS
qualified_name: BaseExecutor::FETCH_START_TIMEOUT_MS
file_path: open-sse/executors/base.ts
language: typescript
docstring:
Timeout for receiving the initial upstream response headers. Once the response
starts streaming, STREAM_IDLE_TIMEOUT_MS / Undici bodyTimeout handle stalls.


id: method:60e38633b870ff7f64d81b4f1628ba0f
kind: method
name: refreshCredentials
qualified_name: BaseExecutor::refreshCredentials
file_path: open-sse/executors/base.ts
language: typescript
docstring: Override in subclass for provider-specific refresh
signature:
(
    credentials: ProviderCredentials,
    log: ExecutorLog | null
  ): Promise<Partial<ProviderCredentials> | null>


id: method:50e70f52d33a645537fd5e29b448f324
kind: method
name: execute
qualified_name: BaseExecutor::execute
file_path: open-sse/executors/base.ts
language: typescript
signature:
({
    model,
    body,
    stream,
    credentials,
    signal,
    log,
    extendedContext,
    upstreamExtraHeaders,
    clientHeaders,
    skipUpstreamRetry = false,
  }: ExecuteInput)


id: import:6beaae5f59be2215175daf17aa54375f
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/blackbox-web.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeAbortSignals,
  mergeUpstreamExtraHeaders,
  type ExecuteInput,
} from "./base.ts";


id: constant:9c8787168f7060f2354610e6f8f962b4
kind: constant
name: BLACKBOX_USER_AGENT
qualified_name: BLACKBOX_USER_AGENT
file_path: open-sse/executors/blackbox-web.ts
language: typescript
signature:
= "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537....


id: function:8705c2991c90f09295a3c9bc1afb031c
kind: function
name: isBlackboxValidatedTokenError
qualified_name: isBlackboxValidatedTokenError
file_path: open-sse/executors/blackbox-web.ts
language: typescript
signature: (responseText: string): boolean
docstring:
Detect whether a Blackbox 403 response body indicates that the `validated`
token is the problem (as opposed to a missing cookie or expired subscription).
Surfaces the BLACKBOX_WEB_VALIDATED_TOKEN env var as the next step.


id: function:344228ae3edac18c7d6507df65a29c7d
kind: function
name: buildStreamingResponse
qualified_name: buildStreamingResponse
file_path: open-sse/executors/blackbox-web.ts
language: typescript
signature:
(
  responseText: string,
  model: string,
  id: string,
  created: number
): ReadableStream<Uint8Array>


id: import:cd1eb2c4a561b47fd5f8e3c842e3f149
kind: import
name: ../services/chatgptTlsClient.ts
qualified_name: ../services/chatgptTlsClient.ts
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
import {
  tlsFetchChatGpt,
  TlsClientUnavailableError,
  type TlsFetchResult,
} from "../services/chatgptTlsClient.ts";


id: import:85961413b746cc92b180e2a703ea52ed
kind: import
name: ../services/chatgptImageCache.ts
qualified_name: ../services/chatgptImageCache.ts
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
import {
  storeChatGptImage,
  getChatGptImageConversationContext,
  __resetChatGptImageCacheForTesting,
  type ChatGptImageConversationContext,
} from "../services/chatgptImageCache.ts";


id: constant:a858b399608ebe2ab5b20f7c617b4d2a
kind: constant
name: deviceIdCache
qualified_name: deviceIdCache
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = new Map<string, string>()
docstring:
Per-cookie device ID. The browser stores a persistent `oai-did` cookie that
uniquely identifies the device for OpenAI's risk model — we derive a stable
UUID from a hash of the session cookie so that each account/connection gets
its own device id, but it doesn't change between requests.


id: constant:cf90c95bad287fdcc44262164cd90c60
kind: constant
name: MODEL_MAP
qualified_name: MODEL_MAP
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
OmniRoute model ID → ChatGPT internal slug. OmniRoute uses dot-form IDs
(e.g. "gpt-5.3-instant"), ChatGPT's web routes use dash-form
(e.g. "gpt-5-3-instant"). The slug catalog comes from
/backend-api/models on a logged-in account; "gpt-5-4-t-mini" is ChatGPT's
abbreviated slug for "GPT-5.4 Thinking Mini".

signature:
= {
  "gpt-5.3-instant": "gpt-5-3-instant",
  "gpt-5.3": "gpt-5-3",
  "gpt-5.3-mini": "gpt-5-3-mini",
...


id: constant:9e27094d67d45fba43226a67acd11aad
kind: constant
name: THINKING_CAPABLE_SLUGS
qualified_name: THINKING_CAPABLE_SLUGS
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
Set of chatgpt.com slugs that the user_last_used_model_config endpoint
accepts a `thinking_effort` value for, derived from MODEL_MAP so adding a
new thinking entry there automatically extends this set. Includes the
abbreviated slug `gpt-5-4-t-mini` (no literal "thinking" substring) — the
reason this set exists at all rather than a substring match.
Derived from MODEL_MAP keys (always dot-form) that contain "thinking" or
are the `o3` reasoning model; the values are the chatgpt.com-side slugs.

signature:
= new Set(
  Object.entries(MODEL_MAP)
    .filter(([k]) => k.includes("thinking") || k === "o3")
    ...


id: interface:042959664191dbc7aa33c2829c3db627
kind: interface
name: SessionResponse
qualified_name: SessionResponse
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
Conversation continuity is intentionally not cached. Open WebUI and most
OpenAI-API-style clients re-send the full history each turn, so each
request just starts a fresh conversation. Temporary Chat mode is the
default; it gets disabled per-request only for image-gen prompts, since
that mode rejects the image_gen tool.
─── /api/auth/session — exchange cookie for JWT ────────────────────────────


id: constant:1890fd642a6be046d391ec849bd80bb9
kind: constant
name: SESSION_TOKEN_FAMILY_RE
qualified_name: SESSION_TOKEN_FAMILY_RE
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = /^__Secure-next-auth\.session-token(?:\.\d+)?$/
docstring:
Session-token family — NextAuth uses one of these depending on token size:
__Secure-next-auth.session-token            (unchunked, < 4KB)
__Secure-next-auth.session-token.0          (chunked, first piece)
__Secure-next-auth.session-token.N          (chunked, additional pieces)
Rotation can change the shape (unchunked → chunked or vice versa). When
that happens, every old family member must be dropped — keeping the stale
variant alongside the new one would send both, and depending on parser
precedence the server could read the stale value and fail auth.


id: function:3e7c5fde448d2e3130a9ca5cd68699e8
kind: function
name: mergeRefreshedCookie
qualified_name: mergeRefreshedCookie
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: ( originalCookie: string, setCookieHeader: string | null ): string | null
docstring:
Merge any rotated session-token chunks from a Set-Cookie response into the
original cookie blob, preserving every other cookie the caller pasted
(cf_clearance, __cf_bm, _cfuvid, _puid, ...). Returns null if no rotation
occurred or the rotated chunks match what's already there.
Returning only the matched session-token chunks here was a bug: when the
caller pastes a full DevTools Cookie line (the recommended form), the
Cloudflare cookies are required for subsequent requests, and dropping
them re-triggers `cf-mitigated: challenge`.


id: function:29e2944ea8ab8c1acf9d36113f6ac157
kind: function
name: buildSessionCookieHeader
qualified_name: buildSessionCookieHeader
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: (rawInput: string): string
docstring:
Build the Cookie header value from whatever the user pasted.
Accepts:
  - A bare value:                       "eyJhbGc..."  →  prepended with __Secure-next-auth.session-token=
  - An unchunked cookie line:           "__Secure-next-auth.session-token=eyJ..."
  - A chunked cookie line:              "__Secure-next-auth.session-token.0=...; __Secure-next-auth.session-token.1=..."
  - The full DevTools cookie header:    "Cookie: __Secure-next-auth.session-token.0=...; cf_clearance=..."
If the user pastes a chunked token, we pass the cookies through verbatim —
NextAuth's server reassembles them on its side.


id: constant:ff611036b516d5b75c95f4a1782b62f3
kind: constant
name: warmupCache
qualified_name: warmupCache
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = new Map<string, number>()
docstring:
─── Session warmup ────────────────────────────────────────────────────────
Mimics chatgpt.com's page-load fetch sequence so Sentinel sees a "warm"
browsing session. Cached per (cookie, access-token) pair for 60s to avoid
hammering the warmup endpoints on every chat completion.


id: function:83e30e1a9a57d3414f658bfa18da7d58
kind: function
name: runSessionWarmup
qualified_name: runSessionWarmup
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  accessToken: string,
  accountId: string | null,
  sessionId: string,
  deviceId: string,
  cookie: string,
  signal: AbortSignal | null | undefined,
  log: { debug?: (tag: string, msg: string) => void } | null | undefined
): Promise<void>


id: constant:6d36e1e1c71b98d2890765009a4d9aed
kind: constant
name: thinkingEffortCache
qualified_name: thinkingEffortCache
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = new Map<string, number>()
docstring:
─── Thinking-effort preference (PATCH user_last_used_model_config) ────────
chatgpt.com has two thinking levels for its dedicated thinking-models:
• standard — default, faster
• extended — longer reasoning budget
The browser sets the level by PATCHing `/backend-api/settings/user_last_used_model_config`
once, then issues the conversation request — the conversation endpoint itself
has no `thinking_effort` field; the server reads the user's stored preference
at routing time. We mirror that handshake when an OpenAI-style request
includes `reasoning_effort` (or a direct `providerSpecificData.thinkingEffort`
override).

Cached per (cookie, slug, effort): the preference persists server-side, so
re-PATCHing the same combination is wasted bytes. Refreshed on TTL expiry or
whenever the caller switches efforts.


id: function:5688d6a9e70cefa26186e22e52c6d997
kind: function
name: isThinkingCapableModel
qualified_name: isThinkingCapableModel
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: (modelId: string, slug: string): boolean
docstring:
chatgpt.com only exposes the thinking-effort toggle on dedicated thinking
models and the o-series. PATCHing for a non-thinking surface is a no-op
(the server accepts it but the routing-time read picks the wrong knob).
Three branches because the input can arrive in three shapes:
  1. OmniRoute dot-form id (`gpt-5.4-thinking-mini`) — every thinking
     variant carries the literal "thinking" substring here.
  2. Resolved chatgpt.com slug containing "thinking" (`gpt-5-5-thinking`).
  3. Resolved chatgpt.com slug that drops the substring under abbreviation
     (`gpt-5-4-t-mini`). Looked up via THINKING_CAPABLE_SLUGS, which is
     derived from MODEL_MAP itself so adding a new abbreviated thinking
     mapping automatically extends the check.
Branch 3 also catches the case where a caller passes the chatgpt.com slug
directly as the `model` field (no MODEL_MAP translation needed), which
would otherwise silently bypass the PATCH.


id: function:373620e36533407709dd24cacfcb3566
kind: function
name: normalizeThinkingEffort
qualified_name: normalizeThinkingEffort
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: (input: unknown): "standard" | "extended" | null
docstring:
Map either a chatgpt.com-native value (`standard`/`extended`) or the
OpenAI Chat Completions `reasoning_effort` field to the value the
`user_last_used_model_config` endpoint expects.
  minimal | low | medium | standard  → standard
  high    | xhigh | extended         → extended
`medium` collapses to `standard` because chatgpt.com only has two levels —
there is no separate medium tier on the web product. Returns null for
absent/unknown inputs.


id: function:faf9593b0d6aa56ea25a80cd1a8773e9
kind: function
name: resolveThinkingEffort
qualified_name: resolveThinkingEffort
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
Resolve the requested effort for this turn.
Order: `providerSpecificData.thinkingEffort` (raw override, takes
`standard`/`extended` directly) > `body.reasoning_effort` (top-level OpenAI
Chat Completions field) > `body.reasoning.effort` (Responses-API nesting).
Returns null when the caller did not request one.

signature:
(
  body: unknown,
  providerSpecificData: Record<string, unknown> | undefined
): "standard" | "extended" | null


id: function:f0ec3a682135f95c1722db57fe84ceed
kind: function
name: setUserThinkingEffort
qualified_name: setUserThinkingEffort
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  modelSlug: string,
  effort: "standard" | "extended",
  accessToken: string,
  accountId: string | null,
  sessionId: string,
  deviceId: string,
  cookie: string,
  signal: AbortSignal | null | undefined,
  log:
    | {
        debug?: (tag: string, msg: string) => void;
        warn?: (tag: string, msg: string) => void;
      }
    | null
    | undefined
): Promise<void>


id: function:280775b0fc5bbfb95c962567a8b4dd3e
kind: function
name: prepareChatRequirements
qualified_name: prepareChatRequirements
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  accessToken: string,
  accountId: string | null,
  sessionId: string,
  deviceId: string,
  cookie: string,
  dplInfo: { dpl: string; scriptSrc: string },
  signal: AbortSignal | null | undefined,
  log?: { warn?: (tag: string, msg: string) => void } | null
): Promise<ChatRequirements>


id: interface:109b54ebdbcd19aef485f464d6ab0b39
kind: interface
name: DplInfo
qualified_name: DplInfo
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
─── Proof-of-work solver ──────────────────────────────────────────────────
Mimics the openai-sentinel / chat2api algorithm. The browser sends a base64-encoded
JSON config string; the server combines it with a seed and expects a SHA3-512 hash
whose hex-prefix is ≤ the difficulty target.

Reference: github.com/leetanshaj/openai-sentinel, github.com/lanqian528/chat2api
Returns "gAAAAAB" + base64 of the winning config (server-recognised prefix).
─── DPL / script-src cache (warmup) ────────────────────────────────────────
Sentinel's prekey check inspects whether config[5]/config[6] reference a real
chatgpt.com deployment (DPL hash + a script URL from the HTML). We GET / once
per hour to scrape these — same trick chat2api uses.


id: function:58d383f00b99778c26e87daff1f33086
kind: function
name: fetchDpl
qualified_name: fetchDpl
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  cookie: string,
  signal: AbortSignal | null | undefined
): Promise<{ dpl: string; scriptSrc: string }>


id: constant:57a57b2e008e71cfbad971d009f81ead
kind: constant
name: NAVIGATOR_KEYS
qualified_name: NAVIGATOR_KEYS
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
─── Browser fingerprint key lists (used in prekey config[10..12]) ─────────
Chosen to look like real navigator/document/window inspection. The unicode
MINUS SIGN (U+2212) in the navigator strings matches what `Object.toString()`
produces in real browsers — Sentinel checks for it.

signature:
= [
  "webdriver−false",
  "geolocation",
  "languages",
  "language",
  "platform",
  "userAgent",
  ...


id: constant:3f69d3a42d526c7ae5edf25fd56bcfeb
kind: constant
name: DOCUMENT_KEYS
qualified_name: DOCUMENT_KEYS
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
= [
  "_reactListeningkfj3eavmks",
  "_reactListeningo743lnnpvdg",
  "location",
  "scrollingElement",...


id: constant:21258acc62ee0cdaabc0d31bf758a479
kind: constant
name: WINDOW_KEYS
qualified_name: WINDOW_KEYS
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
= [
  "webpackChunk_N_E",
  "__NEXT_DATA__",
  "chrome",
  "history",
  "screen",
  "navigation",
  "s...


id: constant:1d4b35cf258b9905571eba7e69acad5e
kind: constant
name: POW_YIELD_EVERY
qualified_name: POW_YIELD_EVERY
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = 1000
docstring:
Build the `p` (prekey) value sent in the chat-requirements POST body.
Format: "<prefix>" + base64(JSON(config)), with a PoW solver loop mutating
config[3] to find a hash whose hex prefix is ≤ the target difficulty.
Mirrors chat2api / openai-sentinel.
  - prepare:      prefix="gAAAAAC", seed=""           (target "0fffff")
  - chat-requirements: prefix="gAAAAAB", seed=<server seed>  (target=difficulty)
Submitting an unsolved token still works on low-friction accounts, so we
fall back to that after exhausting the iteration budget — but emit a warn
log so production can see when it happens.
PoW solvers run up to 100k–500k SHA3-512 hashes. To avoid blocking the
Node event loop on a busy server, we yield with `setImmediate` every
POW_YIELD_EVERY iterations — roughly every ~5ms of work — so concurrent
requests and I/O still get scheduled. Wall time is approximately the same
as the synchronous version; what changes is fairness, not throughput.


id: function:cc91593834a7d3367623abd98d40743d
kind: function
name: buildPrepareToken
qualified_name: buildPrepareToken
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  config: unknown[],
  log?: { warn?: (tag: string, msg: string) => void } | null
): Promise<string>


id: function:91cfa1133e9479b5b7db1b86bebb8eed
kind: function
name: solveProofOfWork
qualified_name: solveProofOfWork
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  seed: string,
  difficulty: string,
  config: unknown[],
  log?: { warn?: (tag: string, msg: string) => void } | null
): Promise<string>


id: constant:911711a71aa141ac64c797303d445883
kind: constant
name: DATA_URI_IMAGE_RE
qualified_name: DATA_URI_IMAGE_RE
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = /!\[([^\]]*)\]\(data:image\/[^)]+\)/g
docstring:
Strip embedded `data:image/...` URIs out of message content so prior
generated images don't get fed back into chatgpt.com on the next turn.
Why: when image generation succeeds we emit `![image](data:image/png;base64,...)`
— frequently 2–4 MB. Chat clients (Open WebUI, OpenAI-style apps) replay
the full conversation history on the next request, so without this strip
we'd send megabytes of base64 back upstream. chatgpt.com responds with an
empty body when that happens (verified: 502 "ChatGPT returned empty
response body" on the very next turn after an image gen succeeds), and
even if it didn't, a single inlined image is well past the model's context
limit. Replacing with a short placeholder keeps semantic continuity
without the bytes.


id: constant:fb94a5150665a540943f2749251e9d88
kind: constant
name: IMAGE_GEN_REGEXES
qualified_name: IMAGE_GEN_REGEXES
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
Cheap heuristic: does the last user turn look like an image-generation
request? Used to decide whether to disable Temporary Chat mode.
Why a heuristic instead of always disabling Temporary Chat: when
`history_and_training_disabled: false`, every conversation gets saved to
the user's chatgpt.com history. For text-only chats that's noise — a
dozen "OmniRoute" entries clutter the sidebar and can interact with
ChatGPT's memory. We pay that cost only when the user actually wants an
image, since Temporary Chat refuses image_gen with the message
"I cannot generate images in this chat".
False positives (text chat misclassified as image) → unnecessary history
entry. False negatives (image request misclassified as text) → ChatGPT
refuses image_gen and the user retries. Tuning leans toward false
positives (we'd rather pollute history than refuse image generation).

signature:
= [
  // verb + (anything within 40 chars) + image-noun
  /\b(?:generate|create|make|draw|paint|render...


id: constant:3392b04818f4ca5c5f5e2e350c537d12
kind: constant
name: OPENWEBUI_TOOL_PROMPT_MARKERS
qualified_name: OPENWEBUI_TOOL_PROMPT_MARKERS
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
Markers Open WebUI uses for its background tool prompts (follow-up
suggestions, title generation, tag categorization). These prompts embed
the prior conversation in `<chat_history>` blocks and frequently quote
the user's earlier "generate an image of..." request — which would
trip the image-gen regex below. Skip them so we don't unnecessarily
disable Temporary Chat and trigger image_gen on background tasks.
Catching just one of these markers is enough; tool prompts always
include several together.

signature:
= [
  /<chat_history>/i,
  /^### Task:/im,
  /\bJSON format:\s*\{/i,
  /\bfollow_?ups\b.*\barray of st...


id: constant:f7c8b820e1103140224b3942febbcd30
kind: constant
name: OPENWEBUI_IMAGE_CONTEXT_MARKERS
qualified_name: OPENWEBUI_IMAGE_CONTEXT_MARKERS
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
= [
  /<context>\s*The requested image has been (?:created|edited and created) by the system successfu...


id: constant:5e93e659eca808bc97b1d43de2009daa
kind: constant
name: IMAGE_EDIT_REGEXES
qualified_name: IMAGE_EDIT_REGEXES
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
= [
  /\b(?:edit|adjust|modify|change|update|alter|revise|retouch|fix)\b[\s\S]{0,120}\b(?:it|image|pic...


id: function:339ab42b3ff4e08349672a4d8cae8577
kind: function
name: buildConversationBody
qualified_name: buildConversationBody
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  parsed: ParsedMessages,
  modelSlug: string,
  parentMessageId: string,
  // When true, send as a regular (non-temporary) chat so the image_gen tool
  // is available. When false (default), use Temporary Chat to keep chats
  // out of the user's chatgpt.com history.
  forImageGen: boolean,
  continuation: ChatGptImageConversationContext | null = null
): Record<string, unknown>


id: interface:5a4c89d2c241475e08d7607116301a6d
kind: interface
name: ImageAssetPart
qualified_name: ImageAssetPart
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
A part inside `content.parts` for a `multimodal_text` content_type.
ChatGPT puts image references in a part with content_type "image_asset_pointer"
and an asset_pointer like "file-service://file-XXXX" (final) or
"sediment://..." (in-progress preview).


id: interface:72e809d9dbb95b5485d4257d0ba2cc53
kind: interface
name: ContentChunk
qualified_name: ContentChunk
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
─── Content extraction ─────────────────────────────────────────────────────
ChatGPT SSE chunks contain CUMULATIVE content (full text so far in `parts[0]`),
not deltas. Diff against the emitted length to produce incremental tokens —
same pattern perplexity-web.ts uses for markdown blocks (lines 386-397).


id: function:ff2e6d23359a9d989bb0a2aefc2f1f6c
kind: function
name: extractImagePointers
qualified_name: extractImagePointers
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: (parts: unknown[]): string[]
docstring:
Pull image asset pointers out of a multimodal_text parts array.
For text-only messages parts is `["text..."]` and this returns `[]`. For
`image_gen` tool output, parts looks like:
  [
    { content_type: "image_asset_pointer",
      asset_pointer: "file-service://file-abc..." or "sediment://..." }
  ]
We collect every asset_pointer seen so the caller can resolve them once
the stream terminates.


id: variable:b0f5c6bff8c1885bdd1087b74450db66
kind: variable
name: conversationId
qualified_name: conversationId
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = null
docstring:
ChatGPT may echo prior assistant turns at the start of the stream with
status: "finished_successfully" and full content, before sending the new
generation. If we emit those bytes downstream, streaming consumers see
the previous answer prepended to the new one (visible in Open WebUI as
run-on output across turns). Strategy: only emit deltas after we've seen
status === "in_progress" for the current message id (i.e., it's being
generated live in this stream). Echoes always arrive already finished
and never transition through in_progress, so they get suppressed. An
end-of-stream fallback handles the rare case where a real turn arrives
as a single already-finished event (instant/cached responses).


id: variable:bd1e04fc684368a81b9072e86e05885b
kind: variable
name: imageGenAsync
qualified_name: imageGenAsync
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = false
docstring:
True if we observed signals the assistant kicked off the async image_gen
tool (see ContentChunk.imageGenAsync). The actual image arrives later via
WebSocket / polling — caller handles that.


id: constant:c0324820d8704373563f5bfa8663b59c
kind: constant
name: msg
qualified_name: msg
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
= typeof event.error === "string"
          ? event.error
          : event.error.message || "ChatGPT ...


id: constant:030477ccffb80bfb8132aae262a6b77d
kind: constant
name: meta
qualified_name: meta
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
= (event as Record<string, unknown>).metadata as
        | Record<string, unknown>
        | undefined...


id: type_alias:6fa2dac3400f800a68879637e27cd3de
kind: type_alias
name: ImageResolver
qualified_name: ImageResolver
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
Resolves a ChatGPT asset_pointer to a downloadable URL, given the live
conversation_id (needed for sediment:// pointers). Returns null on failure
so the caller can decide whether to surface a placeholder or skip silently.


id: function:ca40c7fff89a6f9a8c90bf4d06546373
kind: function
name: resolveImagePointers
qualified_name: resolveImagePointers
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  pointers: ImagePointerRef[] | undefined,
  conversationId: string | null,
  resolver: ImageResolver | null,
  log?: { warn?: (tag: string, msg: string) => void } | null,
  fallbackParentMessageId?: string | null
): Promise<string[]>


id: function:2c082ae42be55d049b592c637b52a8c5
kind: function
name: buildStreamingResponse
qualified_name: buildStreamingResponse
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  eventStream: ReadableStream<Uint8Array>,
  model: string,
  cid: string,
  created: number,
  resolver: ImageResolver | null,
  // Optional poller for async image_gen — when ChatGPT processes the request
  // out-of-band ("Lots of people are creating images right now"), the SSE
  // stream finishes without an image_asset_pointer. The executor passes a
  // closure here that knows how to poll the conversation endpoint.
  pollAsyncImage: ((conversationId: string) => Promise<ImagePointerRef[]>) | null,
  log: { warn?: (tag: string, msg: string) => void } | null,
  signal?: AbortSignal | null
): ReadableStream<Uint8Array>


id: function:684f225cbb275bd09629f44673e9b51f
kind: function
name: buildNonStreamingResponse
qualified_name: buildNonStreamingResponse
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  eventStream: ReadableStream<Uint8Array>,
  model: string,
  cid: string,
  created: number,
  currentMsg: string,
  resolver: ImageResolver | null,
  pollAsyncImage: ((conversationId: string) => Promise<ImagePointerRef[]>) | null,
  log: { warn?: (tag: string, msg: string) => void } | null,
  signal?: AbortSignal | null
): Promise<Response>


id: function:d345fe1be9e0499bfe668035b994894e
kind: function
name: derivePublicBaseUrl
qualified_name: derivePublicBaseUrl
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
docstring:
Build the absolute base URL the client should use to fetch our cached
images at /v1/chatgpt-web/image/<id>. The most reliable value is an
explicit browser-facing origin because relay clients such as Open WebUI
often reach OmniRoute from a container while the user's browser needs a
LAN, tunnel, or reverse-proxy URL.

signature:
(
  clientHeaders?: Record<string, string> | null,
  log?: { debug?: (tag: string, msg: string) => void }
): string


id: constant:fecf05edd7ca4b0f962f7c30407d3ee2
kind: constant
name: FILE_SERVICE_PREFIX
qualified_name: FILE_SERVICE_PREFIX
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = "file-service://"
docstring:
─── Image asset resolution ────────────────────────────────────────────────
ChatGPT's image_gen tool emits `image_asset_pointer` parts whose
`asset_pointer` is one of:

file-service://file-XXXX        → resolved via /backend-api/files/{id}/download
sediment://file-XXXX            → resolved via /backend-api/conversation/{conv_id}/attachment/{id}/download

Both endpoints return JSON `{ download_url: "<azure-blob-sas-url>", ... }`.
The signed URL has a limited lifetime (typically a few hours), but that's
usually sufficient for the user to view the image in their UI right after
generation. Persistent storage can be layered on later if needed.


id: constant:0cb4959990ee879627ac69a40448240d
kind: constant
name: IMAGE_DOWNLOAD_MAX_BYTES
qualified_name: IMAGE_DOWNLOAD_MAX_BYTES
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = 8 * 1024 * 1024
docstring:
Download a chatgpt.com signed image URL and re-serve it from OmniRoute's
short-lived image cache. The URLs returned by /files/<id>/download and
/conversation/<cid>/attachment/<fid>/download point at chatgpt.com's
estuary endpoint, which 403s for any request without the user's session
cookie. Downstream clients (Open WebUI, OpenAI-compatible apps) won't
have those cookies, so we download once via the authenticated TLS client
and return a browser-fetchable OmniRoute URL.


id: function:3cf5f924153931b7211faecb9671a336
kind: function
name: imageUrlToCachedImageUrl
qualified_name: imageUrlToCachedImageUrl
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  signedUrl: string,
  ctx: ResolverContext,
  imageContext?: ChatGptImageConversationContext
): Promise<string | null>


id: function:feb210255d920c29878bf73a4c12b437
kind: function
name: registerWebSocket
qualified_name: registerWebSocket
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: (ctx: ResolverContext): Promise<string | null>
docstring:
Resolve the async image_gen result by registering a WebSocket with
chatgpt.com and listening for the image_asset_pointer.
Background: when chatgpt.com is busy ("Lots of people are creating images
right now") the image_gen tool defers — the initial SSE finishes with a
"Processing image..." placeholder and the real image arrives over a
WebSocket pubsub. (We checked: the conversation tree at
`/backend-api/conversation/{id}` is NOT updated when the image lands, so
polling that endpoint does nothing.)
Flow:
  1. POST /backend-api/register-websocket → { wss_url, expires_at, ... }
  2. Open the wss_url with the standard WebSocket client.
     Auth lives in the URL (signed access token), so we don't need the
     TLS-impersonation transport here.
  3. Each WS message is JSON like { type: "wss-message", data: { ...
     conversation event ... } }. The conversation event has the same
     shape as the SSE events from /backend-api/f/conversation.
  4. Watch for assistant messages with multimodal_text + image_asset_pointer
     OR a `message_stream_complete` for the conversation. Resolve when
     either pointer arrives or the timeout fires.


id: function:987b29ba3d68ee77cb6541c603ca0654
kind: function
name: waitForImageViaWebSocket
qualified_name: waitForImageViaWebSocket
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  wssUrl: string,
  conversationId: string,
  timeoutMs: number,
  ctx: ResolverContext
): Promise<WsWaitOutcome>


id: constant:86f736e8b2242fee7730a6059b8577f6
kind: constant
name: DEFAULT_ASYNC_IMAGE_TIMEOUT_MS
qualified_name: DEFAULT_ASYNC_IMAGE_TIMEOUT_MS
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = 180_000
docstring:
Default 3-minute wait for the async image_gen tool to produce an image
pointer over the celsius WebSocket. Tunable so deployments can stretch
during chatgpt.com queue-deep windows ("Lots of people are creating
images right now") without code changes.


id: function:93047d0a4f719ef03d5e54ddf25989e1
kind: function
name: pollForAsyncImage
qualified_name: pollForAsyncImage
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
(
  conversationId: string,
  ctx: ResolverContext,
  opts: { timeoutMs?: number } = {}
): Promise<ImagePointerRef[]>


id: method:fc15c3e1cc317c52b5d53d9372c336a3
kind: method
name: execute
qualified_name: ChatGptWebExecutor::execute
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature:
({
    model,
    body,
    stream,
    credentials,
    signal,
    log,
    onCredentialsRefreshed,
    clientHeaders,
  }: ExecuteInput)


id: constant:01b38be113de15d419ed15c93d3f4bb4
kind: constant
name: ENTITY_RE
qualified_name: ENTITY_RE
file_path: open-sse/executors/chatgpt-web.ts
language: typescript
signature: = /entity\["[^"]*","([^"]*)"[^\]]*\]/g
docstring:
Strip ChatGPT's internal entity markup. The browser renders these as proper
inline citations / chips via JS; for a plain text completion we just want
the human-readable form.
entity["city","Paris","capital of France"]  →  Paris
entity["…","value", …]                       →  value


id: constant:97b29dcbbfa66cacdce9ef42c07a572b
kind: constant
name: CLAUDE_USER_AGENT
qualified_name: CLAUDE_USER_AGENT
file_path: open-sse/executors/claude-web.ts
language: typescript
signature:
= "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0...


id: interface:0215c6f6484d62e4dda66f1bd2dd6001
kind: interface
name: ClaudeWebCredentials
qualified_name: ClaudeWebCredentials
file_path: open-sse/executors/claude-web.ts
language: typescript
docstring:
─── Types ──────────────────────────────────────────────────────────────────
Extended credentials to include organization and conversation context


id: function:3fe87ca8ef2659891fc30ff15a4eccde
kind: function
name: getBrowserHeaders
qualified_name: getBrowserHeaders
file_path: open-sse/executors/claude-web.ts
language: typescript
signature: (deviceId?: string): Record<string, string>
docstring:
─── Helper Functions ───────────────────────────────────────────────────────
Build browser-like headers for Claude Web API


id: function:e4aff2e858f9a038ed26c8c6c7c2d7e5
kind: function
name: verifyCookieValidity
qualified_name: verifyCookieValidity
file_path: open-sse/executors/claude-web.ts
language: typescript
docstring:
Verify session is still valid by checking if the organizations endpoint
returns a successful response. Claude's API does not have a /api/auth/session
endpoint (unlike ChatGPT), so we use /api/organizations which requires a
valid session cookie and returns 200 only with valid credentials.

signature:
(
  cookieHeader: string,
  deviceId: string | undefined,
  signal?: AbortSignal
): Promise<boolean>


id: function:7cdfa094f1ad3e5db7b43f589465ad5b
kind: function
name: getOrganizationId
qualified_name: getOrganizationId
file_path: open-sse/executors/claude-web.ts
language: typescript
docstring: Get user's organization ID from session
signature:
(
  cookieHeader: string,
  deviceId: string | undefined,
  signal?: AbortSignal
): Promise<string | null>


id: function:8ac00505354eb1fea63488ad9233f332
kind: function
name: resolveAccountUUID
qualified_name: resolveAccountUUID
file_path: open-sse/executors/claudeIdentity.ts
language: typescript
signature:
(
  providerSpecificData: Record<string, unknown> | undefined,
  seed: string,
  accessToken?: string
): string


id: function:6bab45ea5cf4f809c9858ba567a9df73
kind: function
name: parseUpstreamMetadataUserId
qualified_name: parseUpstreamMetadataUserId
file_path: open-sse/executors/claudeIdentity.ts
language: typescript
signature:
(
  body: Record<string, unknown> | null | undefined
): { device_id: string; account_uuid: string; session_id: string } | null


id: constant:bfbb0025289dbd9cabcdac77e2fea183
kind: constant
name: HEAVY_AGENT_BETA_MODEL_PREFIXES
qualified_name: HEAVY_AGENT_BETA_MODEL_PREFIXES
file_path: open-sse/executors/claudeIdentity.ts
language: typescript
signature: = ["claude-opus", "claude-sonnet"]
docstring:
---------- anthropic-beta selector --------------------------------------
Models that support the heavy-agent beta tier (effort, advanced-tool-use).
Only Opus/Sonnet are eligible — Haiku with OAuth authentication rejects
heavy agent flags (issue #2454). Matches real Claude Code captures.


id: constant:55465709f2f337ea8a9193bd875fdc84
kind: constant
name: CONTEXT_1M_BETA_MODEL_PREFIXES
qualified_name: CONTEXT_1M_BETA_MODEL_PREFIXES
file_path: open-sse/executors/claudeIdentity.ts
language: typescript
signature: = ["claude-opus"]
docstring:
Models that support the context-1m beta tier. Only Opus is eligible;
Sonnet trips long-context credit gates under OAuth full-agent traffic.


id: import:736ca240e8ad4c33623e6405fb1fbf76
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeUpstreamExtraHeaders,
  mergeAbortSignals,
  type ProviderCredentials,
} from "./base.ts";


id: constant:5f3c32e3e0874e1fc5871c2146786af5
kind: constant
name: MCP_RESERVED_PREFIX_RE
qualified_name: MCP_RESERVED_PREFIX_RE
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature: = /^mcp_(?=[^_])/
docstring:
Anthropic's reserved tool-name namespace: ^mcp_[^_].* triggers their
server-side MCP connector billing gate, returning a misleading
"out of extra usage" 400. Two-underscore (mcp__X) and capitalized
(Mcp_X) variants pass cleanly.


id: function:eb28a5d33af3219e81cc37e4c7dec57a
kind: function
name: applyMcpToolNameRewrite
qualified_name: applyMcpToolNameRewrite
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature: (body: Record<string, unknown>): Map<string, string>
docstring:
Rewrite ^mcp_[^_] tool names on a body destined for Anthropic's
/v1/messages. Returns a reverse map (rewritten → original) that the SSE
response stream uses to restore the client's original names on tool_use
blocks coming back.
Non-mutating: replaces nested array elements with cloned objects rather
than mutating in place, so the caller's input body is not affected. The
outer `body` reference itself is the cloned `transformed` object from
`transformRequest` — we mutate its top-level `tools`, `messages`, and
`tool_choice` properties to point at the new clones.


id: method:e3f503660894df69d8c2000ff215d1ac
kind: method
name: buildUrl
qualified_name: CliproxyapiExecutor::buildUrl
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature:
(
    _model: string,
    _stream: boolean,
    _urlIndex = 0,
    _credentials: ProviderCredentials | null = null
  ): string


id: method:e779d2851ee11975fc6cc417445b3035
kind: method
name: isAnthropicShape
qualified_name: CliproxyapiExecutor::isAnthropicShape
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature: (body: unknown): boolean
visibility: private
docstring:
Returns true when the body matches the Anthropic Messages wire shape.
chatCore detects target=claude when the request comes from a Claude-source
client (`/v1/messages`, Anthropic-version header, claude/* model). In that
case no openai translation is applied and the executor sees the original
Anthropic body: top-level `system` as an array of content blocks, and
`messages[].content` as arrays. Routing those bodies to CPA's
/v1/chat/completions causes CPA to emit OpenAI-style SSE chunks, which
Anthropic SDK clients (Capy, claude-cli, etc.) cannot parse — the result
looks like a 200 server-side with "0 chunks received" client-side.
CPA exposes /v1/messages natively (claude executor with uTLS spoof,
billing header, CCH signing, etc.) and emits proper Anthropic SSE:
`event: message_start`, `content_block_delta`, etc.


id: method:45aa489f6006a04666f775331e16c6d3
kind: method
name: transformRequest
qualified_name: CliproxyapiExecutor::transformRequest
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature:
(
    model: string,
    body: unknown,
    _stream: boolean,
    _credentials: ProviderCredentials | null
  ): unknown


id: method:96f4ff8a321638ebb345cb092a27abdb
kind: method
name: execute
qualified_name: CliproxyapiExecutor::execute
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature:
(input: {
    model: string;
    body: unknown;
    stream: boolean;
    credentials: ProviderCredentials;
    signal?: AbortSignal | null;
    log?: any;
    upstreamExtraHeaders?: Record<string, string> | null;
  })


id: method:5f1bf7d63615dcb295acb91101680373
kind: method
name: healthCheck
qualified_name: CliproxyapiExecutor::healthCheck
file_path: open-sse/executors/cliproxyapi.ts
language: typescript
signature: (): Promise<{ ok: boolean; latencyMs: number; error?: string }>
docstring:
Health check — verifies CLIProxyAPI is reachable.
CPA 6.x doesn't expose a /health endpoint; previously we hit /health
and got 404, which made the dashboard report "CLIProxyAPI not
detected" even when the service was up and successfully serving
/v1/messages. Probe /v1/models instead (returns 200 with the
advertised model list), which is the closest thing CPA has to a
liveness probe and works on every CPA version we've tested.


id: method:adf22b3b766fdd984745f42969021e25
kind: method
name: buildUrl
qualified_name: CloudflareAIExecutor::buildUrl
file_path: open-sse/executors/cloudflare-ai.ts
language: typescript
signature:
(
    _model: string,
    _stream: boolean,
    _urlIndex = 0,
    credentials: CloudflareCredentials = null
  ): string


id: method:0d687c2c4ecae0e34bbe456d058e20f6
kind: method
name: transformRequest
qualified_name: CloudflareAIExecutor::transformRequest
file_path: open-sse/executors/cloudflare-ai.ts
language: typescript
signature:
(
    _model: string,
    body: Record<string, unknown>,
    _stream: boolean,
    _credentials: CloudflareCredentials
  ): Record<string, unknown>


id: import:c95db286b02fd166a8d3b71cfb93cf64
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/codex.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeUpstreamExtraHeaders,
  setUserAgentHeader,
  type ExecutorLog,
  type ExecuteInput,
  type ProviderCredentials,
} from "./base.ts";


id: import:f663e294a1c0b958b965c931e046ce69
kind: import
name: ../config/codexInstructions.ts
qualified_name: ../config/codexInstructions.ts
file_path: open-sse/executors/codex.ts
language: typescript
signature:
import {
  CODEX_CHAT_DEFAULT_INSTRUCTIONS,
  CODEX_DEFAULT_INSTRUCTIONS,
} from "../config/codexInstructions.ts";


id: import:9421d1350d15f06655acbb66fc164f41
kind: import
name: ../config/codexClient.ts
qualified_name: ../config/codexClient.ts
file_path: open-sse/executors/codex.ts
language: typescript
signature:
import {
  getCodexClientVersion,
  getCodexUserAgent,
  normalizeCodexSessionId,
} from "../config/codexClient.ts";


id: import:aa8647b9360d1a780a2a2ebf40a546bc
kind: import
name: ../config/codexIdentity.ts
qualified_name: ../config/codexIdentity.ts
file_path: open-sse/executors/codex.ts
language: typescript
signature:
import {
  applyCodexClientIdentityHeaders,
  applyCodexClientMetadata,
  createCodexClientIdentity,
  type CodexClientIdentity,
} from "../config/codexIdentity.ts";


id: constant:308c85fb74a4019e478a617d3743e2d4
kind: constant
name: _wreqRequire
qualified_name: _wreqRequire
file_path: open-sse/executors/codex.ts
language: typescript
signature: = createRequire(import.meta.url)
docstring:
─── wreq-js lazy loader ───────────────────────────────────────────────────
wreq-js is a Rust-native module that requires platform-specific .node binaries.
Loading it eagerly crashes the server when the binary is missing (pnpm, Docker
Alpine, unsupported architectures). We lazy-load with try/catch to gracefully
fall back to HTTP transport when the WebSocket transport is unavailable.


id: constant:20d02120d2457c6e356affb2c30d856d
kind: constant
name: CODEX_SCOPE_PATTERNS
qualified_name: CODEX_SCOPE_PATTERNS
file_path: open-sse/executors/codex.ts
language: typescript
docstring:
─── T09: Codex vs Spark Scope-Aware Rate Limiting ────────────────────────
Codex has two independent quota pools: "codex" (standard) and "spark" (premium).
Exhausting one should NOT block requests to the other.
Ref: sub2api PR #1129 (feat(openai): split codex spark rate limiting from codex)
Maps model name substrings to their rate-limit scope.
Checked in order — first match wins.

signature:
= [
  { pattern: "codex-spark", scope: "spark" },
  { pattern: "spark", scope: "spark" },
  { pattern:...


id: function:9a713f5c938b47ae088e5cd1a2c381f6
kind: function
name: getCodexDualWindowCooldownMs
qualified_name: getCodexDualWindowCooldownMs
file_path: open-sse/executors/codex.ts
language: typescript
signature:
(
  quota: CodexQuotaSnapshot,
  threshold = 0.95
): { cooldownMs: number; window: "7d" | "5h" | "none" }


id: function:d0825256039e6b3ffd5bfb95ee7fa406
kind: function
name: convertSystemToDeveloperRole
qualified_name: convertSystemToDeveloperRole
file_path: open-sse/executors/codex.ts
language: typescript
signature: (body: Record<string, unknown>): void
docstring:
Convert role=system messages in `input` to role=developer.
GPT-5 models support the `developer` role in input, but reject `system`.
This keeps the content inside
the `input` array where it benefits from OpenAI's automatic prompt caching.
OpenAI's prompt caching matches on the serialized prefix of the `input` array
(+ tools). The `instructions` field is NOT included in the cache key for
GPT-5 models. Moving system prompts from `input` to `instructions` therefore
removes them from the cacheable prefix, resulting in 0% cache hit rates.
Ref: https://community.openai.com/t/caching-is-borked-for-gpt-5-models/1359574
Ref: https://community.openai.com/t/no-caching-with-model-responses/1338627


id: function:7a801bd4a6575e814a1edcf5a2894f23
kind: function
name: stripStoredItemReferences
qualified_name: stripStoredItemReferences
file_path: open-sse/executors/codex.ts
language: typescript
signature: (body: Record<string, unknown>): void
docstring:
Strip server-generated item IDs from the input array.
The Codex /codex/responses endpoint does not persist response items even when
store=true is sent. When proxy clients (e.g. OpenClaw) include response items
from previous turns in the input array, those items carry server-assigned IDs
(prefixed with "rs_", "fc_", "resp_", "msg_"). The Codex backend tries to
validate these IDs against its persistence store and returns 404 when the items
are not found (because store was effectively false).
This function:
  1. Removes bare string references ("rs_abc123") from the input array
  2. Removes object items with type "item_reference" (explicit stored-item refs)
  3. Strips the "id" field from any object in input whose id matches a
     server-generated prefix (rs_, fc_, resp_, msg_) — so the content is
     preserved but the backend won't try to look it up


id: constant:67fee8f9a80888981bc8278ce102debc
kind: constant
name: CODEX_HOSTED_TOOL_TYPES
qualified_name: CODEX_HOSTED_TOOL_TYPES
file_path: open-sse/executors/codex.ts
language: typescript
docstring:
Responses-API hosted tool types that OpenAI/Codex executes server-side.
These arrive shaped as `{ type, ...params }` with no `function` object and no `name` —
e.g. Codex CLI injects `{ type: "image_generation", output_format: "png" }` or
`{ type: "namespace", name: "mcp__atlassian__", tools: [...] }` for MCP tool groups.
Keep them through `normalizeCodexTools` so upstream can execute them.

signature:
= new Set([
  "image_generation",
  "web_search",
  "web_search_preview",
  "file_search",
  "computer...


id: constant:b57c0254b4effd3bed7ea58fb8a94151
kind: constant
name: MAX_EFFORT_BY_MODEL
qualified_name: MAX_EFFORT_BY_MODEL
file_path: open-sse/executors/codex.ts
language: typescript
docstring:
Maximum reasoning effort allowed per Codex model.
Models not listed here default to "xhigh" (unrestricted).
Update this table when Codex releases new models with different caps.

signature:
= {
  "gpt-5.3-codex": "xhigh",
  "gpt-5.2-codex": "xhigh",
  "gpt-5.1-codex-max": "xhigh",
  "gpt-5-m...


id: function:7de61dbf1a02ad75efd2d9c4abea234a
kind: function
name: clampEffort
qualified_name: clampEffort
file_path: open-sse/executors/codex.ts
language: typescript
signature: (model: string, requested: string): string
docstring:
Clamp reasoning effort to the model's maximum allowed level.
Returns the original value if within limits, or the cap if it exceeds it.


id: method:f7bf56a58bcd6ea233f2c7390080cc89
kind: method
name: buildHeaders
qualified_name: CodexExecutor::buildHeaders
file_path: open-sse/executors/codex.ts
language: typescript
signature: (credentials: ProviderCredentials, stream = true)
docstring:
Codex Responses endpoint is SSE-first.
Always request event-stream from upstream, even when client requested stream=false.
Includes chatgpt-account-id header for strict workspace binding.


id: method:71c11ddbcc63b67c3d72017c7ee70a54
kind: method
name: getPromptCacheSessionId
qualified_name: CodexExecutor::getPromptCacheSessionId
file_path: open-sse/executors/codex.ts
language: typescript
visibility: private
docstring:
Derive a stable session ID for prompt cache affinity.
Priority: per-conversation session_id/conversation_id from request body → workspaceId.
The official Codex client uses conversation_id (a unique UUID per session), NOT
the account-wide workspaceId. Using workspaceId caps cache hit-rate at ~49%
because all conversations share the same cache partition. (#1643)
Ref: openai/codex core/src/client.rs line 853

signature:
(
    credentials: ProviderCredentials | null | undefined,
    body: Record<string, unknown> | null
  ): string | null


id: method:152237192b9b1d5b07299263e6a4d228
kind: method
name: refreshCredentials
qualified_name: CodexExecutor::refreshCredentials
file_path: open-sse/executors/codex.ts
language: typescript
signature: (credentials: ProviderCredentials, log?: ExecutorLog | null)
docstring:
Refresh Codex OAuth credentials when a 401 is received.
OpenAI uses rotating (one-time-use) refresh tokens — if the token was already
consumed by a concurrent refresh, this returns null to signal re-auth is needed.
Fixes #251: After a server restart/upgrade, previously cached access tokens may
have expired or become invalid. chatCore.ts calls this on 401; previously the
base class returned null causing the request to fail instead of refreshing.


id: method:d95f636d4467d68c53ff7d5cb2cbcef6
kind: method
name: transformRequest
qualified_name: CodexExecutor::transformRequest
file_path: open-sse/executors/codex.ts
language: typescript
docstring: Transform request before sending - inject default instructions if missing
signature:
(
    model: string,
    bodyInput: unknown,
    stream: boolean,
    credentials: ProviderCredentials
  )


id: constant:2d0f4f14d4a67a2fa05fb206646e25e3
kind: constant
name: COPILOT_USER_AGENT
qualified_name: COPILOT_USER_AGENT
file_path: open-sse/executors/copilot-web.ts
language: typescript
signature:
= "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0...


id: constant:e2fdfd7c0093c543c7180e787529516b
kind: constant
name: MODEL_MODE_MAP
qualified_name: MODEL_MODE_MAP
file_path: open-sse/executors/copilot-web.ts
language: typescript
docstring: Model mapping: OmniRoute model ID → Copilot mode
signature:
= {
  copilot: "chat",
  "copilot-chat": "chat",
  "gpt-4o": "chat",
  "gpt-4": "chat",
  "copilot-thi...


id: constant:9fc4de80994b265cf4eef406e89100d2
kind: constant
name: MAX_HASHCASH_DIFFICULTY
qualified_name: MAX_HASHCASH_DIFFICULTY
file_path: open-sse/executors/copilot-web.ts
language: typescript
signature: = 8
docstring:
Hashcash difficulty cap. Upstream supplies `difficulty`, so we clamp it to
prevent a malicious/buggy server from forcing huge prefix allocations or
effectively infinite work. 8 hex zeros = 2^32 expected iterations, already
far beyond the ~10M iteration budget below.


id: method:2c1ae7dd272bdcd02511ba28cd2b8551
kind: method
name: wsChat
qualified_name: CopilotWebExecutor::wsChat
file_path: open-sse/executors/copilot-web.ts
language: typescript
docstring: Send a message via WebSocket and collect the streamed response.
visibility: private
signature:
(
    conversationId: string,
    prompt: string,
    mode: string,
    accessToken?: string,
    signal?: AbortSignal
  ): Promise<ReadableStream<Uint8Array>>


id: method:75b10de19f1b51aadd861bbd32261850
kind: method
name: execute
qualified_name: CopilotWebExecutor::execute
file_path: open-sse/executors/copilot-web.ts
language: typescript
docstring: Main execute method — translates OpenAI format to Copilot WebSocket protocol.
signature:
(input: ExecuteInput): Promise<{
    response: Response;
    url: string;
    headers: Record<string, string>;
    transformedBody: unknown;
  }>


id: import:00f4b6dade8fee3187c3e7db477e7f83
kind: import
name: ../utils/cursorAgentProtobuf.ts
qualified_name: ../utils/cursorAgentProtobuf.ts
file_path: open-sse/executors/cursor.ts
language: typescript
signature:
import {
  buildAgentRequestBody,
  decodeAgentServerMessage,
  decodeExecServerEvent,
  decodeKvServerEvent,
  encodeRequestContextResponse,
  encodeKvGetBlobResult,
  encodeKvSetBlobResult,
  encodeExecReadRejected,
  encodeExecWriteRejected,
  encodeExecDeleteRejected,
  encodeExecLsRejected,
  encodeExecShellRejected,
  encodeExecBackgroundShellSpawnRejected,
  encodeExecGrepError,
  encodeExecFetchError,
  encodeExecWriteShellStdinError,
  encodeExecDiagnosticsResult,
  flattenMessages,
  openAIToolsToMcpDefs,
  type ChatMessage,
  type ExecServerEvent,
  type McpToolDefinition,
  type OpenAITool,
} from "../utils/cursorAgentProtobuf.ts";


id: import:e088a8ed11e6d03e58840cf00dbfb404
kind: import
name: ../utils/usageTracking.ts
qualified_name: ../utils/usageTracking.ts
file_path: open-sse/executors/cursor.ts
language: typescript
signature:
import {
  estimateInputTokens,
  estimateOutputTokens,
  addBufferToUsage,
} from "../utils/usageTracking.ts";


id: constant:00850028b3b7c53339457482fbdb079e
kind: constant
name: BUILTIN_TOOL_REJECT_REASON
qualified_name: BUILTIN_TOOL_REJECT_REASON
file_path: open-sse/executors/cursor.ts
language: typescript
signature: = "Tool not available in this environment. Use the MCP tools provided instead."
docstring:
Reject reason text aligned with kaitranntt/CLIProxyAPIPlus — proven to
keep cursor's model from retrying the same built-in tool indefinitely.
The model adapts and either answers from context or uses declared MCP tools.


id: function:9e5da71d07464fb71cf0df8759dc76d7
kind: function
name: buildExecRejection
qualified_name: buildExecRejection
file_path: open-sse/executors/cursor.ts
language: typescript
signature: (event: ExecServerEvent): Buffer | null
docstring:
Build the ExecClientMessage frame that responds to a built-in tool request.
Returns null for the request_context handshake (caller handles separately
to inject MCP tools in Phase 3) and for exec_mcp (model is invoking a
declared MCP tool — Phase 5 surfaces this as an OpenAI tool_calls delta).


id: constant:117cc4d8a50dc858b6b7abd20f312024
kind: constant
name: CURSOR_DEBUG
qualified_name: CURSOR_DEBUG
file_path: open-sse/executors/cursor.ts
language: typescript
signature: = process.env.CURSOR_DEBUG === "1" || process.env.CURSOR_STREAM_DEBUG === "1"
docstring:
Phase 10: CURSOR_DEBUG=1 enables verbose streaming debug logs (decoded
frame summaries, exec router dispatches, session lifecycle events).
CURSOR_STREAM_DEBUG is kept as a backward-compatible alias.


id: constant:d0ab525dad1885d484fbe5f08cb1d0c2
kind: constant
name: CURSOR_STREAM_TIMEOUT_MS
qualified_name: CURSOR_STREAM_TIMEOUT_MS
file_path: open-sse/executors/cursor.ts
language: typescript
signature: = parseInt(process.env.CURSOR_STREAM_TIMEOUT_MS || "300000", 10)
docstring:
Phase 8: max wall-clock time before we give up on the upstream and abort
the stream. Cursor's longest-observed plain chat takes ~90s; tool-using
turns can be longer. Five minutes is generous but bounded.


id: function:fef92a34dcab8ed351b55957478e3e4c
kind: function
name: processFrame
qualified_name: processFrame
file_path: open-sse/executors/cursor.ts
language: typescript
signature:
(
  payload: Buffer,
  ctx: StreamCtx,
  ackedExecIds: Set<string>,
  opts: {
    h2Req?: import("http2").ClientHttp2Stream;
    mcpTools?: McpToolDefinition[];
    blobStore?: Map<string, Buffer>;
  } = {}
): void


id: method:ac0aacc7834de848a55b0c01368a4ea4
kind: method
name: buildRequest
qualified_name: CursorExecutor::buildRequest
file_path: open-sse/executors/cursor.ts
language: typescript
visibility: private
docstring:
Build the request body and return it alongside the request-scoped
blobStore. cursor's models (auto, claude-*, gpt-*) don't reliably
follow system-role content delivered via the KV blob channel — even
though the blob is requested and our reply is accepted, the model
proceeds without applying the prompt.
As a pragmatic workaround we prepend the system content into the
UserMessage text (the pre-Phase-7 behavior). The KV-blob handshake
machinery is still in place for any future schema where cursor honors
root_prompt_messages_json semantically — verified end-to-end with
wire-tap captures.

signature:
(
    model: string,
    body: { messages?: ChatMessage[]; tools?: unknown; conversation_id?: string }
  ): { body: Uint8Array; blobStore: Map<string, Buffer> }


id: method:dd2a63de9b13933ec6c5b0ffb30fc99f
kind: method
name: openH2
qualified_name: CursorExecutor::openH2
file_path: open-sse/executors/cursor.ts
language: typescript
visibility: private
docstring:
─── h2 lifecycle: open + drive (Phase 4 streaming refactor) ─────────────

openH2 establishes the bidirectional stream and waits for the response
headers (so we can decide whether to commit to a streaming SSE Response
or return an error). driveH2 then consumes data events incrementally,
dispatching frames through processFrame so SSE chunks land on the
ReadableStream controller as the upstream produces them.

The fetch fallback (cloud envs without http2) preserves the legacy
buffer-then-decode behavior — Connect-RPC bidirectional ack-on-same-stream
can't run over a one-shot fetch anyway.

signature:
(
    url: string,
    headers: Record<string, string>,
    body: Uint8Array,
    signal?: AbortSignal
  ): Promise<{
    status: number;
    headers: Record<string, string | number>;
    client: import("http2").ClientHttp2Session;
    req: import("http2").ClientHttp2Stream;
    initialBytes: Buffer;
    consumeError: () => Promise<Buffer>;
  }>


id: method:8a1fa59c7b11a2eaedbc074b45e3ed16
kind: method
name: driveH2
qualified_name: CursorExecutor::driveH2
file_path: open-sse/executors/cursor.ts
language: typescript
visibility: private
docstring:
Drive an open h2 stream to completion. processFrame populates ctx as
each Connect-RPC frame is decoded; the loop closes when ctx.endReason
is set (turn_ended, kv_after_text, server_end) or the stream errors.
Phase 8 will add a max-stream safety timeout here.

signature:
(
    h2: {
      req: import("http2").ClientHttp2Stream;
      client: import("http2").ClientHttp2Session;
      initialBytes: Buffer;
    },
    ctx: StreamCtx,
    mcpTools: McpToolDefinition[] | undefined,
    blobStore: Map<string, Buffer> | undefined,
    signal?: AbortSignal
  ): Promise<void>


id: method:d3f0eb26aa8d0047de32c22fd971d286
kind: method
name: finalizeSseStream
qualified_name: CursorExecutor::finalizeSseStream
file_path: open-sse/executors/cursor.ts
language: typescript
signature: (ctx: StreamCtx, body: { messages?: ChatMessage[] })
visibility: private
docstring:
Emit the trailing SSE chunks (finish + usage + DONE) onto an already-open
stream. Called once driveH2 returns and ctx.endReason is set. The
mid-stream-error path emits an error chunk instead.


id: method:41c74a5882faf34756f97b5632011f72
kind: method
name: buildResponseFromCtx
qualified_name: CursorExecutor::buildResponseFromCtx
file_path: open-sse/executors/cursor.ts
language: typescript
signature: (ctx: StreamCtx, body: { messages?: ChatMessage[] }): Response
visibility: private
docstring:
Build a non-streaming chat.completion JSON Response from a fully-driven
StreamCtx. The streaming path emits chunks live via finalizeSseStream
and never calls this method.


id: constant:58713ba5abf33ce57c7610b56d2ebe8d
kind: constant
name: FAKE_HEADERS
qualified_name: FAKE_HEADERS
file_path: open-sse/executors/deepseek-web.ts
language: typescript
signature:
= {
  Accept: "*/*",
  "Accept-Encoding": "gzip, deflate, br, zstd",
  "Accept-Language": "en-US,en;q=...


id: function:739e31c9151c0c76ec2a286769fbccd0
kind: function
name: resolveModelOptions
qualified_name: resolveModelOptions
file_path: open-sse/executors/deepseek-web.ts
language: typescript
signature:
(
  model?: string,
  bodyObj?: Record<string, unknown>
): {
  modelType: string;
  thinkingEnabled: boolean;
  searchEnabled: boolean;
}


id: function:ba5f81355ba6800c469eb1bc7635bded
kind: function
name: acquireAccessToken
qualified_name: acquireAccessToken
file_path: open-sse/executors/deepseek-web.ts
language: typescript
docstring: ── DeepSeek API calls (Bearer token auth, like Chat2API) ───────────────
signature:
(
  userToken: string,
  signal?: AbortSignal | null,
  log?: ExecuteInput["log"]
): Promise<string>


id: function:d23523301119ad340b5d064b1c1d69cc
kind: function
name: createSession
qualified_name: createSession
file_path: open-sse/executors/deepseek-web.ts
language: typescript
signature:
(
  accessToken: string,
  connectionId: string | undefined,
  signal?: AbortSignal | null
): Promise<string>


id: import:a06ba8eb82e58804c43f759ad8ecbcca
kind: import
name: ../services/claudeCodeCompatible.ts
qualified_name: ../services/claudeCodeCompatible.ts
file_path: open-sse/executors/default.ts
language: typescript
signature:
import {
  buildClaudeCodeCompatibleHeaders,
  CLAUDE_CODE_COMPATIBLE_DEFAULT_CHAT_PATH,
  joinClaudeCodeCompatibleUrl,
} from "../services/claudeCodeCompatible.ts";


id: import:0cd724a47d7d02620c8b18185ccffe1a
kind: import
name: ../services/provider.ts
qualified_name: ../services/provider.ts
file_path: open-sse/executors/default.ts
language: typescript
signature:
import {
  detectFormat,
  getOpenAICompatibleType,
  getTargetFormat,
  isClaudeCodeCompatible,
} from "../services/provider.ts";


id: method:9222798ce77c9f972c91375e3dea89d0
kind: method
name: transformRequest
qualified_name: DefaultExecutor::transformRequest
file_path: open-sse/executors/default.ts
language: typescript
signature: (model, body, stream, credentials)
docstring:
For compatible providers, the model name is already clean by the time
it reaches the executor (chatCore sets body.model = modelInfo.model,
which is the parsed model ID without internal routing prefixes).
Models may legitimately contain "/" as part of their ID (e.g. "zai-org/GLM-5-FP8",
"org/model-name") — we must NOT strip path segments. (Fix #493)


id: method:fa7bcfa5fcd79d6cae78aa4982d923a2
kind: method
name: refreshCredentials
qualified_name: DefaultExecutor::refreshCredentials
file_path: open-sse/executors/default.ts
language: typescript
signature: (credentials, log)
docstring:
Refresh credentials via the centralized tokenRefresh service.
Delegates to getAccessToken() which handles all providers with
race-condition protection (deduplication via refreshPromiseCache).


id: method:ba800ec959bf2f86df0680b5a9d68bc3
kind: method
name: execute
qualified_name: DevinCliExecutor::execute
file_path: open-sse/executors/devin-cli.ts
language: typescript
signature:
({ model, body, stream: _stream, credentials, signal, log }: ExecuteInput): Promise<{
    response: Response;
    url: string;
    headers: Record<string, string>;
    transformedBody: unknown;
  }>


id: function:dd3cb461ac5124a6b7fad0d8f7faa08a
kind: function
name: extractResultText
qualified_name: extractResultText
file_path: open-sse/executors/devin-cli.ts
language: typescript
signature: (result: Record<string, unknown>): string
docstring:
─── Helpers ─────────────────────────────────────────────────────────────────
Try to extract text from a final ACP session/prompt result object.


id: constant:ddfd7f598bd10d60db35702328c97acc
kind: constant
name: LOAD_CODE_ASSIST_METADATA
qualified_name: LOAD_CODE_ASSIST_METADATA
file_path: open-sse/executors/gemini-cli.ts
language: typescript
signature:
= Object.freeze({
  ideType: "IDE_UNSPECIFIED",
  platform: "PLATFORM_UNSPECIFIED",
  pluginType: "GEM...


id: method:16afd5e06e2fd10c445f6cdf5aa8f2c0
kind: method
name: buildHeaders
qualified_name: GeminiCLIExecutor::buildHeaders
file_path: open-sse/executors/gemini-cli.ts
language: typescript
signature:
(
    credentials,
    stream = true,
    clientHeaders?: Record<string, string> | null,
    model?: string
  )


id: method:79f8db00b7072ece67722da7336ee92c
kind: method
name: onboardManagedProject
qualified_name: GeminiCLIExecutor::onboardManagedProject
file_path: open-sse/executors/gemini-cli.ts
language: typescript
signature:
(
    accessToken: string,
    tierId = DEFAULT_ONBOARD_TIER,
    options: OnboardOptions = {},
    model = "unknown"
  ): Promise<string | null>


id: method:b7eb905c7a31b47c0c359f7ddfa7741f
kind: method
name: refreshProject
qualified_name: GeminiCLIExecutor::refreshProject
file_path: open-sse/executors/gemini-cli.ts
language: typescript
signature: (accessToken: string, model = "unknown"): Promise<string | null>
docstring:
Fetch the current cloudaicompanionProject via loadCodeAssist API.
Native Gemini CLI refreshes this every 30 seconds — OmniRoute stores it once
at OAuth connection time, so it goes stale. This method keeps it fresh.


id: function:70a45d3c46ca74e8bbb2036fd4a72aac
kind: function
name: parseCookies
qualified_name: parseCookies
file_path: open-sse/executors/gemini-web.ts
language: typescript
signature: (raw: string): Array<{ name: string; value: string }>
docstring:
Parse cookie string, stripping attributes (Path, Domain, Expires, etc.)
Input: full browser cookie string or just "name=value; name2=value2"
Output: array of { name, value } pairs


id: function:245fb2c8b5d0d1bd3904792329960026
kind: function
name: parseStreamResponse
qualified_name: parseStreamResponse
file_path: open-sse/executors/gemini-web.ts
language: typescript
signature: (raw: string): string
docstring:
Parse Gemini StreamGenerate response text.
Response format:
  )]}'
  <length>
  [["wrb.fr", null, "<JSON string>"]]
  <length>
  [["wrb.fr", null, "<JSON string>"]]
The JSON string contains nested array: inner[4][0][1] = ["text chunks"]
We return text from the first wrb.fr line that contains content.


id: import:855a2a5f1cf75b118ff02a6aa9e127f7
kind: import
name: ../config/providerHeaderProfiles.ts
qualified_name: ../config/providerHeaderProfiles.ts
file_path: open-sse/executors/github.ts
language: typescript
signature:
import {
  getGitHubCopilotChatHeaders,
  getGitHubCopilotRefreshHeaders,
} from "../config/providerHeaderProfiles.ts";


id: method:ed3b14c60fe003649f0b8809df9f29b1
kind: method
name: buildHeaders
qualified_name: GithubExecutor::buildHeaders
file_path: open-sse/executors/github.ts
language: typescript
signature:
(
    credentials: ProviderCredentials,
    stream = true,
    clientHeaders?: Record<string, string> | null
  ): Record<string, string>


id: import:0a2204ff6a7bc2f3067e18f38684625a
kind: import
name: @/lib/oauth/gitlab
qualified_name: @/lib/oauth/gitlab
file_path: open-sse/executors/gitlab.ts
language: typescript
signature:
import {
  buildGitLabDirectGatewayUrl,
  buildGitLabOAuthEndpoints,
  getCachedGitLabDirectAccess,
  isGitLabDirectAccessDisabled,
  parseGitLabDirectAccessDetails,
  resolveGitLabOAuthBaseUrl,
  type GitLabDirectAccessDetails,
} from "@/lib/oauth/gitlab";


id: function:024909e60662fe101f5a05e54c78c03f
kind: function
name: mergeCredentials
qualified_name: mergeCredentials
file_path: open-sse/executors/gitlab.ts
language: typescript
signature:
(
  current: ProviderCredentials,
  patch: Partial<ProviderCredentials> | null | undefined
): ProviderCredentials


id: function:6a0375ccadc582b5581998f4699db86d
kind: function
name: persistGitLabDirectAccessCache
qualified_name: persistGitLabDirectAccessCache
file_path: open-sse/executors/gitlab.ts
language: typescript
signature:
(
  input: ExecuteInput,
  credentials: ProviderCredentials,
  root: string,
  directAccess: GitLabDirectAccessDetails
)


id: method:5ddba77367b4e5a1f5ca25a0d265d4e4
kind: method
name: buildUrl
qualified_name: GitlabExecutor::buildUrl
file_path: open-sse/executors/gitlab.ts
language: typescript
signature:
(
    _model: string,
    _stream: boolean,
    _urlIndex = 0,
    credentials: ExecuteInput["credentials"] | null = null
  ): string


id: method:dc736d4d046c83405f94883a5432a8bd
kind: method
name: transformRequest
qualified_name: GitlabExecutor::transformRequest
file_path: open-sse/executors/gitlab.ts
language: typescript
signature:
(
    _model: string,
    body: Record<string, unknown>,
    _stream: boolean,
    credentials: ExecuteInput["credentials"]
  ): Record<string, unknown>


id: method:4a3fc0ffc73c42a51eeed9fb77e92e87
kind: method
name: fetchGitLabDirectAccess
qualified_name: GitlabExecutor::fetchGitLabDirectAccess
file_path: open-sse/executors/gitlab.ts
language: typescript
visibility: private
signature:
(
    root: string,
    accessToken: string,
    signal: AbortSignal | null | undefined
  ): Promise<{
    directAccess: GitLabDirectAccessDetails | null;
    response: Response | null;
    bodyText: string;
  }>


id: method:de1c39219e9a100f12a65fffacc7e78d
kind: method
name: resolveRequestTarget
qualified_name: GitlabExecutor::resolveRequestTarget
file_path: open-sse/executors/gitlab.ts
language: typescript
visibility: private
signature:
(
    input: ExecuteInput,
    credentials: ProviderCredentials
  ): Promise<{
    target: GitLabRequestTarget | null;
    credentials: ProviderCredentials;
    errorResponse: Response | null;
  }>


id: method:24a208e4b2392cd6c7fd8b6715f9988a
kind: method
name: performRequest
qualified_name: GitlabExecutor::performRequest
file_path: open-sse/executors/gitlab.ts
language: typescript
visibility: private
signature:
(
    input: ExecuteInput,
    target: GitLabRequestTarget,
    transformedBody: Record<string, unknown>
  )


id: import:46c333b0aadcf945a7b3364d731c8c5c
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/glm.ts
language: typescript
signature:
import {
  applyConfiguredUserAgent,
  mergeAbortSignals,
  mergeUpstreamExtraHeaders,
  type CountTokensInput,
  type ExecuteInput,
  type ProviderCredentials,
} from "./base.ts";


id: import:a49896e7a5a6cb79d0b3ff491403c536
kind: import
name: ../config/glmProvider.ts
qualified_name: ../config/glmProvider.ts
file_path: open-sse/executors/glm.ts
language: typescript
signature:
import {
  buildGlmBaseHeaders,
  buildGlmChatUrl,
  buildGlmCodingHeaders,
  buildGlmCountTokensUrl,
  GLM_COUNT_TOKENS_TIMEOUT_MS,
  type GlmTransport,
  getGlmTransport,
} from "../config/glmProvider.ts";


id: import:033682f3d8f3cf95abf6a9ad4325a4f2
kind: import
name: ../config/providerHeaderProfiles.ts
qualified_name: ../config/providerHeaderProfiles.ts
file_path: open-sse/executors/glm.ts
language: typescript
signature:
import {
  getRuntimeVersion,
  normalizeStainlessArch,
  normalizeStainlessPlatform,
} from "../config/providerHeaderProfiles.ts";


id: method:fab32079621c0c35fbb96c0548155a1e
kind: method
name: buildUrl
qualified_name: GlmExecutor::buildUrl
file_path: open-sse/executors/glm.ts
language: typescript
signature:
(
    _model: string,
    _stream: boolean,
    _urlIndex = 0,
    credentials: ProviderCredentials | null = null
  )


id: method:0d4708b6a809df784c459cb994f903b1
kind: method
name: buildHeaders
qualified_name: GlmExecutor::buildHeaders
file_path: open-sse/executors/glm.ts
language: typescript
signature:
(
    credentials: ProviderCredentials,
    stream = true,
    _clientHeaders?: Record<string, string> | null,
    _model?: string,
    transport: GlmTransport = getGlmTransport(credentials.providerSpecificData)
  ): Record<string, string>


id: method:f246c9411d48f22079c00abdbd409af8
kind: method
name: transformRequest
qualified_name: GlmExecutor::transformRequest
file_path: open-sse/executors/glm.ts
language: typescript
signature:
(
    model: string,
    body: unknown,
    stream: boolean,
    credentials: ProviderCredentials
  )


id: method:086586ee9064bb46458b093a378780c2
kind: method
name: transformForTransport
qualified_name: GlmExecutor::transformForTransport
file_path: open-sse/executors/glm.ts
language: typescript
signature:
(
    model: string,
    body: unknown,
    stream: boolean,
    credentials: ProviderCredentials,
    transport: GlmTransport
  )


id: import:bda4672b6d4e2cb22a8f2fe6cbeda4c3
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeUpstreamExtraHeaders,
  mergeAbortSignals,
  type ExecuteInput,
} from "./base.ts";


id: interface:fe46247e31f5f8b7bced9d3fb7b56366
kind: interface
name: GrokModelInfo
qualified_name: GrokModelInfo
file_path: open-sse/executors/grok-web.ts
language: typescript
docstring:
─── Model mappings ─────────────────────────────────────────────────────────
Grok Web exposes UI modes, not stable public model IDs. Keep OmniRoute model
IDs mapped directly to Grok's modeId field.


id: constant:aa1f3245b29c9b283e573806ef2edc1e
kind: constant
name: MODEL_MAP
qualified_name: MODEL_MAP
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
= {
  fast: { modeId: "fast", isThinking: false },
  expert: { modeId: "expert", isThinking: true },
 ...


id: function:ca4120384667dd9859042578aa6b4fcd
kind: function
name: buildGrokMessage
qualified_name: buildGrokMessage
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
(messages: Array<Record<string, unknown>>, toolRegistry: GrokToolRegistry, toolChoice: unknown): string


id: function:30b92ea7b82584ede2b11a3bdfb9f31b
kind: function
name: adaptArgumentsToDeclaredTool
qualified_name: adaptArgumentsToDeclaredTool
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
(
  toolName: string,
  args: Record<string, unknown>,
  toolRegistry: GrokToolRegistry,
  intent: string,
  options: { preserveUnknownArgs?: boolean } = { preserveUnknownArgs: true }
): Record<string, unknown>


id: constant:659b0ce62aaccc52cce05b088b85f5e4
kind: constant
name: thinkingDelta
qualified_name: thinkingDelta
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
= cleanedThinking.startsWith(emittedThinking)
          ? cleanedThinking.slice(emittedThinking.length...


id: constant:240b36e60bfb74d2f56ee907f1d3d7dd
kind: constant
name: thinkingDelta
qualified_name: thinkingDelta
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
= cleanedThinking.startsWith(emittedThinking)
        ? cleanedThinking.slice(emittedThinking.length)
...


id: constant:60c99067ce29b58519d46d6a5243438a
kind: constant
name: thinkingDelta
qualified_name: thinkingDelta
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
= trailingThinking.startsWith(emittedThinking)
      ? trailingThinking.slice(emittedThinking.length)
...


id: function:e161d0ad90d2e070e0c417ad2fb0bffb
kind: function
name: enqueueStreamingToolCalls
qualified_name: enqueueStreamingToolCalls
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
(
  controller: ReadableStreamDefaultController<Uint8Array>,
  encoder: TextEncoder,
  params: {
    id: string;
    created: number;
    model: string;
    fingerprint: string;
    toolCalls: OpenAIToolCall[];
  }
): void


id: function:7ef9395d3e886337729d38f8f29c0a92
kind: function
name: buildStreamingResponse
qualified_name: buildStreamingResponse
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
(
  eventStream: ReadableStream<Uint8Array>,
  model: string,
  cid: string,
  created: number,
  isThinkingModel: boolean,
  toolRegistry: GrokToolRegistry,
  signal?: AbortSignal | null
): ReadableStream<Uint8Array>


id: function:5a6d5ca9e0317667a817fea24a88032e
kind: function
name: buildNonStreamingResponse
qualified_name: buildNonStreamingResponse
file_path: open-sse/executors/grok-web.ts
language: typescript
signature:
(
  eventStream: ReadableStream<Uint8Array>,
  model: string,
  cid: string,
  created: number,
  isThinkingModel: boolean,
  toolRegistry: GrokToolRegistry,
  signal?: AbortSignal | null
): Promise<Response>


id: constant:20800c2b97b5884e680207b60a64bf75
kind: constant
name: executors
qualified_name: executors
file_path: open-sse/executors/index.ts
language: typescript
signature:
= {
  antigravity: new AntigravityExecutor(),
  "gemini-cli": new GeminiCLIExecutor(),
  github: new G...


id: import:a0b88e0c5452897104e3f457d603d2f9
kind: import
name: ../utils/kieTask.ts
qualified_name: ../utils/kieTask.ts
file_path: open-sse/executors/kie.ts
language: typescript
signature:
import {
  isJsonObject,
  normalizeKieTaskState,
  type JsonObject,
  type KieTaskState,
} from "../utils/kieTask.ts";


id: method:26dbc13dbfe8e8dd10e1a560b0f192c2
kind: method
name: pollTask
qualified_name: KieExecutor::pollTask
file_path: open-sse/executors/kie.ts
language: typescript
signature:
({
    statusUrl,
    taskId,
    token,
    timeoutMs,
    pollIntervalMs,
  }: KiePollInput): Promise<KieTaskRecord>


id: import:a31d5910987cbadd11f3cd129cecefec
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/kiro.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeUpstreamExtraHeaders,
  type ExecuteInput,
  type ExecutorLog,
  type ProviderCredentials,
} from "./base.ts";


id: function:5529f97356f455bdf02fa35f9e29961e
kind: function
name: buildKiroFinishChunk
qualified_name: buildKiroFinishChunk
file_path: open-sse/executors/kiro.ts
language: typescript
signature:
(
  state: KiroStreamState,
  responseId: string,
  created: number,
  model: string,
  includeUsage: boolean
): JsonRecord


id: method:916443948a3853090fcce10eec424723
kind: method
name: transformEventStreamToSSE
qualified_name: KiroExecutor::transformEventStreamToSSE
file_path: open-sse/executors/kiro.ts
language: typescript
signature: (response: Response, model: string)
docstring:
Transform AWS EventStream binary response to SSE text stream
Using TransformStream instead of ReadableStream.pull() to avoid Workers timeout


id: import:182787c9b50f9b4900ca5a5a6cd96d18
kind: import
name: @/lib/providers/webCookieAuth
qualified_name: @/lib/providers/webCookieAuth
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
import {
  normalizeSessionCookieHeader,
  normalizeSessionCookieHeaders,
} from "@/lib/providers/webCookieAuth";


id: constant:e4cc813d326751b7c6bc022d1b0d84ce
kind: constant
name: META_AI_DEFAULT_COOKIE
qualified_name: META_AI_DEFAULT_COOKIE
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature: = "ecto_1_sess"
docstring:
Meta rebranded the chat product from "Abra" to "Ecto"; the session cookie
`abra_sess` was replaced by `ecto_1_sess`. `normalizeSessionCookieHeader`
only uses this constant when the user pastes a bare cookie value with no
`name=` prefix; full cookie lines (with any cookie names) pass through
untouched, so users who paste their entire DevTools cookie line still work.


id: constant:b3001c5a0a18ad9ffc28e8dc8b71414d
kind: constant
name: META_AI_SEND_MESSAGE_DOC_ID
qualified_name: META_AI_SEND_MESSAGE_DOC_ID
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature: = "29ae946c82d1f301196c6ca2226400b5"
docstring:
Persisted-query id and friendly name for the current send-message
operation. The previous Abra mutation (doc_id 078dfdff...) was retired
when Meta removed the RewriteOptionsInput type from the schema; it now
fails server-side validation with `Unknown type "RewriteOptionsInput"`.
The new operation is a Subscription rather than a Mutation, but Meta's
GraphQL endpoint still accepts it over POST and streams the response.


id: constant:612dc85b53a27cd4dfbf7ffb786d6023
kind: constant
name: MODEL_MAP
qualified_name: MODEL_MAP
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
= {
  "muse-spark": { mode: "mode_fast", isThinking: false },
  "muse-spark-thinking": { mode: "mode_t...


id: type_alias:a57c655e0d30cdacb40ab3097a81a62b
kind: type_alias
name: CachedConversation
qualified_name: CachedConversation
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
docstring:
─── Conversation continuity cache ──────────────────────────────────────────
The default behavior of /v1/chat/completions is stateless: the caller passes
the full message history each turn. Without continuation, every turn would
open a brand-new meta.ai conversation containing the OpenAI history folded
into a single user prompt — three real chat turns become three separate
conversations in the user's meta.ai history, each polluted with the prior
turns rendered as "user: …" / "assistant: …" text.

To present a clean single growing conversation in meta.ai, we cache the
conversationId we created on the previous turn keyed by a hash of the
(connectionId, model, normalized history through the last assistant turn).
On the next turn, if the incoming OpenAI history's prefix-up-to-the-last-
assistant-turn matches a cached entry, we reuse the cached conversationId,
set isNewConversation=false, and send only the latest user turn — Meta
appends to the existing conversation tree.

Hashing the *full prefix* (not just the assistant text) is important: two
independent chats from the same connection that happen to land on identical
assistant text (e.g. a generic refusal or greeting) would otherwise collide
and route the next turn into the wrong meta.ai conversation, mixing chat
state across logical sessions. The differing preceding history makes the
hashes distinct.

TTL is 30 minutes (Meta's web client also expires idle conversations on a
similar window). Cache cap is generous — entries are tiny (~250 B) so 5000
entries is ~1.25 MB, plenty of headroom for multi-user setups.


id: function:14df0e9248efee7532ad0154ebcbaae2
kind: function
name: canonicalizeNormalizedHistory
qualified_name: canonicalizeNormalizedHistory
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature: (messages: NormalizedMessage[]): string
docstring:
Canonical-stringify a normalized message list so the same logical history
always produces the same hash. Uses ASCII Group Separator / Record
Separator characters as field delimiters so they can't appear inside
normal message content.


id: constant:cdc9bbbab4fd51bb958e52e849fcbfe1
kind: constant
name: META_AI_REASONING_KEYS
qualified_name: META_AI_REASONING_KEYS
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
= [
  "reasoning",
  "reasoningContent",
  "reasoning_content",
  "reasoningText",
  "thinking",
  "th...


id: constant:d5d6fea1e997af8365f036d5559467ba
kind: constant
name: META_AI_NESTED_RENDERER_KEYS
qualified_name: META_AI_NESTED_RENDERER_KEYS
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
= [
  "contentRenderer",
  "textContent",
  "message",
  "mediaContent",
  "unified_response",
  "unif...


id: function:b792b93f234c11b8fcdade292f5e81ff
kind: function
name: buildStreamingResponse
qualified_name: buildStreamingResponse
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  deltas: string[],
  reasoningDeltas: string[],
  model: string,
  id: string,
  created: number
): ReadableStream<Uint8Array>


id: function:4a52b45fc18d9553b1bbe7396bcef70e
kind: function
name: resultWithResponse
qualified_name: resultWithResponse
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  response: Response,
  headers: Record<string, string>,
  transformedBody: unknown
): MuseSparkExecuteResult


id: function:8014b9273a1c327b454550daa71addde
kind: function
name: errorResult
qualified_name: errorResult
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  status: number,
  message: string,
  code: string,
  headers: Record<string, string>,
  transformedBody: unknown
): MuseSparkExecuteResult


id: function:5b3a58eb9fab7cee72f43b2c29aee220
kind: function
name: getContinuationCacheKey
qualified_name: getContinuationCacheKey
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  parsedHistory: ParsedHistory,
  credentials: ExecuteInput["credentials"],
  model: string
): string | null


id: function:f85f6ea0c66240e21920bf558cea57ed
kind: function
name: postMetaAiRequest
qualified_name: postMetaAiRequest
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  headers: Record<string, string>,
  transformedBody: unknown,
  signal: AbortSignal,
  log: ExecuteInput["log"]
): Promise<{ ok: true; response: Response } | { ok: false; result: MuseSparkExecuteResult }>


id: function:c59d0df81beb32d1c7faa6cb4a52c243
kind: function
name: buildHttpErrorResult
qualified_name: buildHttpErrorResult
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  upstreamResponse: Response,
  headers: Record<string, string>,
  transformedBody: unknown,
  cached: CachedConversation | null,
  cacheKey: string | null
): MuseSparkExecuteResult


id: function:d94159e63e092877bb06ebcc3daa1b23
kind: function
name: buildParsedErrorResult
qualified_name: buildParsedErrorResult
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  parsed: ParsedMetaAiResponse,
  headers: Record<string, string>,
  transformedBody: unknown,
  cached: CachedConversation | null,
  cacheKey: string | null
): MuseSparkExecuteResult


id: function:3e9877b3308316969e004a7769de0150
kind: function
name: rememberAssistantTurn
qualified_name: rememberAssistantTurn
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  parsed: ParsedMetaAiResponse,
  credentials: ExecuteInput["credentials"],
  model: string,
  parsedHistory: ParsedHistory,
  conversationContext: ConversationContext
): void


id: function:e5e7507f59ae2f561b9d9c6b44483f23
kind: function
name: buildSuccessResult
qualified_name: buildSuccessResult
file_path: open-sse/executors/muse-spark-web.ts
language: typescript
signature:
(
  parsed: ParsedMetaAiResponse,
  stream: boolean,
  model: string,
  headers: Record<string, string>,
  transformedBody: unknown
): MuseSparkExecuteResult


id: import:65c4a1787f9c7d5df496e6a4f5786934
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/nlpcloud.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeUpstreamExtraHeaders,
  type ExecuteInput,
  type ProviderCredentials,
} from "./base.ts";


id: function:4995edb241ddbf21d7d42b4ab8d9ea7b
kind: function
name: resolvePrompt
qualified_name: resolvePrompt
file_path: open-sse/executors/nlpcloud.ts
language: typescript
signature:
(messages: OpenAIMessage[] | undefined): {
  input: string;
  context: string | null;
  history: NlpCloudHistoryEntry[];
}


id: method:c0c605cf960e4ae802efa15f7c66a649
kind: method
name: buildUrl
qualified_name: NlpCloudExecutor::buildUrl
file_path: open-sse/executors/nlpcloud.ts
language: typescript
signature:
(
    model: string,
    _stream: boolean,
    _urlIndex = 0,
    credentials: ProviderCredentials | null = null
  ): string


id: import:b6571ed1a2156f57421d2606d67e51d1
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/opencode.ts
language: typescript
signature:
import {
  BaseExecutor,
  setUserAgentHeader,
  type ExecuteInput,
  type ProviderCredentials,
} from "./base.ts";


id: method:12b684c08b83fc8dac484c457c5d479c
kind: method
name: buildHeaders
qualified_name: OpencodeExecutor::buildHeaders
file_path: open-sse/executors/opencode.ts
language: typescript
signature:
(
    credentials: ProviderCredentials | null,
    stream = true,
    clientHeaders?: Record<string, string> | null,
    model?: string
  )


id: method:ee7a81f66bae7294f4d89bd86377177f
kind: method
name: transformRequest
qualified_name: OpencodeExecutor::transformRequest
file_path: open-sse/executors/opencode.ts
language: typescript
signature:
(
    model: string,
    body: any,
    stream: boolean,
    credentials: ProviderCredentials
  ): any


id: import:21f60f61cee9919e77fcbce1427e5316
kind: import
name: ../services/perplexityTlsClient.ts
qualified_name: ../services/perplexityTlsClient.ts
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature:
import {
  tlsFetchPerplexity,
  isCloudflareChallenge,
  TlsClientUnavailableError,
  type TlsFetchResult,
} from "../services/perplexityTlsClient.ts";


id: constant:21537e66e5132246ef8ef82aef55be79
kind: constant
name: PPLX_USER_AGENT
qualified_name: PPLX_USER_AGENT
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature: = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:148.0) Gecko/20100101 Firefox/148.0"
docstring:
Firefox 148 — must match the `firefox_148` TLS profile used by perplexityTlsClient.
A mismatched UA vs TLS fingerprint is itself a Cloudflare bot signal (issue #2459).


id: constant:003aca36d8183e82f7c51a9732185065
kind: constant
name: MODEL_MAP
qualified_name: MODEL_MAP
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature:
= {
  "pplx-auto": ["concise", "pplx_pro"],
  "pplx-sonar": ["copilot", "experimental"],
  "pplx-gpt":...


id: constant:321f3c78d4b42d9b47a36136b6e5cad4
kind: constant
name: THINKING_MAP
qualified_name: THINKING_MAP
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature:
= {
  "pplx-gpt": "gpt54_thinking",
  "pplx-sonnet": "claude46sonnetthinking",
  "pplx-opus": "claude4...


id: function:84982b85d7742359efd1615dffd9652d
kind: function
name: sessionStore
qualified_name: sessionStore
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature:
(
  history: Array<{ role: string; content: string }>,
  currentMsg: string,
  responseText: string,
  backendUuid: string | null
): void


id: function:3cc5e97d8c812531ec913a8be757fb7b
kind: function
name: buildPplxRequestBody
qualified_name: buildPplxRequestBody
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature:
(
  query: string,
  mode: string,
  modelPref: string,
  followUpUuid: string | null
): Record<string, unknown>


id: function:971947cddbdd72ff30b69f166b3e106a
kind: function
name: buildStreamingResponse
qualified_name: buildStreamingResponse
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature:
(
  eventStream: ReadableStream<Uint8Array>,
  model: string,
  cid: string,
  created: number,
  history: Array<{ role: string; content: string }>,
  currentMsg: string,
  signal?: AbortSignal | null
): ReadableStream<Uint8Array>


id: function:70375a59b86bdcdb38018222298890a8
kind: function
name: buildNonStreamingResponse
qualified_name: buildNonStreamingResponse
file_path: open-sse/executors/perplexity-web.ts
language: typescript
signature:
(
  eventStream: ReadableStream<Uint8Array>,
  model: string,
  cid: string,
  created: number,
  history: Array<{ role: string; content: string }>,
  currentMsg: string,
  signal?: AbortSignal | null
): Promise<Response>


id: import:e4fff888e26b27998519f661dd6b6d35
kind: import
name: ../config/petals.ts
qualified_name: ../config/petals.ts
file_path: open-sse/executors/petals.ts
language: typescript
signature:
import {
  PETALS_DEFAULT_BASE_URL,
  PETALS_DEFAULT_MODEL,
  normalizePetalsBaseUrl,
} from "../config/petals.ts";


id: method:252eff32890e07b230114f8f9a682ecd
kind: method
name: buildUrl
qualified_name: PetalsExecutor::buildUrl
file_path: open-sse/executors/petals.ts
language: typescript
signature:
(
    _model: string,
    _stream: boolean,
    _urlIndex = 0,
    credentials: ProviderCredentials | null = null
  ): string


id: import:6f81591f053c73dcfca33ca09133d2bc
kind: import
name: ./base.ts
qualified_name: ./base.ts
file_path: open-sse/executors/qoder.ts
language: typescript
signature:
import {
  BaseExecutor,
  mergeUpstreamExtraHeaders,
  setUserAgentHeader,
  type ExecuteInput,
  type ProviderCredentials,
} from "./base.ts";


id: import:f70787d2f3443b695f051c183891e1a2
kind: import
name: ../config/providerHeaderProfiles.ts
qualified_name: ../config/providerHeaderProfiles.ts
file_path: open-sse/executors/qoder.ts
language: typescript
signature:
import {
  getQoderDashscopeCompatHeaders,
  QODER_DEFAULT_USER_AGENT,
} from "../config/providerHeaderProfiles.ts";


id: method:bc63c6d4c90cb5963386aa4278910a8d
kind: method
name: buildHeaders
qualified_name: QoderExecutor::buildHeaders
file_path: open-sse/executors/qoder.ts
language: typescript
signature:
(
    credentials: ProviderCredentials,
    stream = true,
    clientHeaders?: Record<string, string> | null,
    model?: string
  ): Record<string, string>


id: constant:277ee6ab5ae281e9c759dc5f9dc90d60
kind: constant
name: COMPLETION_URL
qualified_name: COMPLETION_URL
file_path: open-sse/executors/t3-chat-web.ts
language: typescript
signature: = `${T3_CHAT_BASE}/api/chat`
docstring:
TODO(post-devtools-capture): Replace with confirmed endpoint URL.
Guesses based on Convex HTTP action pattern and reference implementations:
- https://t3.chat/api/chat
- https://t3.chat/api/sync/streamRoom
Check T3Router Rust source for the BASE_URL constant before going live.


id: constant:79b77b0f673f97362d63caca715feaa6
kind: constant
name: USER_AGENT
qualified_name: USER_AGENT
file_path: open-sse/executors/t3-chat-web.ts
language: typescript
signature:
= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 S...


id: function:0565688506ce5a85d05b6ed818368777
kind: function
name: transformT3SSE
qualified_name: transformT3SSE
file_path: open-sse/executors/t3-chat-web.ts
language: typescript
signature: (t3Stream: ReadableStream, model: string): ReadableStream
docstring:
── SSE Transform (t3.chat Convex → OpenAI) ──────────────────────────────

TODO(post-devtools-capture): Implement the actual chunk extraction logic.
The field paths below are best guesses based on the Convex streaming protocol.
Common Convex patterns: { type: "text", text: "..." } or { delta: "..." }.
Replace `chunk.text ?? chunk.delta ?? chunk.content` with the real field path.


id: constant:7c47551cce3d19b237505c93ea8eda21
kind: constant
name: USER_AGENT
qualified_name: USER_AGENT
file_path: open-sse/executors/veoaifree-web.ts
language: typescript
signature:
= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 S...


id: constant:274c76264ca89664c50f3815e1602853
kind: constant
name: PARTNER_MODELS
qualified_name: PARTNER_MODELS
file_path: open-sse/executors/vertex.ts
language: typescript
signature:
= new Set([
  "claude-3-5-sonnet",
  "claude-3-opus",
  "claude-3-haiku",
  "deepseek-v3",
  "deepseek...


id: constant:89b8156a1f34284b9c9fe1c506fa9b6c
kind: constant
name: MODEL_ALIAS_MAP
qualified_name: MODEL_ALIAS_MAP
file_path: open-sse/executors/windsurf.ts
language: typescript
docstring:
─── Model alias normalizer ──────────────────────────────────────────────────

Model names are passed directly to the Windsurf API as ModelOrAlias strings.
The API accepts the catalog names as-is (e.g. "claude-4.5-sonnet", "swe-1.6-fast").

This table handles only OmniRoute-style backwards-compat aliases where users
might type dashes instead of dots (e.g. "swe-1-6-fast" → "swe-1.6-fast").
Model IDs — source: model_configs_v2.bin extracted from Devin CLI binary.
OmniRoute uses dot-notation user IDs (e.g. "gpt-5.5-high").
Windsurf API accepts dash-notation modelUids (e.g. "gpt-5-5-high").
This map normalises dot→dash for newer models and handles legacy aliases.

signature:
= {
  // ── SWE ─────────────────────────────────────────────────────────────────
  "swe-1.6-fast": "s...


id: function:ffc4ee4c8f0aa3ec6f955ea72a3e4235
kind: function
name: encodeVarint
qualified_name: encodeVarint
file_path: open-sse/executors/windsurf.ts
language: typescript
signature: (value: number): Uint8Array
docstring:
─── Minimal protobuf encoder ────────────────────────────────────────────────

Implements only what is needed for GetChatMessageRequest.
Wire types: 0 = varint, 2 = length-delimited.


id: function:79b12794e641a0758d0ad0340382515e
kind: function
name: grpcWebFrame
qualified_name: grpcWebFrame
file_path: open-sse/executors/windsurf.ts
language: typescript
signature: (payload: Uint8Array): Uint8Array
docstring:
─── gRPC-web framing ────────────────────────────────────────────────────────
Wrap a protobuf message in a 5-byte gRPC-web data frame.


id: type_alias:dc6a2b185ff08dcdb2077b7644df6e38
kind: type_alias
name: DecodedChunk
qualified_name: DecodedChunk
file_path: open-sse/executors/windsurf.ts
language: typescript
docstring:
─── Protobuf response decoder ───────────────────────────────────────────────

CompletionChunk (oneof):
field 1 (length-delimited) → ContentChunk  { field 1: string text }
field 2 (length-delimited) → ToolCallChunk (skipped for now)
field 3 (length-delimited) → DoneChunk     { field 1: UsageStats }
field 4 (length-delimited) → ErrorChunk    { field 1: string message }

GetChatMessageResponse (unary fallback):
field 1 (length-delimited) → content string   (heuristic)
field 2 (length-delimited) → nested message   (heuristic)


id: method:7d0daedcaa51daa16d99bffd9f7c2959
kind: method
name: execute
qualified_name: WindsurfExecutor::execute
file_path: open-sse/executors/windsurf.ts
language: typescript
signature:
({
    model,
    body,
    stream,
    credentials,
    signal,
    log,
    upstreamExtraHeaders,
  }: ExecuteInput): Promise<{
    response: Response;
    url: string;
    headers: Record<string, string>;
    transformedBody: unknown;
  }>


id: import:50243be9bf96725c0be8439c64896d17
kind: import
name: ../utils/kieTask.ts
qualified_name: ../utils/kieTask.ts
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
signature:
import {
  getKieCallbackUrl,
  getKieErrorMessage,
  getKieErrorStatus,
  isJsonObject,
  parseKieResultJson,
} from "../utils/kieTask.ts";


id: function:f03e7266525157de9d4e2f00eaaaf9db
kind: function
name: isValidPathSegment
qualified_name: isValidPathSegment
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
signature: (segment: string): boolean
docstring:
Validate a path segment to prevent path traversal / SSRF.
Returns true if safe, false if it contains traversal sequences.


id: function:0c9c83f5d352a271eedcc53757dcd20b
kind: function
name: handleElevenLabsSpeech
qualified_name: handleElevenLabsSpeech
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
signature: (providerConfig, body, modelId, token)
docstring:
Handle ElevenLabs TTS
POST {baseUrl}/{voice_id} with { text, model_id }
voice_id is mapped from the OpenAI `voice` parameter


id: constant:4df6342b8131d8a6c8b0eb836d217978
kind: constant
name: INWORLD_AUDIO_FORMATS
qualified_name: INWORLD_AUDIO_FORMATS
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
docstring:
Handle Inworld TTS
POST { text, voiceId, modelId, audioConfig } → JSON { audioContent: "<base64>" }
Docs: https://docs.inworld.ai/api-reference/ttsAPI/texttospeech/synthesize-speech

signature:
= {
  mp3: { audioEncoding: "MP3", mimeType: "audio/mpeg" },
  wav: { audioEncoding: "WAV", mimeType: ...


id: function:20344108f3f96136bbbad970591ce963
kind: function
name: handleCartesiaSpeech
qualified_name: handleCartesiaSpeech
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
signature: (providerConfig, body, modelId, token)
docstring:
Handle Cartesia TTS
POST { model_id, transcript, voice, output_format } → binary audio bytes
Docs: https://docs.cartesia.ai/api-reference/tts/bytes


id: function:804cd2bd2c1099500bfc6364c04b4a9d
kind: function
name: handlePlayHtSpeech
qualified_name: handlePlayHtSpeech
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
signature: (providerConfig, body, modelId, token)
docstring:
Handle PlayHT TTS
POST { text, voice, voice_engine, output_format } → audio stream
Auth: X-USER-ID header (from token string "userId:apiKey")
Docs: https://docs.play.ht/reference/api-generate-tts-audio-stream


id: function:9724d67bc2d80947dde910f4ab483d3d
kind: function
name: handleAwsPollySpeech
qualified_name: handleAwsPollySpeech
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
signature: (providerConfig, body, modelId, token, credentials)
docstring:
Handle AWS Polly TTS
POST /v1/speech signed with AWS SigV4.
The configured apiKey stores AWS Secret Access Key; providerSpecificData.accessKeyId stores
AWS Access Key ID, with optional region/baseUrl/defaultVoice/sessionToken.


id: function:e3b01496e6308d13c83960c09b86d773
kind: function
name: handleXiaomiMimoSpeech
qualified_name: handleXiaomiMimoSpeech
file_path: open-sse/handlers/audioSpeech.ts
language: typescript
signature: (providerConfig, body, modelId, token, credentials)
docstring:
Xiaomi MiMo TTS uses chat/completions with an audio config instead of OpenAI's /audio/speech
request body.


id: import:da21037d1dbfab5584f6020a2cb9c13c
kind: import
name: ../config/audioRegistry.ts
qualified_name: ../config/audioRegistry.ts
file_path: open-sse/handlers/audioTranscription.ts
language: typescript
signature:
import {
  getTranscriptionProvider,
  parseTranscriptionModel,
  type AudioProvider,
} from "../config/audioRegistry.ts";


id: function:35973301e5e9344b4c3deedefc637edd
kind: function
name: resolveAudioContentType
qualified_name: resolveAudioContentType
file_path: open-sse/handlers/audioTranscription.ts
language: typescript
signature: (file: Blob & { name?: unknown }): string
docstring:
Infer a suitable Content-Type for Deepgram from the browser-provided MIME
type and the original filename.  Deepgram accepts `audio/*` and many raw
formats, but `video/*` causes it to silently fail with "no speech detected".
Strategy:
1. If the browser says `audio/*`, keep it as-is.
2. If it's `video/*` (e.g. `.mp4`), remap to the audio equivalent so
   Deepgram extracts the audio track.  `.mp4` → `audio/mp4`, etc.
3. Fall back to `application/octet-stream` which tells Deepgram to
   auto-detect from the raw bytes (most reliable for unknown formats).


id: function:ffa047671b6812365e33131b2f9144f4
kind: function
name: handleHuggingFaceTranscription
qualified_name: handleHuggingFaceTranscription
file_path: open-sse/handlers/audioTranscription.ts
language: typescript
signature: (providerConfig, file, modelId, token)
docstring:
Handle HuggingFace Inference transcription
POST raw binary audio to {baseUrl}/{model_id}, returns { text }


id: function:ee331d671b56276d49773a8465128b66
kind: function
name: handleAudioTranscription
qualified_name: handleAudioTranscription
file_path: open-sse/handlers/audioTranscription.ts
language: typescript
signature:
({
  formData,
  credentials,
  resolvedProvider = null,
  resolvedModel = null,
}: {
  formData: FormData;
  credentials?: TranscriptionCredentials | null;
  resolvedProvider?: AudioProvider | null;
  resolvedModel?: string | null;
}): Promise<Response>


id: import:5f076400460ee76ea05c116ed3ec6a8d
kind: import
name: ../utils/stream.ts
qualified_name: ../utils/stream.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  createSSETransformStreamWithLogger,
  createPassthroughStreamWithLogger,
  COLORS,
  withBodyTimeout,
} from "../utils/stream.ts";


id: import:44309f24b4092263876e9d96fc14fba7
kind: import
name: ../services/modelStrip.ts
qualified_name: ../services/modelStrip.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  getStripTypesForProviderModel,
  stripIncompatibleMessageContent,
} from "../services/modelStrip.ts";


id: import:08710fa9883ebe175063246039da30e8
kind: import
name: ../utils/error.ts
qualified_name: ../utils/error.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  buildErrorBody,
  createErrorResult,
  parseUpstreamError,
  formatProviderError,
} from "../utils/error.ts";


id: import:0f098172a03a587132cac567ec38d309
kind: import
name: ../config/constants.ts
qualified_name: ../config/constants.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  COOLDOWN_MS,
  HTTP_STATUS,
  FETCH_BODY_TIMEOUT_MS,
  MAX_TOOLS_LIMIT,
  PROVIDER_MAX_TOKENS,
  SSE_HEARTBEAT_INTERVAL_MS,
  STREAM_IDLE_TIMEOUT_MS,
  STREAM_READINESS_TIMEOUT_MS,
  ANTIGRAVITY_PRE_RESPONSE_TIMEOUT_CODE,
} from "../config/constants.ts";


id: import:bbbe392086aeaf74fd43eb1cbd7c13fc
kind: import
name: ../services/errorClassifier.ts
qualified_name: ../services/errorClassifier.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  classifyProviderError,
  PROVIDER_ERROR_TYPES,
  isEmptyContentResponse,
} from "../services/errorClassifier.ts";


id: import:281c9d693e7dbdf696ddb63d55977ef8
kind: import
name: ../services/apiKeyRotator.ts
qualified_name: ../services/apiKeyRotator.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  recordKeyFailure,
  recordKeySuccess,
  getInvalidKeyCount,
  trackConnectionExtraKeys,
  connectionHasExtraKeys,
  type KeyHealth,
} from "../services/apiKeyRotator.ts";


id: import:8cbda3b1db54b4e8488f7285142502c3
kind: import
name: @/lib/logEnv
qualified_name: @/lib/logEnv
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  getCallLogPipelineCaptureStreamChunks,
  getChatLogTextLimit,
  getChatLogArrayTailItems,
  getChatLogMaxDepth,
  getChatLogMaxObjectKeys,
} from "@/lib/logEnv";


id: import:73422b7ab3e9e6c8cabb5cdb4fa7d005
kind: import
name: @/lib/usageDb
qualified_name: @/lib/usageDb
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  saveRequestUsage,
  trackPendingRequest,
  updatePendingRequest,
  appendRequestLog,
  saveCallLog,
} from "@/lib/usageDb";


id: import:ebf6e92a427753ae1f6df176807333c1
kind: import
name: @/lib/localDb
qualified_name: @/lib/localDb
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  getModelNormalizeToolCallId,
  getModelPreserveOpenAIDeveloperRole,
  getModelUpstreamExtraHeaders,
  getUpstreamProxyConfig,
} from "@/lib/localDb";


id: import:4a75f0cb7697ca506acb86207910eb2c
kind: import
name: ../services/payloadRules.ts
qualified_name: ../services/payloadRules.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  applyConfiguredPayloadRules,
  resolvePayloadRuleProtocols,
} from "../services/payloadRules.ts";


id: import:6001fd25684b72a06b28ecd536313cba
kind: import
name: ../utils/cacheControlPolicy.ts
qualified_name: ../utils/cacheControlPolicy.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  shouldPreserveCacheControl,
  providerSupportsCaching,
} from "../utils/cacheControlPolicy.ts";


id: import:890a6828387312a2f3c2ad744abd7006
kind: import
name: @/lib/providers/claudeFastMode
qualified_name: @/lib/providers/claudeFastMode
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  CPA_FORCE_FAST_MODE_HEADER,
  shouldRequestClaudeFastMode,
} from "@/lib/providers/claudeFastMode";


id: import:f0623527d3cf053f6fcf61c451bd9630
kind: import
name: @/lib/providers/requestDefaults
qualified_name: @/lib/providers/requestDefaults
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  getCodexRequestDefaults,
  normalizeCodexServiceTier,
} from "@/lib/providers/requestDefaults";


id: import:f33c9467652c959977600401aea22957
kind: import
name: ../services/toolLimitDetector.ts
qualified_name: ../services/toolLimitDetector.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  getEffectiveToolLimit,
  setDetectedToolLimit,
  parseToolLimitFromError,
  shouldDetectLimit,
} from "../services/toolLimitDetector.ts";


id: import:b61a9e0858ebd52de1f33e6a5b8e9f8d
kind: import
name: ../executors/codex.ts
qualified_name: ../executors/codex.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  parseCodexQuotaHeaders,
  getCodexModelScope,
  getCodexDualWindowCooldownMs,
  isCompactResponsesEndpoint,
} from "../executors/codex.ts";


id: import:041c07b06a0257462fbcf6c48c8d81f4
kind: import
name: ./sseParser.ts
qualified_name: ./sseParser.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  parseSSEToClaudeResponse,
  parseSSEToOpenAIResponse,
  parseSSEToResponsesOutput,
} from "./sseParser.ts";


id: import:d0b01703850b44a7fbf1c33bf344c5c9
kind: import
name: ../services/rateLimitManager.ts
qualified_name: ../services/rateLimitManager.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  withRateLimit,
  updateFromHeaders,
  updateFromResponseBody,
  initializeRateLimits,
} from "../services/rateLimitManager.ts";


id: import:9688e47489b2cd0ba907bc4ef839312f
kind: import
name: ../services/accountSemaphore.ts
qualified_name: ../services/accountSemaphore.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  acquire as acquireAccountSemaphore,
  buildAccountSemaphoreKey,
  markBlocked as markAccountSemaphoreBlocked,
} from "../services/accountSemaphore.ts";


id: import:7eae1f277ecbaad885a712b8f7f1c6d5
kind: import
name: @/lib/semanticCache
qualified_name: @/lib/semanticCache
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  generateSignature,
  getCachedResponse,
  setCachedResponse,
  isCacheableForRead,
  isCacheableForWrite,
} from "@/lib/semanticCache";


id: import:d3f813dd472b62b28b9f27106b1c943d
kind: import
name: ../services/modelFamilyFallback.ts
qualified_name: ../services/modelFamilyFallback.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  isModelUnavailableError,
  getNextFamilyFallback,
  isContextOverflowError,
  findLargerContextModel,
  getModelFamily,
} from "../services/modelFamilyFallback.ts";


id: import:69e934dd95c0bed2729a9f3abca94449
kind: import
name: ../services/backgroundTaskDetector.ts
qualified_name: ../services/backgroundTaskDetector.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  getBackgroundTaskReason,
  getDegradedModel,
  getBackgroundDegradationConfig,
} from "../services/backgroundTaskDetector.ts";


id: import:9a38a3d45ea5a890147bbc10ad09f4de
kind: import
name: ../services/emergencyFallback.ts
qualified_name: ../services/emergencyFallback.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  shouldUseFallback,
  isFallbackDecision,
  EMERGENCY_FALLBACK_CONFIG,
} from "../services/emergencyFallback.ts";


id: import:9c32f5595445f17db25d9ea00b772702
kind: import
name: ../utils/aiSdkCompat.ts
qualified_name: ../utils/aiSdkCompat.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  resolveExplicitStreamAlias,
  resolveStreamFlag,
  stripMarkdownCodeFence,
} from "../utils/aiSdkCompat.ts";


id: import:02ee5bd1522db9aaf34fc86df4810459
kind: import
name: @/lib/memory/settings
qualified_name: @/lib/memory/settings
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  DEFAULT_MEMORY_SETTINGS,
  getMemorySettings,
  toMemoryRetrievalConfig,
} from "@/lib/memory/settings";


id: import:c1de131ef583ed4015b991d5764199b0
kind: import
name: ../services/claudeCodeCompatible.ts
qualified_name: ../services/claudeCodeCompatible.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  buildClaudeCodeCompatibleRequest,
  isClaudeCodeCompatibleProvider,
  resolveClaudeCodeCompatibleSessionId,
} from "../services/claudeCodeCompatible.ts";


id: import:ceae4f2b8bfd08c256aa1014cb6fbde6
kind: import
name: ../services/modelscopePolicy.ts
qualified_name: ../services/modelscopePolicy.ts
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
import {
  classifyModelScope429,
  getModelScopeRetryDelayMs,
  isModelScopeProvider,
} from "../services/modelscopePolicy.ts";


id: function:5db119e90fc7641e10e287e053ee3c8e
kind: function
name: maybeSyncClaudeExtraUsageState
qualified_name: maybeSyncClaudeExtraUsageState
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
({
  provider,
  connectionId,
  providerSpecificData,
  log,
}: {
  provider: string | null | undefined;
  connectionId: string | null | undefined;
  providerSpecificData: unknown;
  log?: { debug?: (...args: unknown[]) => void; warn?: (...args: unknown[]) => void } | null;
})


id: function:e95a7bdb69fff10b18a557b6fb8d6811
kind: function
name: shouldUseNativeCodexPassthrough
qualified_name: shouldUseNativeCodexPassthrough
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
({
  provider,
  sourceFormat,
  endpointPath,
}: {
  provider?: string | null;
  sourceFormat?: string | null;
  endpointPath?: string | null;
}): boolean


id: function:4c51d5317f19245ae08a1fd52e49cbda
kind: function
name: isClaudeCodeSemanticPassthroughRequest
qualified_name: isClaudeCodeSemanticPassthroughRequest
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
({
  provider,
  sourceFormat,
  targetFormat,
  headers,
  userAgent,
}: {
  provider?: string | null;
  sourceFormat?: string | null;
  targetFormat?: string | null;
  headers?: Record<string, unknown> | Headers | null;
  userAgent?: string | null;
}): boolean


id: function:174b8c851b4fcd2c985c4cb9de85a9d6
kind: function
name: mergeResponseToolNameMap
qualified_name: mergeResponseToolNameMap
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
(
  baseToolNameMap: Map<string, string> | null,
  transformedBody: Record<string, unknown> | null | undefined
)


id: function:d983754e52fc19f84bb44e9050cfe926
kind: function
name: buildStreamingResponseHeaders
qualified_name: buildStreamingResponseHeaders
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
(
  providerHeaders: Headers,
  meta: Parameters<typeof buildOmniRouteResponseMetaHeaders>[0]
): Record<string, string>


id: function:650a9c659ffe72a7c017dfffd5c17d9c
kind: function
name: parseNonStreamingSSEPayload
qualified_name: parseNonStreamingSSEPayload
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
(
  rawBody: string,
  preferredFormat: string,
  fallbackModel: string
): { body: Record<string, unknown>; format: string } | null


id: constant:58e31875c2b1761bb68c598b811d4605
kind: constant
name: NON_STREAMING_SSE_TERMINAL_TYPES
qualified_name: NON_STREAMING_SSE_TERMINAL_TYPES
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
= new Set([
  "message_stop",
  "response.completed",
  "response.done",
  "response.cancelled",
  "re...


id: function:d8621274af01d33c9e4e3a4c98856d09
kind: function
name: readStreamChunkWithTimeout
qualified_name: readStreamChunkWithTimeout
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
(
  reader: ReadableStreamDefaultReader<Uint8Array>,
  timeoutMs: number
): Promise<ReadableStreamReadResult<Uint8Array>>


id: function:e8d9223c4d90875b841127677fbbcd60
kind: function
name: resolveAccountSemaphoreAccountKey
qualified_name: resolveAccountSemaphoreAccountKey
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
(
  connectionId: string | null | undefined,
  credentials: Record<string, unknown> | null | undefined
): string | null


id: function:f1a7653d790e06827f0715ec4f81394a
kind: function
name: resolveAccountSemaphoreKey
qualified_name: resolveAccountSemaphoreKey
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
({
  provider,
  model,
  connectionId,
  credentials,
}: {
  provider: string | null | undefined;
  model: string;
  connectionId: string | null | undefined;
  credentials: Record<string, unknown> | null | undefined;
}): string | null


id: function:1a916f3411bb311f1fd8136e4c01f8ee
kind: function
name: buildClaudePromptCacheLogMeta
qualified_name: buildClaudePromptCacheLogMeta
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
(
  targetFormat: string,
  finalBody: Record<string, unknown> | null | undefined,
  providerHeaders: Record<string, unknown> | Headers | null | undefined,
  clientHeaders?: Headers | Record<string, unknown> | null | undefined
)


id: function:6c7b3560457d7129bf61fdd812114206
kind: function
name: attachLogMeta
qualified_name: attachLogMeta
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
(
  payload: Record<string, unknown> | null | undefined,
  meta: Record<string, unknown> | null | undefined
)


id: constant:1f44a72d1c176dddf700a8117059e79b
kind: constant
name: _proxyConfigCache
qualified_name: _proxyConfigCache
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature: = new Map<string, { mode: string; enabled: boolean; ts: number }>()
docstring:
Core chat handler - shared between SSE and Worker
Returns { success, response, status, error } for caller to handle fallback
@param {object} options
@param {object} options.body - Request body
@param {object} options.modelInfo - { provider, model }
@param {object} options.credentials - Provider credentials
@param {object} options.log - Logger instance (optional)
@param {function} options.onCredentialsRefreshed - Callback when credentials are refreshed
@param {function} options.onRequestSuccess - Callback when request succeeds (to clear error status)
@param {function} options.onDisconnect - Callback when client disconnects
@param {string} options.connectionId - Connection ID for usage tracking
@param {object} options.apiKeyInfo - API key metadata for usage attribution
@param {string} options.userAgent - Client user agent for caching decisions
@param {string} options.comboName - Combo name if this is a combo request
@param {string} options.comboStrategy - Combo routing strategy (e.g., 'priority', 'cost-optimized')
@param {boolean} options.isCombo - Whether this request is from a combo
@param {string} options.connectionId - Connection ID for settings lookup
Module-level cache for upstream proxy config (shared across all requests).
10s TTL prevents per-request DB lookups while staying fresh enough for setting changes.


id: variable:ceba63a949db2c991f941e9584f6a578
kind: variable
name: _combosPromise
qualified_name: _combosPromise
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature: = null
docstring:
Module-level cache for all combos data (shared across all requests).
Uses cached promises to prevent thundering herd — all concurrent callers
wait for the same underlying DB query while it's in flight.


id: function:62d84e2adbb065b53c06db34f58907a1
kind: function
name: handleChatCore
qualified_name: handleChatCore
file_path: open-sse/handlers/chatCore.ts
language: typescript
signature:
({
  body,
  modelInfo,
  credentials,
  log,
  onCredentialsRefreshed,
  onRequestSuccess,
  onStreamFailure,
  onDisconnect,
  clientRawRequest,
  connectionId,
  apiKeyInfo = null,
  userAgent,
  comboName,
  comboStrategy = null,
  isCombo = false,
  comboStepId = null,
  comboExecutionKey = null,
  disableEmergencyFallback = false,
  cachedSettings = null,
  skipUpstreamRetry = false,
})


id: import:0b5c643d2ec21ad01fa3fc03c73f399a
kind: import
name: ../config/embeddingRegistry.ts
qualified_name: ../config/embeddingRegistry.ts
file_path: open-sse/handlers/embeddings.ts
language: typescript
signature:
import {
  getEmbeddingProvider,
  parseEmbeddingModel,
  type EmbeddingProvider,
} from "../config/embeddingRegistry.ts";


id: function:0039d6da5648f9198945466b8d6d902f
kind: function
name: handleEmbedding
qualified_name: handleEmbedding
file_path: open-sse/handlers/embeddings.ts
language: typescript
signature:
({
  body,
  credentials,
  log,
  resolvedProvider = null,
  resolvedModel = null,
  clientRawRequest = null,
  apiKeyId = null,
  apiKeyName = null,
  connectionId = null,
}: {
  body: Record<string, unknown>;
  credentials: { apiKey?: string; accessToken?: string } | null;
  log?: { info: (...args: unknown[]) => void; error: (...args: unknown[]) => void };
  resolvedProvider?: EmbeddingProvider | null;
  resolvedModel?: string | null;
  clientRawRequest?: ClientRawRequest | null;
  apiKeyId?: string | null;
  apiKeyName?: string | null;
  connectionId?: string | null;
})


id: import:c7aab1d259d68bd85f77aedb09619dbb
kind: import
name: ../utils/kieTask.ts
qualified_name: ../utils/kieTask.ts
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
import {
  getKieErrorMessage,
  getKieErrorStatus,
  isJsonObject,
  parseKieResultJson,
} from "../utils/kieTask.ts";


id: import:a3c0ee2cbb813b506c331be7dc4e7594
kind: import
name: ../utils/comfyuiClient.ts
qualified_name: ../utils/comfyuiClient.ts
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
import {
  submitComfyWorkflow,
  pollComfyResult,
  fetchComfyOutput,
  extractComfyOutputFiles,
} from "../utils/comfyuiClient.ts";


id: constant:11c7117edbb1ed8e1cd5635a2bb65398
kind: constant
name: OPENAI_IMAGE_TO_IMAGE_MODELS
qualified_name: OPENAI_IMAGE_TO_IMAGE_MODELS
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
= new Set([
  "black-forest-labs/FLUX.2-max",
  "black-forest-labs/FLUX.2-pro",
  "black-forest-labs/F...


id: constant:43f905cd742107ce27b981cdad441eb9
kind: constant
name: BFL_MODEL_ENDPOINTS
qualified_name: BFL_MODEL_ENDPOINTS
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
= {
  "flux-2-max": "/v1/flux-2-max",
  "flux-2-pro": "/v1/flux-2-pro",
  "flux-2-flex": "/v1/flux-2-f...


id: constant:93deaedadfb8622665e4e1a07d0bc663
kind: constant
name: BFL_EDIT_MODELS
qualified_name: BFL_EDIT_MODELS
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
= new Set([
  "flux-2-max",
  "flux-2-pro",
  "flux-2-flex",
  "flux-kontext-pro",
  "flux-kontext-max...


id: constant:97eb2ce960e78fa56dfc7f0ba687b3af
kind: constant
name: STABILITY_GENERATION_ENDPOINTS
qualified_name: STABILITY_GENERATION_ENDPOINTS
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
= {
  "sd3.5-large": "/v2beta/stable-image/generate/sd3",
  "sd3.5-large-turbo": "/v2beta/stable-image...


id: constant:4554883ed8dc4f699f23580f9df19bf1
kind: constant
name: STABILITY_EDIT_ENDPOINTS
qualified_name: STABILITY_EDIT_ENDPOINTS
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
= {
  inpaint: "/v2beta/stable-image/edit/inpaint",
  outpaint: "/v2beta/stable-image/edit/outpaint",
...


id: constant:676682404ad0152c571c0cd91f0f20f0
kind: constant
name: FAL_PRESET_SIZES
qualified_name: FAL_PRESET_SIZES
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
= {
  "1024x1024": "square_hd",
  "512x512": "square",
  "1792x1024": "landscape_16_9",
  "1024x1792":...


id: function:b3a46f765d26d83cfba39c0290035478
kind: function
name: handleImageGeneration
qualified_name: handleImageGeneration
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
({
  body,
  credentials,
  log,
  resolvedProvider = null,
  signal = null,
  clientHeaders = null,
})


id: function:8cbe2056a4d314ef880392d8b97fc83a
kind: function
name: handleGeminiImageGeneration
qualified_name: handleGeminiImageGeneration
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature: ({ model, providerConfig, body, credentials, log })
docstring:
Handle Gemini-format image generation (Antigravity / Nano Banana)
Uses Gemini's generateContent API with responseModalities: ["TEXT", "IMAGE"]


id: function:c539afe451f6db408f787d5b8db0677f
kind: function
name: handleImageEdit
qualified_name: handleImageEdit
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
({
  provider,
  model,
  body,
  imageBytes,
  credentials,
  log,
  signal = null,
  clientHeaders = null,
}: {
  provider: string;
  model: string;
  body: Record<string, any>;
  imageBytes: Buffer;
  imageMime?: string; // accepted for symmetry with route layer; not used
  credentials: any;
  log: any;
  signal?: AbortSignal | null;
  clientHeaders?: Record<string, string> | null;
})


id: function:8e2c6e6dbe13280571496fe0ac29abce
kind: function
name: mapLegacyImageQualityToImageTool
qualified_name: mapLegacyImageQualityToImageTool
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature: (value: string): string
docstring:
The image_generation hosted tool accepts { "auto" | "low" | "medium" | "high" }
for `quality`. Legacy image clients often send "standard" / "hd". Map those values
so OpenWebUI's quality dropdown doesn't silently get rejected upstream.


id: function:0aa279c07aa1614d6c4071415bd56271
kind: function
name: saveImageSuccessResult
qualified_name: saveImageSuccessResult
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature:
({
  provider,
  model,
  startTime,
  requestBody = null,
  responseBody = null,
  created = null,
  images,
})


id: function:3083718b46a42e69fa20cd368fa620ba
kind: function
name: handleHyperbolicImageGeneration
qualified_name: handleHyperbolicImageGeneration
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature: ({ model, provider, providerConfig, body, credentials, log, })
docstring:
Handle Hyperbolic image generation
Uses { model_name, prompt, height, width } and returns { images: [{ image: base64 }] }


id: function:b4d6c79ec5a0b47149e4a40bee243a26
kind: function
name: handleNanoBananaImageGeneration
qualified_name: handleNanoBananaImageGeneration
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature: ({ model, provider, providerConfig, body, credentials, log, })
docstring:
Handle NanoBanana image generation
NanoBanana is async (submit task -> poll status -> return final image URL/base64)


id: function:cd7f46126c70325b3e5ec032dc46c7b6
kind: function
name: handleSDWebUIImageGeneration
qualified_name: handleSDWebUIImageGeneration
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature: ({ model, provider, providerConfig, body, log })
docstring:
Handle SD WebUI image generation (local, no auth)
POST {baseUrl} with { prompt, negative_prompt, width, height, steps }
Response: { images: ["base64..."] }


id: function:1706c90cdc9c98e3f087a66660b63192
kind: function
name: handleComfyUIImageGeneration
qualified_name: handleComfyUIImageGeneration
file_path: open-sse/handlers/imageGeneration.ts
language: typescript
signature: ({ model, provider, providerConfig, body, log })
docstring:
Handle ComfyUI image generation (local, no auth)
Submits a txt2img workflow, polls for completion, fetches output


id: function:3e3f5d3e4c06ca388adb2edb18a591f5
kind: function
name: handleComfyUIMusicGeneration
qualified_name: handleComfyUIMusicGeneration
file_path: open-sse/handlers/musicGeneration.ts
language: typescript
signature: ({ model, provider, providerConfig, body, log })
docstring:
Handle ComfyUI music generation
Submits an audio generation workflow (Stable Audio / MusicGen), polls, fetches output


id: function:b48eb9cfc9ee25a66b814d04b1e89655
kind: function
name: handleKieMusicGeneration
qualified_name: handleKieMusicGeneration
file_path: open-sse/handlers/musicGeneration.ts
language: typescript
signature:
({
  model,
  provider,
  providerConfig,
  body,
  credentials,
  log,
}: {
  model: string;
  provider: string;
  providerConfig: {
    baseUrl: string;
    statusUrl?: string;
  };
  body: Record<string, unknown> & {
    prompt?: unknown;
    timeout_ms?: unknown;
    poll_interval_ms?: unknown;
  };
  credentials?: {
    apiKey?: string;
    accessToken?: string;
  } | null;
  log?: {
    info: (scope: string, message: string) => void;
    error: (scope: string, message: string) => void;
  } | null;
})


id: import:19324bbf8cea04e3e83ca3a666f4356b
kind: import
name: ../config/rerankRegistry.ts
qualified_name: ../config/rerankRegistry.ts
file_path: open-sse/handlers/rerank.ts
language: typescript
signature:
import { getRerankProvider, parseRerankModel, RERANK_PROVIDERS } from "../config/rerankRegistry.ts";


id: constant:b47711253bd7b552d5bc53c671d5f730
kind: constant
name: ALLOWED_USAGE_FIELDS
qualified_name: ALLOWED_USAGE_FIELDS
file_path: open-sse/handlers/responseSanitizer.ts
language: typescript
docstring:
Response Sanitizer — Normalizes LLM responses to strict OpenAI SDK format.
Fixes Issues:
1. Strips non-standard fields (x_groq, usage_breakdown, service_tier) that
   break OpenAI Python SDK v1.83+ Pydantic validation (returns str instead of object)
2. Extracts <think> tags from thinking models into reasoning_content
3. Normalizes response id, object, and usage fields
4. Converts developer role → system for non-OpenAI providers

signature:
= new Set([
  "prompt_tokens",
  "completion_tokens",
  "total_tokens",
  "prompt_tokens_details",
  "...


id: constant:b69f79848fc9aa7305b18703a33fae24
kind: constant
name: ALLOWED_RESPONSES_USAGE_FIELDS
qualified_name: ALLOWED_RESPONSES_USAGE_FIELDS
file_path: open-sse/handlers/responseSanitizer.ts
language: typescript
signature:
= new Set([
  "input_tokens",
  "output_tokens",
  "total_tokens",
  "input_tokens_details",
  "output...


id: constant:bbf45c7aeee254b6de07e9eaa893cf71
kind: constant
name: EXCESSIVE_NEWLINES
qualified_name: EXCESSIVE_NEWLINES
file_path: open-sse/handlers/responseSanitizer.ts
language: typescript
signature: = /\n{2,}/g
docstring:
#638, #727: Collapse runs of 2+ consecutive newlines into \n\n
Tool call responses from thinking models often accumulate excessive newlines


id: import:bda61dcf0878fb454d4c5fb6d83710ee
kind: import
name: ../services/geminiThoughtSignatureStore.ts
qualified_name: ../services/geminiThoughtSignatureStore.ts
file_path: open-sse/handlers/responseTranslator.ts
language: typescript
signature:
import {
  buildGeminiThoughtSignatureKey,
  storeGeminiThoughtSignature,
} from "../services/geminiThoughtSignatureStore.ts";


id: function:db3c202b08ed51299aba3a2653d7b0ae
kind: function
name: findBestMessageText
qualified_name: findBestMessageText
file_path: open-sse/handlers/responseTranslator.ts
language: typescript
docstring:
T19: Pick the last non-empty message output text from Responses API output.
Falls back to the last message item even when all message texts are empty.

signature:
(output: unknown[]): {
  text: string;
  selectedMessageIndex: number;
  messageItems: JsonRecord[];
}


id: function:91f10e10d7f77a96b4b94a067b5ca4f5
kind: function
name: translateNonStreamingResponse
qualified_name: translateNonStreamingResponse
file_path: open-sse/handlers/responseTranslator.ts
language: typescript
signature:
(
  responseBody: unknown,
  targetFormat: string,
  sourceFormat: string,
  toolNameMap?: Map<string, string> | null
): unknown


id: function:706b52fee310da387885bd332e891eea
kind: function
name: handleResponsesCore
qualified_name: handleResponsesCore
file_path: open-sse/handlers/responsesHandler.ts
language: typescript
signature:
({
  body,
  modelInfo,
  credentials,
  log,
  onCredentialsRefreshed,
  onRequestSuccess,
  onDisconnect,
  connectionId,
  signal,
})


id: constant:a4970f8b5d2b3f366bfa1eb3e348c415
kind: constant
name: CONTROL_CHAR_RE
qualified_name: CONTROL_CHAR_RE
file_path: open-sse/handlers/search.ts
language: typescript
signature: = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/
docstring:
── Input Sanitization ──────────────────────────────────────────────────
Control characters that should never appear in search queries


id: function:96a0b4346e2c029762ec32809196d128
kind: function
name: makeResult
qualified_name: makeResult
file_path: open-sse/handlers/search.ts
language: typescript
docstring: ── Response Normalizers ────────────────────────────────────────────────
signature:
(
  providerId: string,
  item: {
    title?: string;
    url?: string;
    snippet?: string;
    score?: number;
    published_at?: string;
    favicon_url?: string;
    author?: string;
    source_type?: string;
    image_url?: string;
    full_text?: string;
    text_format?: string;
  },
  idx: number,
  now: string
): SearchResult


id: function:7cbf6f61fd41ccf8aa0df9c3021dfc15
kind: function
name: normalizeSerperResponse
qualified_name: normalizeSerperResponse
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(
  data: any,
  _query: string,
  searchType: string
): { results: SearchResult[]; totalResults: number | null }


id: function:2fdb4868d15e8704f50830d9b2ffd193
kind: function
name: getProviderSettingString
qualified_name: getProviderSettingString
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(
  params: Pick<SearchRequestParams, "providerOptions" | "providerSpecificData">,
  key: string
): string | undefined


id: function:998ebee4922ceafbbdbd4c7e2a32d91b
kind: function
name: buildSerperRequest
qualified_name: buildSerperRequest
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(
  config: SearchProviderConfig,
  params: SearchRequestParams
): { url: string; init: RequestInit }


id: function:60951538854f26b30ec0b409df1d1345
kind: function
name: normalizePerplexityResponse
qualified_name: normalizePerplexityResponse
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(
  data: any,
  _query: string,
  _searchType: string
): { results: SearchResult[]; totalResults: number | null }


id: constant:b0ca16adf314a353d75d83dbbe2a968f
kind: constant
name: ZaiSearchItemSchema
qualified_name: ZaiSearchItemSchema
file_path: open-sse/handlers/search.ts
language: typescript
docstring:
── Z.AI Coding Plan Search MCP Execution ───────────────────────────
Schema for the Z.AI MCP web_search_prime tool result. Z.AI double-encodes
the results array as a JSON string inside the MCP text content, so we
safely unwrap it with a typed schema instead of `JSON.parse(parsed)`.

signature:
= z
  .object({
    title: z.string().optional(),
    link: z.string().optional(),
    content: z.stri...


id: function:4cb6f334d020b8e5586589b88b4c2554
kind: function
name: unwrapZaiContent
qualified_name: unwrapZaiContent
file_path: open-sse/handlers/search.ts
language: typescript
signature: (rawText: string): ZaiSearchItem[] | null
docstring:
Unwrap the double-encoded JSON from a Z.AI MCP web_search_prime response.
Quirk: the MCP server returns a text content block whose body is a JSON
string. That JSON string, once parsed, is itself another JSON string
containing the actual results array. We try a single parse first
(in case the upstream behavior ever changes), then a nested parse.
Both paths are validated through `ZaiSearchResultsSchema` so any shape
regression upstream lands in our error path instead of corrupting results.


id: function:4aabf4315b5932ff862a96a058609763
kind: function
name: zaiSearchExecute
qualified_name: zaiSearchExecute
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(params: {
  config: SearchProviderConfig;
  query: string;
  token: string;
  params: SearchRequestParams;
  signal?: AbortSignal;
}): Promise<{ results: SearchResult[]; totalResults: number | null }>


id: function:f2f2e16d507de5d7f896e35cb61ae184
kind: function
name: tryZaiMCPProvider
qualified_name: tryZaiMCPProvider
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(
  config: SearchProviderConfig,
  params: Omit<SearchRequestParams, "token">,
  token: string,
  providerSpecificData: Record<string, unknown> | undefined,
  startTime: number,
  globalStartTime: number,
  log?: any
): Promise<SearchHandlerResult>


id: function:dd49ff5aa511b720a6b0ba99f05ad018
kind: function
name: normalizeResponse
qualified_name: normalizeResponse
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(
  providerId: string,
  data: any,
  query: string,
  searchType: string
): { results: SearchResult[]; totalResults: number | null }


id: function:22bb87167ebf97e09aaa4a15302ffee1
kind: function
name: tryProvider
qualified_name: tryProvider
file_path: open-sse/handlers/search.ts
language: typescript
signature:
(
  config: SearchProviderConfig,
  params: Omit<SearchRequestParams, "token">,
  credentials: Record<string, any>,
  globalStartTime: number,
  log?: any
): Promise<SearchHandlerResult>


id: function:b34002d3886e57d81fb359d565413b7f
kind: function
name: readSSEEvents
qualified_name: readSSEEvents
file_path: open-sse/handlers/sseParser.ts
language: typescript
signature: (rawSSE)
docstring:
Convert OpenAI-style SSE chunks into a single non-streaming JSON response.
Used as a fallback when upstream returns text/event-stream for stream=false.


id: constant:2f5039802b96a723e1cdf8066767d20b
kind: constant
name: RESPONSES_TERMINAL_EVENT_TYPES
qualified_name: RESPONSES_TERMINAL_EVENT_TYPES
file_path: open-sse/handlers/sseParser.ts
language: typescript
docstring:
Convert Responses API SSE events into a single non-streaming response object.
Expects events such as response.created / response.in_progress / response.completed.

signature:
= new Set([
  "response.completed",
  "response.done",
  "response.cancelled",
  "response.canceled",
...


id: import:c7f4900152ff821e5af98a219296683b
kind: import
name: ../config/runway.ts
qualified_name: ../config/runway.ts
file_path: open-sse/handlers/videoGeneration.ts
language: typescript
signature:
import {
  buildRunwayApiUrl,
  buildRunwayHeaders,
  RUNWAYML_IMAGE_REQUIRED_MODELS,
} from "../config/runway.ts";


id: function:d95542fc33d2ddf4854c548b4b841f52
kind: function
name: handleComfyUIVideoGeneration
qualified_name: handleComfyUIVideoGeneration
file_path: open-sse/handlers/videoGeneration.ts
language: typescript
signature: ({ model, provider, providerConfig, body, log })
docstring:
Handle ComfyUI video generation
Submits an AnimateDiff or SVD workflow, polls for completion, fetches output video


id: function:7846ee12eb84cc1a9db91438eb421909
kind: function
name: handleKieVideoGeneration
qualified_name: handleKieVideoGeneration
file_path: open-sse/handlers/videoGeneration.ts
language: typescript
signature:
({
  model,
  provider,
  providerConfig,
  body,
  credentials,
  log,
}: {
  model: string;
  provider: string;
  providerConfig: {
    baseUrl: string;
    statusUrl?: string;
  };
  body: Record<string, unknown> & {
    prompt?: unknown;
    duration?: unknown;
    aspect_ratio?: unknown;
    sound?: unknown;
    timeout_ms?: unknown;
    poll_interval_ms?: unknown;
  };
  credentials?: {
    apiKey?: string;
    accessToken?: string;
  } | null;
  log?: {
    info: (scope: string, message: string) => void;
    error: (scope: string, message: string) => void;
  } | null;
})


id: method:bd377a68510c7c1c89c1febf482b5b02
kind: method
name: encodeString
qualified_name: DeepSeekHashWasm::encodeString
file_path: open-sse/lib/deepseek-pow.ts
language: typescript
visibility: private
signature:
(
    text: string,
    allocate: (size: number, align: number) => number,
    reallocate: (ptr: number, oldSize: number, newSize: number, align: number) => number
  ): number


id: function:db26ce0e0d503486c70db4c2fd84af12
kind: function
name: solveDeepSeekPowAsync
qualified_name: solveDeepSeekPowAsync
file_path: open-sse/lib/deepseek-pow.ts
language: typescript
signature:
(
  algorithm: string,
  challenge: string,
  salt: string,
  difficulty: number,
  expireAt: number
): Promise<number>


id: function:ab859a9cd66cff19fbd4722a56bc546a
kind: function
name: solveDeepSeekPow
qualified_name: solveDeepSeekPow
file_path: open-sse/lib/deepseek-pow.ts
language: typescript
signature:
(
  algorithm: string,
  challenge: string,
  salt: string,
  difficulty: number,
  expireAt: number
): number


id: import:c618fd663d57cf563e5f4636c185254f
kind: import
name: ../schemas/tools.ts
qualified_name: ../schemas/tools.ts
file_path: open-sse/mcp-server/__tests__/cacheTools.test.ts
language: typescript
signature:
import {
  MCP_TOOLS,
  MCP_TOOL_MAP,
  cacheStatsInput,
  cacheFlushInput,
  cacheStatsTool,
  cacheFlushTool,
} from "../schemas/tools.ts";


id: import:03490187d06e79a41e13f56eadcb2bd5
kind: import
name: ../../config/providerModels.ts
qualified_name: ../../config/providerModels.ts
file_path: open-sse/mcp-server/__tests__/glmCodingProviderConfig.test.ts
language: typescript
signature:
import {
  PROVIDER_ID_TO_ALIAS,
  getModelsByProviderId,
  getProviderModels,
} from "../../config/providerModels.ts";


id: import:deb578f2a054d35bd594fa8cd577cb19
kind: import
name: ../schemas/tools.ts
qualified_name: ../schemas/tools.ts
file_path: open-sse/mcp-server/__tests__/routingStrategyTool.test.ts
language: typescript
signature:
import {
  MCP_TOOLS,
  MCP_TOOL_MAP,
  setRoutingStrategyInput,
  setRoutingStrategyTool,
} from "../schemas/tools.ts";


id: function:09da63d42d637930833da6c0881ab9ab
kind: function
name: logToolCall
qualified_name: logToolCall
file_path: open-sse/mcp-server/audit.ts
language: typescript
signature:
(
  toolName: string,
  input: unknown,
  output: unknown,
  durationMs: number,
  success: boolean,
  errorCode?: string
): Promise<void>


id: function:6c43a8705d9784c7fed7ca95859badf2
kind: function
name: queryAuditEntries
qualified_name: queryAuditEntries
file_path: open-sse/mcp-server/audit.ts
language: typescript
signature:
(
  filters: McpAuditQuery = {}
): Promise<{ entries: McpAuditEntry[]; total: number; limit: number; offset: number }>


id: function:9b804667fdb272af35f9f655e073052d
kind: function
name: getAuditStats
qualified_name: getAuditStats
file_path: open-sse/mcp-server/audit.ts
language: typescript
signature:
(): Promise<{
  totalCalls: number;
  successRate: number;
  avgDurationMs: number;
  topTools: Array<{ tool: string; count: number }>;
}>


id: import:b0f994fe1555b2c2973b5b0ac059e65e
kind: import
name: ../services/compression/preservation.ts
qualified_name: ../services/compression/preservation.ts
file_path: open-sse/mcp-server/descriptionCompressor.ts
language: typescript
signature:
import {
  extractPreservedBlocks,
  restorePreservedBlocks,
} from "../services/compression/preservation.ts";


id: constant:847ae90029d16bdaf50f7256e40804e0
kind: constant
name: descriptionCompressionStats
qualified_name: descriptionCompressionStats
file_path: open-sse/mcp-server/descriptionCompressor.ts
language: typescript
signature:
= {
  descriptionsCompressed: 0,
  charsBefore: 0,
  charsAfter: 0,
  charsSaved: 0,
  estimatedTokens...


id: function:d3516ba8266464a8cff849128101a9de
kind: function
name: compressDescriptionsInPlace
qualified_name: compressDescriptionsInPlace
file_path: open-sse/mcp-server/descriptionCompressor.ts
language: typescript
signature:
(
  value: unknown,
  fieldNames: string[] = ["description"],
  options: DescriptionCompressionOptions = {}
): void


id: import:ec3036247963ac053ae459fbbc92de16
kind: import
name: @modelcontextprotocol/sdk/server/webStandardStreamableHttp.js
qualified_name: @modelcontextprotocol/sdk/server/webStandardStreamableHttp.js
file_path: open-sse/mcp-server/httpTransport.ts
language: typescript
signature:
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";


id: function:3a6b8a97f698eef5564ae46c55e454b7
kind: function
name: getMcpHttpStatus
qualified_name: getMcpHttpStatus
file_path: open-sse/mcp-server/httpTransport.ts
language: typescript
signature:
(): {
  online: boolean;
  transport: string | null;
  startedAt: number | null;
  uptime: string | null;
}


id: function:4525ef4ff53e2d8c4ce2caaae6efa167
kind: function
name: startMcpHeartbeat
qualified_name: startMcpHeartbeat
file_path: open-sse/mcp-server/runtimeHeartbeat.ts
language: typescript
signature:
(config: {
  version: string;
  scopesEnforced: boolean;
  allowedScopes: string[];
  toolCount: number;
  intervalMs?: number;
}): () => void


id: function:f135c9d80ea67d951459fe0e069da7a6
kind: function
name: isMcpHeartbeatOnline
qualified_name: isMcpHeartbeatOnline
file_path: open-sse/mcp-server/runtimeHeartbeat.ts
language: typescript
signature:
(
  snapshot: McpHeartbeatSnapshot | null,
  options?: { staleAfterMs?: number; requireLivePid?: boolean }
): boolean


id: constant:da02af54cf54960528eec78808d9ebb3
kind: constant
name: AgentSkillSchema
qualified_name: AgentSkillSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  id: z.string(),
  name: z.string(),
  description: z.string(),
  tags: z.array(z.string...


id: constant:61467e7e2ff995ea64b427fa821cfe08
kind: constant
name: AgentCardSchema
qualified_name: AgentCardSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  name: z.string(),
  description: z.string(),
  url: z.string().url(),
  version: z.stri...


id: constant:bae9c0616fcf3dfbb1fbb9e4fe345b0e
kind: constant
name: TaskInputSchema
qualified_name: TaskInputSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  messages: z
    .array(
      z.object({
        role: z.string(),
        content: z.s...


id: constant:aa9a83bd1ea2e9680b59cc18db9a260c
kind: constant
name: CostEnvelopeSchema
qualified_name: CostEnvelopeSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  estimated: z.number(),
  actual: z.number(),
  currency: z.string().default("USD"),
})


id: constant:8570532df44517a9a5ef583dcc769621
kind: constant
name: ResilienceTraceEventSchema
qualified_name: ResilienceTraceEventSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  event: z.string(),
  provider: z.string().optional(),
  reason: z.string().optional(),
...


id: constant:4bcff7b3959d12c6fd7f1afae458853e
kind: constant
name: PolicyVerdictSchema
qualified_name: PolicyVerdictSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  allowed: z.boolean(),
  reason: z.string(),
  restrictions: z.array(z.string()).optiona...


id: constant:8ef2884cbba802e3ef6833b9a473cbe4
kind: constant
name: TaskOutputSchema
qualified_name: TaskOutputSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  response: z
    .object({
      content: z.string(),
      model: z.string(),
      tok...


id: constant:29f023d08f24fcddf0a400daf19f01e3
kind: constant
name: TaskSchema
qualified_name: TaskSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  id: z.string().uuid(),
  state: TaskStateEnum,
  skillId: z.string(),
  input: TaskInpu...


id: constant:3e176ba30e3082dd42aca2e80ca4c0ab
kind: constant
name: JsonRpcRequestSchema
qualified_name: JsonRpcRequestSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  jsonrpc: z.literal("2.0"),
  method: z.enum(["message/send", "message/stream", "tasks/g...


id: constant:7d5cb96ef62fa50a67d3cc41353dad37
kind: constant
name: JsonRpcResponseSchema
qualified_name: JsonRpcResponseSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  jsonrpc: z.literal("2.0"),
  result: z.unknown().optional(),
  error: z
    .object({
 ...


id: constant:0a70457a94d544a17e0d58953b06bb6a
kind: constant
name: MessageSendParamsSchema
qualified_name: MessageSendParamsSchema
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= z.object({
  task: z
    .object({
      skillId: z.string(),
    })
    .optional(),
  message: z.o...


id: constant:2b37c59a87237b7f9051ba5077bbb30f
kind: constant
name: A2A_SSE_EVENTS
qualified_name: A2A_SSE_EVENTS
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= {
  TASK_STATUS: "task.status",
  TASK_ARTIFACT: "task.artifact",
  TASK_CHUNK: "task.chunk",
  TASK...


id: constant:115b20896d865e3a88cdd607ea280061
kind: constant
name: A2A_ERROR_CODES
qualified_name: A2A_ERROR_CODES
file_path: open-sse/mcp-server/schemas/a2a.ts
language: typescript
signature:
= {
  INVALID_REQUEST: -32600,
  METHOD_NOT_FOUND: -32601,
  INVALID_PARAMS: -32602,
  INTERNAL_ERROR:...


id: import:750ffca308311c69245090be5207d769
kind: import
name: ../../../src/shared/constants/routingStrategies.ts
qualified_name: ../../../src/shared/constants/routingStrategies.ts
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
import {
  AUTO_ROUTING_STRATEGY_VALUES,
  ROUTING_STRATEGY_VALUES,
} from "../../../src/shared/constants/routingStrategies.ts";


id: constant:bc2100514143bbd578361e7a2d737ae1
kind: constant
name: getHealthOutput
qualified_name: getHealthOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  uptime: z.string(),
  version: z.string(),
  memoryUsage: z.object({
    heapUsed: z.nu...


id: constant:f6ec6cad0cebf27bf9b8b99cc81f420b
kind: constant
name: getHealthTool
qualified_name: getHealthTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_get_health",
  description:
    "Returns the current health status of OmniRoute...


id: constant:c32f4e8ecd8645beb389f4b9a1f40a2e
kind: constant
name: listCombosInput
qualified_name: listCombosInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  includeMetrics: z
    .boolean()
    .optional()
    .describe("Include request count, ...


id: constant:e7ebbf97b5ea66af0d1b559b39055c4e
kind: constant
name: listCombosOutput
qualified_name: listCombosOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  combos: z.array(
    z.object({
      id: z.string(),
      name: z.string(),
      mod...


id: constant:c5dedb9a6d98e5469cf6954480d6bd37
kind: constant
name: listCombosTool
qualified_name: listCombosTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_list_combos",
  description:
    "Lists all configured combos (model chains) wi...


id: constant:f339c8edfc4df4b7756c83c9a7257dbc
kind: constant
name: getComboMetricsOutput
qualified_name: getComboMetricsOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  requests: z.number(),
  successRate: z.number(),
  avgLatency: z.number(),
  costTotal:...


id: constant:cb05986792a0a168e4a1b2bc1bb4e59e
kind: constant
name: getComboMetricsTool
qualified_name: getComboMetricsTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_get_combo_metrics",
  description:
    "Returns detailed performance metrics fo...


id: constant:d4508860b072fc24c6e33d8934496768
kind: constant
name: switchComboInput
qualified_name: switchComboInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  comboId: z.string().describe("ID of the combo to activate/deactivate"),
  active: z.boo...


id: constant:3026677db3d0a609247f02bb4d23f304
kind: constant
name: switchComboOutput
qualified_name: switchComboOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  success: z.boolean(),
  combo: z.object({
    id: z.string(),
    name: z.string(),
   ...


id: constant:7f21dd956e70ab7674d2dc2790d3fc54
kind: constant
name: switchComboTool
qualified_name: switchComboTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
    name: "omniroute_switch_combo",
    description:
      "Activates or deactivates a combo. When...


id: constant:b6176a7a9988df816423bc7e95401823
kind: constant
name: checkQuotaInput
qualified_name: checkQuotaInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  provider: z
    .string()
    .optional()
    .describe(
      "Filter by provider name...


id: constant:4f5f601a3fa39b18fd010674a9650077
kind: constant
name: checkQuotaOutput
qualified_name: checkQuotaOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  providers: z.array(
    z.object({
      name: z.string(),
      provider: z.string(),
...


id: constant:d57a80267ac28761b101cc58d141852e
kind: constant
name: checkQuotaTool
qualified_name: checkQuotaTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_check_quota",
  description:
    "Checks the remaining API quota for one or all...


id: constant:6d0b706ecbe7841a86422dda5a4afab7
kind: constant
name: routeRequestInput
qualified_name: routeRequestInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  model: z.string().describe("Model identifier (e.g., 'claude-sonnet-4', 'gpt-4o')"),
  m...


id: constant:eb821f5e715e273ab834fb402716d684
kind: constant
name: routeRequestOutput
qualified_name: routeRequestOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  response: z.object({
    content: z.string(),
    model: z.string(),
    tokens: z.obje...


id: constant:1eb5c27430a8727365b6123bdf331b60
kind: constant
name: routeRequestTool
qualified_name: routeRequestTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_route_request",
  description:
    "Sends a chat completion request through Omn...


id: constant:8e2be89e5c2fab12ed7b4bae943089b1
kind: constant
name: costReportInput
qualified_name: costReportInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  period: z
    .enum(["session", "day", "week", "month"])
    .optional()
    .default("...


id: constant:52b6e9a565562a11bd3169d6c4358c7e
kind: constant
name: costReportOutput
qualified_name: costReportOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  period: z.string(),
  totalCost: z.number(),
  requestCount: z.number(),
  tokenCount: ...


id: constant:ad9f610ba8f26623d1a1e91875afef93
kind: constant
name: costReportTool
qualified_name: costReportTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_cost_report",
  description:
    "Generates a cost report for the specified per...


id: constant:9b30d297f09d1c57519e78a8c8551cbf
kind: constant
name: listModelsCatalogInput
qualified_name: listModelsCatalogInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  provider: z.string().optional().describe("Filter by provider name"),
  capability: z
  ...


id: constant:653a31bf387f255b2c72e3cf730fc455
kind: constant
name: listModelsCatalogOutput
qualified_name: listModelsCatalogOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  models: z.array(
    z.object({
      id: z.string(),
      provider: z.string(),
     ...


id: constant:d49ce4fa01dbb2d2946adbf045c1ec5d
kind: constant
name: listModelsCatalogTool
qualified_name: listModelsCatalogTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_list_models_catalog",
  description:
    "Lists all available AI models across ...


id: constant:7c35bd36c15e065c4fc163430bbf66a2
kind: constant
name: webSearchInput
qualified_name: webSearchInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  query: z
    .string()
    .min(1, "Query is required")
    .max(500, "Query must be 50...


id: constant:0746f945d8e9a2bc1f232238f6f72bf8
kind: constant
name: webSearchOutput
qualified_name: webSearchOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  id: z.string(),
  provider: z.string(),
  query: z.string(),
  results: z.array(
    z....


id: constant:b24061910a7f68f3a80665e34436bfc5
kind: constant
name: webSearchTool
qualified_name: webSearchTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_web_search",
  description:
    "Performs a web search using OmniRoute's search...


id: constant:b7ec81653c4f1a9da9f29afd3aa55029
kind: constant
name: simulateRouteInput
qualified_name: simulateRouteInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  model: z.string().describe("Target model for simulation"),
  promptTokenEstimate: z.num...


id: constant:37b299a36bb2c716b444152b60fb61ce
kind: constant
name: simulateRouteOutput
qualified_name: simulateRouteOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  simulatedPath: z.array(
    z.object({
      provider: z.string(),
      model: z.strin...


id: constant:a1bdceb7699d50b38889641917a089f1
kind: constant
name: simulateRouteTool
qualified_name: simulateRouteTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_simulate_route",
  description:
    "Simulates (dry-run) the routing path a req...


id: constant:a2d33524f5a01b582d33a64a14779b3e
kind: constant
name: setBudgetGuardInput
qualified_name: setBudgetGuardInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  maxCost: z.number().describe("Maximum cost in USD for this session"),
  action: z.enum(...


id: constant:f4e2db49e5c1c0b75efe1791f25e59ec
kind: constant
name: setBudgetGuardOutput
qualified_name: setBudgetGuardOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  sessionId: z.string(),
  budgetTotal: z.number(),
  budgetSpent: z.number(),
  budgetRe...


id: constant:5fc617eb1f7bbac46436418881934867
kind: constant
name: setBudgetGuardTool
qualified_name: setBudgetGuardTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_set_budget_guard",
  description:
    "Sets a budget guard that limits spending...


id: constant:26401415b514fa5e099200f0e2dc2556
kind: constant
name: setRoutingStrategyInput
qualified_name: setRoutingStrategyInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  comboId: z.string().describe("Combo ID or name to update"),
  strategy: z.enum(ROUTING_...


id: constant:3be971c97c1b8095029f3dc4aa8fb5a5
kind: constant
name: setRoutingStrategyTool
qualified_name: setRoutingStrategyTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_set_routing_strategy",
  description:
    "Updates a combo routing strategy (pr...


id: constant:348c04ae88bf88d7db71c24d287fbeb0
kind: constant
name: setResilienceProfileInput
qualified_name: setResilienceProfileInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  profile: z
    .enum(["aggressive", "balanced", "conservative"])
    .describe("Resilie...


id: constant:432a85e184279c77ce6d58e869e5d35b
kind: constant
name: setResilienceProfileOutput
qualified_name: setResilienceProfileOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  applied: z.boolean(),
  settings: z.object({
    circuitBreakerThreshold: z.number(),
 ...


id: constant:8ddc304b09204245a1fad9651c57e93d
kind: constant
name: setResilienceProfileTool
qualified_name: setResilienceProfileTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_set_resilience_profile",
  description:
    "Applies a resilience profile that ...


id: constant:a4292e215756b5e51a4d42b55df2ee09
kind: constant
name: testComboInput
qualified_name: testComboInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  comboId: z.string().describe("ID of the combo to test"),
  testPrompt: z.string().max(5...


id: constant:07505efa9ed15fad38a6f82357b8b09e
kind: constant
name: testComboOutput
qualified_name: testComboOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  results: z.array(
    z.object({
      provider: z.string(),
      model: z.string(),
 ...


id: constant:31802eb715b8cf6b505066bdbcc3db66
kind: constant
name: testComboTool
qualified_name: testComboTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_test_combo",
  description:
    "Tests a combo by sending a short test prompt t...


id: constant:6011b2a9d464f1a37e865c95df40d547
kind: constant
name: getProviderMetricsInput
qualified_name: getProviderMetricsInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  provider: z.string().describe("Provider name (e.g., 'claude', 'gemini-cli', 'codex')"),...


id: constant:ead581b4151ccb820b99cf2f9d0ed275
kind: constant
name: getProviderMetricsOutput
qualified_name: getProviderMetricsOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  provider: z.string(),
  successRate: z.number(),
  requestCount: z.number(),
  avgLaten...


id: constant:b2b116d4d52789f5d1b4c56f424ff059
kind: constant
name: getProviderMetricsTool
qualified_name: getProviderMetricsTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_get_provider_metrics",
  description:
    "Returns detailed performance metrics...


id: constant:a2815535b57c0fe40368bf2b2b8ee1b8
kind: constant
name: bestComboForTaskInput
qualified_name: bestComboForTaskInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  taskType: z
    .enum(["coding", "review", "planning", "analysis", "debugging", "docume...


id: constant:85178c9a15238e7b691bab904f9fd6c3
kind: constant
name: bestComboForTaskOutput
qualified_name: bestComboForTaskOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  recommendedCombo: z.object({
    id: z.string(),
    name: z.string(),
    reason: z.st...


id: constant:d7387442706d990cbbdc2b6a1d01dc88
kind: constant
name: bestComboForTaskTool
qualified_name: bestComboForTaskTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_best_combo_for_task",
  description:
    "Recommends the best combo for a given...


id: constant:9130741f796e7fc045cd223e5851f77a
kind: constant
name: explainRouteOutput
qualified_name: explainRouteOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  requestId: z.string(),
  decision: z.object({
    comboUsed: z.string(),
    providerSe...


id: constant:0eedf49e0d89543da4a2857740044733
kind: constant
name: explainRouteTool
qualified_name: explainRouteTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_explain_route",
  description:
    "Explains why a specific request was routed ...


id: constant:dce6516b77197e24ea38b014ba545f5b
kind: constant
name: getSessionSnapshotOutput
qualified_name: getSessionSnapshotOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  sessionStart: z.string(),
  duration: z.string(),
  requestCount: z.number(),
  costTot...


id: constant:fda1e078a4c3e679c0aa3c4166254d1e
kind: constant
name: getSessionSnapshotTool
qualified_name: getSessionSnapshotTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_get_session_snapshot",
  description:
    "Returns a snapshot of the current wo...


id: constant:a459c73ed13743776f42e20b561f6022
kind: constant
name: dbHealthCheckInput
qualified_name: dbHealthCheckInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  autoRepair: z
    .boolean()
    .optional()
    .describe("When true, runs the databas...


id: constant:1361293e56cdf03ef49d9d2984cc62e1
kind: constant
name: dbHealthCheckOutput
qualified_name: dbHealthCheckOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  isHealthy: z.boolean(),
  issues: z.array(
    z.object({
      type: z.enum([
        ...


id: constant:5c122103132ffdc870b100829bcb634f
kind: constant
name: dbHealthCheckTool
qualified_name: dbHealthCheckTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_db_health_check",
  description:
    "Diagnoses OmniRoute database drift such a...


id: constant:7812065c7fe18ecf8f84837cbe78c43f
kind: constant
name: syncPricingInput
qualified_name: syncPricingInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  sources: z
    .array(z.string())
    .optional()
    .describe("External pricing sourc...


id: constant:56f0e1833b78bf8b6d8dad9245b809ed
kind: constant
name: syncPricingOutput
qualified_name: syncPricingOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  success: z.boolean(),
  modelCount: z.number(),
  providerCount: z.number(),
  source: ...


id: constant:a0d62d658e1debf47b0cf611f23fab52
kind: constant
name: syncPricingTool
qualified_name: syncPricingTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
    name: "omniroute_sync_pricing",
    description:
      "Syncs pricing data from external sourc...


id: constant:957bafa0b7a029cb767b4c1876a2d71b
kind: constant
name: cacheStatsOutput
qualified_name: cacheStatsOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  semanticCache: z.object({
    memoryEntries: z.number(),
    dbEntries: z.number(),
   ...


id: constant:8df99245b925643ceb24ca399889778c
kind: constant
name: cacheStatsTool
qualified_name: cacheStatsTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_cache_stats",
  description:
    "Returns cache statistics including semantic c...


id: constant:669b8fef4020c012d16095ad195a0ce2
kind: constant
name: cacheFlushInput
qualified_name: cacheFlushInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  signature: z.string().optional().describe("Specific cache signature to invalidate"),
  ...


id: constant:e6ff1c99f18e5143d8ece9e81f998054
kind: constant
name: cacheFlushOutput
qualified_name: cacheFlushOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  ok: z.boolean(),
  invalidated: z.number().optional(),
  scope: z.string().optional(),
...


id: constant:bc5679a94447b6e211f6d50ad10c5bb9
kind: constant
name: cacheFlushTool
qualified_name: cacheFlushTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_cache_flush",
  description:
    "Flush cache entries. Provide signature to inv...


id: constant:dfd47aecfbb8ee48c012f616abd9e91e
kind: constant
name: compressionStatusOutput
qualified_name: compressionStatusOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  enabled: z.boolean(),
  strategy: z.string(),
  settings: z.object({
    maxTokens: z.n...


id: constant:a90e758a7087f6ea2ed20fd1955e62a1
kind: constant
name: compressionStatusTool
qualified_name: compressionStatusTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_compression_status",
  description:
    "Returns current compression configurat...


id: constant:e0471b54e331f74956b0bce109f86867
kind: constant
name: compressionConfigureInput
qualified_name: compressionConfigureInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  enabled: z.boolean().optional(),
  strategy: z
    .enum(["off", "lite", "standard", "a...


id: constant:5ca18f61a7267dd8b492433ae3c12c61
kind: constant
name: compressionConfigureOutput
qualified_name: compressionConfigureOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  success: z.boolean(),
  updated: z.record(z.string(), z.unknown()),
  settings: z.objec...


id: constant:657bf08cae9cf91d9a6db9edd5f6d223
kind: constant
name: compressionConfigureTool
qualified_name: compressionConfigureTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_compression_configure",
  description:
    "Configure compression settings at r...


id: constant:a15bd6473bae7e5a7a0310caf0889849
kind: constant
name: setCompressionEngineInput
qualified_name: setCompressionEngineInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  engine: z.enum(["off", "caveman", "rtk", "stacked"]).optional(),
  cavemanIntensity: z....


id: constant:59881522ce73069540def669d56b47e0
kind: constant
name: setCompressionEngineTool
qualified_name: setCompressionEngineTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_set_compression_engine",
  description: "Set the active compression engine and ...


id: constant:3928ba7ed7e36fb6d561c44e093d86ee
kind: constant
name: listCompressionCombosTool
qualified_name: listCompressionCombosTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_list_compression_combos",
  description: "List compression combos and their eng...


id: constant:a4df77352c19bacd7191d69019ba8529
kind: constant
name: compressionComboStatsInput
qualified_name: compressionComboStatsInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  comboId: z.string().optional(),
  since: z.enum(["24h", "7d", "30d", "all"]).optional()...


id: constant:28c57f58cba067f964b6fc8b5008ec34
kind: constant
name: compressionComboStatsTool
qualified_name: compressionComboStatsTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_compression_combo_stats",
  description: "Get compression analytics grouped by ...


id: constant:7cd41d26f8e40267472b6d35917abda9
kind: constant
name: oneproxyFetchInput
qualified_name: oneproxyFetchInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  protocol: z.string().optional().describe("Filter by protocol: http, https, socks4, sock...


id: constant:f5932e55f700edd16bf32c55c82cc6cc
kind: constant
name: oneproxyFetchOutput
qualified_name: oneproxyFetchOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  items: z.array(
    z.object({
      id: z.string(),
      host: z.string(),
      port...


id: constant:a95b26b0cd7182a19aaadef6296783cd
kind: constant
name: oneproxyFetchTool
qualified_name: oneproxyFetchTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_oneproxy_fetch",
  description:
    "Fetch free proxies from the 1proxy marketp...


id: constant:a3038de4c47f9349b5439f71ef3c1d1e
kind: constant
name: oneproxyRotateInput
qualified_name: oneproxyRotateInput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  strategy: z
    .enum(["random", "quality", "sequential"])
    .optional()
    .describ...


id: constant:185953ebefce20d8eb07715f234bfccb
kind: constant
name: oneproxyRotateOutput
qualified_name: oneproxyRotateOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  id: z.string(),
  host: z.string(),
  port: z.number(),
  type: z.string(),
  countryCo...


id: constant:8e7077755cae75aae910a61db0c8cdde
kind: constant
name: oneproxyRotateTool
qualified_name: oneproxyRotateTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_oneproxy_rotate",
  description:
    "Get the next available free proxy from th...


id: constant:03c9d5db22739587aa32ea79d3ffbd08
kind: constant
name: oneproxyStatsOutput
qualified_name: oneproxyStatsOutput
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= z.object({
  stats: z.object({
    total: z.number(),
    active: z.number(),
    avgQuality: z.numb...


id: constant:6dcb03b4968083bd2c9676900e2d1a89
kind: constant
name: oneproxyStatsTool
qualified_name: oneproxyStatsTool
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= {
  name: "omniroute_oneproxy_stats",
  description:
    "Returns 1proxy sync status and statistics:...


id: constant:748befd3731697056abdd2064c96deb9
kind: constant
name: MCP_TOOLS
qualified_name: MCP_TOOLS
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= [
  getHealthTool,
  listCombosTool,
  getComboMetricsTool,
  switchComboTool,
  checkQuotaTool,
  r...


id: constant:90f4e8934137635326fa89f740a17429
kind: constant
name: MCP_TOOL_MAP
qualified_name: MCP_TOOL_MAP
file_path: open-sse/mcp-server/schemas/tools.ts
language: typescript
signature:
= Object.fromEntries(MCP_TOOLS.map((t) => [t.name, t])) as Record<
  string,
  (typeof MCP_TOOLS)[numb...


id: function:a69de0094db7f2bddfec8e4a26bf1f3a
kind: function
name: resolveCallerScopeContext
qualified_name: resolveCallerScopeContext
file_path: open-sse/mcp-server/scopeEnforcement.ts
language: typescript
signature:
(
  extra: McpToolExtraLike | undefined,
  fallbackScopes: readonly string[] = []
): CallerScopeContext


id: function:938b5ea3dcae202d7a3c11f1ed0cb89d
kind: function
name: evaluateToolScopes
qualified_name: evaluateToolScopes
file_path: open-sse/mcp-server/scopeEnforcement.ts
language: typescript
signature:
(
  toolName: string,
  callerScopes: readonly string[],
  enforceScopes: boolean
): ScopeCheckResult


id: import:67393aea5bdab339803b6d80558a79a8
kind: import
name: ../../src/lib/combos/steps.ts
qualified_name: ../../src/lib/combos/steps.ts
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
import {
  getComboModelProvider,
  getComboModelString,
  getComboStepTarget,
} from "../../src/lib/combos/steps.ts";


id: import:0a2b448674a7bfd2f3f9dc7b959f74ea
kind: import
name: ./schemas/tools.ts
qualified_name: ./schemas/tools.ts
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
import {
  MCP_TOOLS,
  getHealthInput,
  listCombosInput,
  getComboMetricsInput,
  switchComboInput,
  checkQuotaInput,
  routeRequestInput,
  costReportInput,
  listModelsCatalogInput,
  webSearchInput,
  simulateRouteInput,
  setBudgetGuardInput,
  setRoutingStrategyInput,
  setResilienceProfileInput,
  testComboInput,
  getProviderMetricsInput,
  bestComboForTaskInput,
  explainRouteInput,
  getSessionSnapshotInput,
  dbHealthCheckInput,
  syncPricingInput,
  cacheStatsInput,
  cacheFlushInput,
  oneproxyFetchInput,
  oneproxyRotateInput,
  oneproxyStatsInput,
} from "./schemas/tools.ts";


id: import:2bb6888f7370a2cc9ad2a40ac005fe1e
kind: import
name: ./scopeEnforcement.ts
qualified_name: ./scopeEnforcement.ts
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
import {
  evaluateToolScopes,
  resolveCallerScopeContext,
  type McpToolExtraLike,
} from "./scopeEnforcement.ts";


id: import:053357a317d632a726a8d9a64a55669c
kind: import
name: ./tools/advancedTools.ts
qualified_name: ./tools/advancedTools.ts
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
import {
  handleSimulateRoute,
  handleSetBudgetGuard,
  handleSetRoutingStrategy,
  handleSetResilienceProfile,
  handleTestCombo,
  handleGetProviderMetrics,
  handleBestComboForTask,
  handleExplainRoute,
  handleGetSessionSnapshot,
  handleDbHealthCheck,
  handleSyncPricing,
  handleCacheStats,
  handleCacheFlush,
  handleOneproxyFetch,
  handleOneproxyRotate,
  handleOneproxyStats,
} from "./tools/advancedTools.ts";


id: import:ba7d2d63ec7b8466f368ae6c2f487589
kind: import
name: ../services/compression/engines/mcpAccessibility/constants.ts
qualified_name: ../services/compression/engines/mcpAccessibility/constants.ts
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
import {
  DEFAULT_MCP_ACCESSIBILITY_CONFIG,
  type McpAccessibilityConfig,
} from "../services/compression/engines/mcpAccessibility/constants.ts";


id: constant:4d8a189a952e8683890d6e4019783f4b
kind: constant
name: MCP_ALLOWED_SCOPES
qualified_name: MCP_ALLOWED_SCOPES
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
= new Set(
  (process.env.OMNIROUTE_MCP_SCOPES || "")
    .split(",")
    .map((s) => s.trim())
    .f...


id: constant:d9f4a82863a63eefa112d13a9e4cad05
kind: constant
name: TOTAL_MCP_TOOL_COUNT
qualified_name: TOTAL_MCP_TOOL_COUNT
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
= MCP_TOOLS.length +
  Object.keys(memoryTools).length +
  Object.keys(skillTools).length +
  gamifica...


id: function:2e107c3956e1501113c8f6b63813f6fa
kind: function
name: withScopeEnforcement
qualified_name: withScopeEnforcement
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
(
  toolName: string,
  handler: (args: unknown, extra?: McpToolExtraLike) => Promise<TextToolResult>
)


id: function:40180ee8961c33f067568cb719739318
kind: function
name: handleRouteRequest
qualified_name: handleRouteRequest
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
(args: {
  model: string;
  messages: Array<{ role: string; content: string }>;
  combo?: string;
  budget?: number;
  role?: string;
  stream?: boolean;
})


id: function:88e39415e7aaf4b751faa50109d3a20c
kind: function
name: handleWebSearch
qualified_name: handleWebSearch
file_path: open-sse/mcp-server/server.ts
language: typescript
signature:
(args: {
  query: string;
  max_results?: number;
  search_type?: "web" | "news";
  provider?:
    | "serper-search"
    | "brave-search"
    | "perplexity-search"
    | "exa-search"
    | "tavily-search"
    | "google-pse-search"
    | "linkup-search"
    | "searchapi-search"
    | "searxng-search";
})


id: import:5fe0233e7d085615b0f70f569ad97315
kind: import
name: ../../../src/lib/combos/steps.ts
qualified_name: ../../../src/lib/combos/steps.ts
file_path: open-sse/mcp-server/tools/advancedTools.ts
language: typescript
signature:
import {
  getComboModelProvider,
  getComboModelString,
  getComboStepTarget,
} from "../../../src/lib/combos/steps.ts";


id: import:9f6dbd95b9f22f1fb8ee9edce67b381e
kind: import
name: ../../../src/shared/constants/routingStrategies.ts
qualified_name: ../../../src/shared/constants/routingStrategies.ts
file_path: open-sse/mcp-server/tools/advancedTools.ts
language: typescript
signature:
import type {
  AutoRoutingStrategyValue,
  RoutingStrategyValue,
} from "../../../src/shared/constants/routingStrategies.ts";


id: constant:88772085f5109b1acb73c1aa0e83f05c
kind: constant
name: RESILIENCE_PROFILES
qualified_name: RESILIENCE_PROFILES
file_path: open-sse/mcp-server/tools/advancedTools.ts
language: typescript
signature:
= {
  aggressive: {
    requestQueue: {
      requestsPerMinute: 180,
      minTimeBetweenRequestsMs: ...


id: constant:74e2a26c227ff3bf1df6469eca46e4f9
kind: constant
name: TASK_FITNESS
qualified_name: TASK_FITNESS
file_path: open-sse/mcp-server/tools/advancedTools.ts
language: typescript
signature:
= {
  coding: { preferred: ["claude", "deepseek", "codex"], traits: ["fast", "code-optimized"] },
  re...


id: function:f0e941358c5c0c14e3eab8e543c975d6
kind: function
name: handleSetBudgetGuard
qualified_name: handleSetBudgetGuard
file_path: open-sse/mcp-server/tools/advancedTools.ts
language: typescript
signature:
(args: {
  maxCost: number;
  action: "degrade" | "block" | "alert";
  degradeToTier?: "cheap" | "free";
})


id: function:ede7c1bc326c5fc07ec79daf37cdc88d
kind: function
name: handleSetRoutingStrategy
qualified_name: handleSetRoutingStrategy
file_path: open-sse/mcp-server/tools/advancedTools.ts
language: typescript
signature:
(args: {
  comboId: string;
  strategy: RoutingStrategyValue;
  autoRoutingStrategy?: AutoRoutingStrategyValue;
})


id: import:482f8401c0824a0bec98e199c719445f
kind: import
name: ../../../src/lib/db/compression.ts
qualified_name: ../../../src/lib/db/compression.ts
file_path: open-sse/mcp-server/tools/compressionTools.ts
language: typescript
signature:
import {
  getCompressionSettings,
  updateCompressionSettings,
} from "../../../src/lib/db/compression.ts";


id: import:d4ad6086432323faa6f16a473a8ff2b4
kind: import
name: ../descriptionCompressor.ts
qualified_name: ../descriptionCompressor.ts
file_path: open-sse/mcp-server/tools/compressionTools.ts
language: typescript
signature:
import {
  getMcpDescriptionCompressionStats,
  snapshotMcpDescriptionCompressionStats,
} from "../descriptionCompressor.ts";


id: function:e42b87789a3dfbaa8d2d0a4afb248624
kind: function
name: handleCompressionStatus
qualified_name: handleCompressionStatus
file_path: open-sse/mcp-server/tools/compressionTools.ts
language: typescript
signature:
(
  args: Record<string, never>,
  extra?: McpToolExtraLike
): Promise<{
  enabled: boolean;
  strategy: string;
  settings: {
    maxTokens: number;
    autoTriggerMode: string;
    targetRatio: number;
    preserveSystemPrompt: boolean;
    mcpDescriptionCompressionEnabled: boolean;
  };
  analytics: {
    totalRequests: number;
    compressedRequests: number;
    tokensSaved: number;
    avgCompressionRatio: number;
    byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;
    byEngine: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;
    byCompressionCombo: Record<string, { count: number; tokensSaved: number }>;
    validationFallbacks: number;
    requestsWithReceipts: number;
    realUsage: {
      requestsWithReceipts: number;
      promptTokens: number;
      completionTokens: number;
      totalTokens: number;
      cacheReadTokens: number;
      cacheWriteTokens: number;
      estimatedUsdSaved: number;
      bySource: Record<string, number>;
    };
    mcpDescriptionCompression: {
      descriptionsCompressed: number;
      charsBefore: number;
      charsAfter: number;
      charsSaved: number;
      estimatedTokensSaved: number;
      persistedEstimatedTokensSaved: number;
      persistedSnapshots: number;
      source: "mcp_metadata_estimate";
      notProviderUsage: true;
    };
  };
  cacheStats: {
    hits: number;
    misses: number;
    hitRate: string;
    tokensSaved: number;
  } | null;
}>


id: function:bacece546b650b7925c5cac3c6779fa2
kind: function
name: handleCompressionConfigure
qualified_name: handleCompressionConfigure
file_path: open-sse/mcp-server/tools/compressionTools.ts
language: typescript
signature:
(
  args: {
    enabled?: boolean;
    strategy?: string;
    autoTriggerMode?: string;
    maxTokens?: number;
    targetRatio?: number;
    preserveSystemPrompt?: boolean;
    mcpDescriptionCompressionEnabled?: boolean;
  },
  extra?: McpToolExtraLike
): Promise<{
  success: boolean;
  updated: Record<string, unknown>;
  settings: {
    enabled: boolean;
    strategy: string;
    autoTriggerMode: string;
    maxTokens: number;
    targetRatio: number;
    preserveSystemPrompt: boolean;
    mcpDescriptionCompressionEnabled: boolean;
  };
}>


id: import:f879fa2a00eff91fd2b6821391169eba
kind: import
name: ../schemas/tools.ts
qualified_name: ../schemas/tools.ts
file_path: open-sse/mcp-server/tools/compressionTools.ts
language: typescript
signature:
import {
  compressionStatusInput,
  compressionConfigureInput,
  setCompressionEngineInput,
  listCompressionCombosInput,
  compressionComboStatsInput,
} from "../schemas/tools.ts";


id: function:ab7014b2fb232bfa2c24267bf130885d
kind: function
name: handleSetCompressionEngine
qualified_name: handleSetCompressionEngine
file_path: open-sse/mcp-server/tools/compressionTools.ts
language: typescript
signature:
(
  args: z.infer<typeof setCompressionEngineInput>
): Promise<{ success: boolean; settings: Record<string, unknown> }>


id: constant:8774173a989377a33f78a14657fe6682
kind: constant
name: compressionTools
qualified_name: compressionTools
file_path: open-sse/mcp-server/tools/compressionTools.ts
language: typescript
signature:
= {
  omniroute_compression_status: {
    name: "omniroute_compression_status",
    description:
     ...


id: constant:3397a74c19f4998733e2c2f7753b4c2b
kind: constant
name: gamificationTools
qualified_name: gamificationTools
file_path: open-sse/mcp-server/tools/gamificationTools.ts
language: typescript
signature:
= [
  {
    name: "gamification_leaderboard",
    description: "Get leaderboard rankings for a scope (...


id: constant:37f0105101f6b0ed77971059e2b30bfa
kind: constant
name: MemorySearchSchema
qualified_name: MemorySearchSchema
file_path: open-sse/mcp-server/tools/memoryTools.ts
language: typescript
signature:
= z.object({
  apiKeyId: z.string(),
  query: z.string().optional(),
  type: z.enum(["factual", "episo...


id: constant:0d51d658a3cc441954fffe834f20b295
kind: constant
name: MemoryAddSchema
qualified_name: MemoryAddSchema
file_path: open-sse/mcp-server/tools/memoryTools.ts
language: typescript
signature:
= z.object({
  apiKeyId: z.string(),
  sessionId: z.string().optional(),
  type: z.enum(["factual", "e...


id: constant:f424d3f743a7d343d0636b5d5a7b088c
kind: constant
name: MemoryClearSchema
qualified_name: MemoryClearSchema
file_path: open-sse/mcp-server/tools/memoryTools.ts
language: typescript
signature:
= z.object({
  apiKeyId: z.string(),
  type: z.enum(["factual", "episodic", "procedural", "semantic"])...


id: constant:4c6d15e7cac128efd5e26891666c9d64
kind: constant
name: memoryTools
qualified_name: memoryTools
file_path: open-sse/mcp-server/tools/memoryTools.ts
language: typescript
signature:
= {
  omniroute_memory_search: {
    name: "omniroute_memory_search",
    description: "Search memorie...


id: constant:61c1abdc1a81e647930e3c230df438fe
kind: constant
name: SkillListSchema
qualified_name: SkillListSchema
file_path: open-sse/mcp-server/tools/skillTools.ts
language: typescript
signature:
= z.object({
  apiKeyId: z.string().optional(),
  name: z.string().optional(),
  enabled: z.boolean()....


id: constant:b75026977391d3873ae3d84f2f5257f7
kind: constant
name: SkillExecuteSchema
qualified_name: SkillExecuteSchema
file_path: open-sse/mcp-server/tools/skillTools.ts
language: typescript
signature:
= z.object({
  apiKeyId: z.string(),
  skillName: z.string(),
  input: z.record(z.string(), z.unknown(...


id: constant:4f04551f53d27a3f2ce5812ef029bcaa
kind: constant
name: skillTools
qualified_name: skillTools
file_path: open-sse/mcp-server/tools/skillTools.ts
language: typescript
signature:
= {
  omniroute_skills_list: {
    name: "omniroute_skills_list",
    description: "List all registere...


id: constant:ff6ee0eeda51e23326e1737e399bc61a
kind: constant
name: PROXY_ENV_KEYS
qualified_name: PROXY_ENV_KEYS
file_path: open-sse/services/__tests__/chatgptTlsClient.test.ts
language: typescript
signature:
= [
  "OMNIROUTE_TLS_PROXY_URL",
  "HTTPS_PROXY",
  "https_proxy",
  "HTTP_PROXY",
  "http_proxy",
  "...


id: import:59e73f9626fe15f50d083da445743bc8
kind: import
name: ../manifestAdapter.ts
qualified_name: ../manifestAdapter.ts
file_path: open-sse/services/__tests__/manifestAdapter.test.ts
language: typescript
signature:
import {
  generateRoutingHints,
  compareByCostEffectiveness,
  estimateRequestCost,
} from "../manifestAdapter.ts";


id: import:db6ccfbc72a9ce453cec60488fb5801e
kind: import
name: ../specificityDetector.ts
qualified_name: ../specificityDetector.ts
file_path: open-sse/services/__tests__/specificityDetector.test.ts
language: typescript
signature:
import {
  analyzeSpecificity,
  getSpecificityLevel,
  getRecommendedMinTier,
  isHighSpecificity,
  isLowSpecificity,
} from "../specificityDetector.ts";


id: import:3ddaa7e272a7b8b52580fc1ac54f3695
kind: import
name: ../tierResolver.ts
qualified_name: ../tierResolver.ts
file_path: open-sse/services/__tests__/tierResolver.test.ts
language: typescript
signature:
import {
  classifyTier,
  setTierConfig,
  clearTierCache,
  getTierStats,
  classifyTiers,
} from "../tierResolver.ts";


id: import:03c51a5d9d652ce84f47292e5fb4acba
kind: import
name: ../config/constants.ts
qualified_name: ../config/constants.ts
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
import {
  BACKOFF_STEPS_MS,
  PROVIDER_PROFILES,
  RateLimitReason,
  HTTP_STATUS,
} from "../config/constants.ts";


id: import:d6a77212ddd3f7c14304d5dbc7d28125
kind: import
name: ../config/errorConfig.ts
qualified_name: ../config/errorConfig.ts
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
import {
  BACKOFF_CONFIG,
  COOLDOWN_MS,
  calculateBackoffCooldown,
  findMatchingErrorRule,
  matchErrorRuleByText,
  matchErrorRuleByStatus,
} from "../config/errorConfig.ts";


id: import:c91f05a6a730598159c33a97e48dfff7
kind: import
name: ../../src/lib/resilience/settings
qualified_name: ../../src/lib/resilience/settings
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
import {
  DEFAULT_RESILIENCE_SETTINGS,
  resolveResilienceSettings,
} from "../../src/lib/resilience/settings";


id: import:83a1ec729d3a20408506facc607b0a4c
kind: import
name: ../../src/shared/utils/circuitBreaker
qualified_name: ../../src/shared/utils/circuitBreaker
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
import {
  getAllCircuitBreakerStatuses,
  getCircuitBreaker,
  STATE,
} from "../../src/shared/utils/circuitBreaker";


id: constant:cef20c6a4b1da0b5c54c10d86073e23d
kind: constant
name: PROVIDER_FAILURE_ERROR_CODES
qualified_name: PROVIDER_FAILURE_ERROR_CODES
file_path: open-sse/services/accountFallback.ts
language: typescript
signature: = new Set([408, 500, 502, 503, 504])
docstring:
Provider-level failure tracking for circuit breaker behavior
Error codes that count toward provider-level failure threshold
429 (rate limit) is intentionally excluded: rate limits are connection-scoped
and handled via Connection Cooldown, not provider-wide circuit breaker.
Counting 429 toward provider failure causes cascading provider trips at scale
when many connections hit rate limits simultaneously (Issue #1846).


id: constant:9bb5948df97b6b3d41aee372f142e107
kind: constant
name: CONNECTION_FAILURE_DEDUP_MS
qualified_name: CONNECTION_FAILURE_DEDUP_MS
file_path: open-sse/services/accountFallback.ts
language: typescript
signature: = 5000
docstring:
Per-connection failure deduplication: prevents rapid-fire failures from the
same connection from counting multiple times toward the provider breaker.


id: constant:5e51cbee9df59a3fe480b8b1ba302641
kind: constant
name: ACCOUNT_DEACTIVATED_SIGNALS
qualified_name: ACCOUNT_DEACTIVATED_SIGNALS
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
= [
  "account_deactivated",
  "account has been deactivated",
  "account has been disabled",
  "your ...


id: constant:d4e7ea187e3074bc9e11ff03b33b5a1a
kind: constant
name: CREDITS_EXHAUSTED_SIGNALS
qualified_name: CREDITS_EXHAUSTED_SIGNALS
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
= [
  "insufficient_quota",
  "billing_hard_limit_reached",
  "exceeded your current quota",
  "credit...


id: constant:65f894675898f1bbe0403bfd1bd22dfd
kind: constant
name: OAUTH_INVALID_TOKEN_SIGNALS
qualified_name: OAUTH_INVALID_TOKEN_SIGNALS
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
= [
  "invalid authentication credentials",
  "oauth 2",
  "login cookie",
  "valid authentication cre...


id: constant:3e95c84b4980493b8fcc861abf3fd689
kind: constant
name: CONTEXT_OVERFLOW_PATTERNS
qualified_name: CONTEXT_OVERFLOW_PATTERNS
file_path: open-sse/services/accountFallback.ts
language: typescript
docstring:
Context overflow patterns — the prompt exceeds the model's maximum context length.
Different providers phrase this differently. Used to decide whether a 400 error
should trigger combo fallback (a different model may have a larger context window).

signature:
= [
  /\binput is too long\b/i,
  /\binput too long\b/i,
  /\bcontext.*(too long|exceeded|overflow|lim...


id: constant:5e25cf2229e7bdbb4b079d0bde1b22d9
kind: constant
name: MODEL_ACCESS_DENIED_CODES
qualified_name: MODEL_ACCESS_DENIED_CODES
file_path: open-sse/services/accountFallback.ts
language: typescript
docstring:
Structured error codes that reliably indicate model access denied
(more reliable than regex on human-readable messages).
OpenAI:  { error: { code: "model_not_found", ... } }
Anthropic: { error: { type: "not_found_error", ... } }

signature:
= new Set([
  "model_not_found", // OpenAI, OpenAI-compatible (Kiro, Together, Fireworks, etc.)
  "dep...


id: constant:a0afbe5410c3989be520772a4012d2ce
kind: constant
name: MODEL_ACCESS_AMBIGUOUS_TYPES
qualified_name: MODEL_ACCESS_AMBIGUOUS_TYPES
file_path: open-sse/services/accountFallback.ts
language: typescript
signature: = new Set([ "permission_error", // Anthropic: could be model access OR key/org/feature scope ])
docstring:
Anthropic's permission_error is NOT exclusively model-access related: it also
covers API-key scope, organization restrictions and feature gating. Treating it
as model-access-denied unconditionally would make a genuinely auth-restricted key
silently exhaust every combo target and hide the real error from the caller.
So it only counts when the message text confirms it refers to the model.


id: constant:ab4dce3ede5f2b051b339725aff7daa3
kind: constant
name: MODEL_ACCESS_DENIED_PATTERNS
qualified_name: MODEL_ACCESS_DENIED_PATTERNS
file_path: open-sse/services/accountFallback.ts
language: typescript
docstring:
Model access patterns — the account does not have access to the requested model
but a different account (e.g. PRO vs free tier) may support it.

signature:
= [
  /\binvalid model\b/i,
  /\bmodel.*not.*(?:available|found|supported|accessible)\b/i,
  /\bmodel....


id: constant:f454f7c700cdb7da6893b26053502aeb
kind: constant
name: AUTH_CREDENTIAL_ERROR_PATTERNS
qualified_name: AUTH_CREDENTIAL_ERROR_PATTERNS
file_path: open-sse/services/accountFallback.ts
language: typescript
docstring:
Pure credential/authentication failures — the key or token itself is bad, which
is NOT a model-availability problem. Some providers phrase these as a 400 that
also mentions the model (e.g. "invalid api key for model X"), which would
otherwise trip MODEL_ACCESS_DENIED_PATTERNS above and trigger combo fallback
across every target, masking the real "fix your credential" error. When the
text clearly indicates a bad credential, the regex-based model-access detection
is suppressed (structured codes/types like model_not_found are unaffected).

signature:
= [
  /\b(?:invalid|incorrect|expired|missing|revoked)\s+api[\s_-]?key\b/i,
  /\bapi[\s_-]?key\s+(?:is...


id: constant:e9b2eb02327a81b985a489462b3aab06
kind: constant
name: MALFORMED_REQUEST_PATTERNS
qualified_name: MALFORMED_REQUEST_PATTERNS
file_path: open-sse/services/accountFallback.ts
language: typescript
docstring:
Malformed request patterns — the model rejected the message format but a different
provider/model in the combo may accept it.

signature:
= [
  /\bimproperly formed request\b/i,
  /\binvalid.*message.*format/i,
  /\bmessages must alternate\...


id: constant:5fa316842e73b1e65befae5d88fb0b81
kind: constant
name: modelLockouts
qualified_name: modelLockouts
file_path: open-sse/services/accountFallback.ts
language: typescript
signature: = new Map<string, ModelLockoutEntry>()
docstring:
─── Per-Model Lockout Tracking ─────────────────────────────────────────────
In-memory map: "provider:connectionId:model" → { reason, until, lockedAt }


id: function:1478897d87044202a6bb79db986e0781
kind: function
name: lockModel
qualified_name: lockModel
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  provider: string,
  connectionId: string,
  model: string | null | undefined,
  reason: string,
  cooldownMs: number,
  metadata: Partial<ModelLockoutEntry> = {}
): void


id: function:d37899b1bcc20c5d30f852ff1953b80f
kind: function
name: recordModelLockoutFailure
qualified_name: recordModelLockoutFailure
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  provider: string,
  connectionId: string,
  model: string,
  reason: string,
  status: number,
  fallbackCooldownMs: number,
  profile: ProviderProfile | null = null,
  options: { exactCooldownMs?: number | null } = {}
)


id: function:3e9831fbf614fb2f28bc1a6a0cff51e5
kind: function
name: hasPerModelQuota
qualified_name: hasPerModelQuota
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  provider: string | null | undefined,
  _model: string | null | undefined = null,
  connectionPassthroughModels?: boolean
): boolean


id: function:bf6fb0d6b3fd62467f700b352f9b2906
kind: function
name: lockModelIfPerModelQuota
qualified_name: lockModelIfPerModelQuota
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  provider: string,
  connectionId: string,
  model: string | null,
  reason: string,
  cooldownMs: number,
  connectionPassthroughModels?: boolean
): boolean


id: function:01a80c0fd258433f3eb78f9a982d20ab
kind: function
name: shouldMarkAccountExhaustedFrom429
qualified_name: shouldMarkAccountExhaustedFrom429
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  provider: string | null | undefined,
  model: string | null | undefined = null,
  connectionPassthroughModels?: boolean,
  failureKind?: FailureKind
): boolean


id: type_alias:7a2769b9ba20cab37a3e80e1fe062ae5
kind: type_alias
name: ProviderBreakerProfile
qualified_name: ProviderBreakerProfile
file_path: open-sse/services/accountFallback.ts
language: typescript
docstring:
─── Provider Breaker Compatibility Wrappers ────────────────────────────────
Legacy helpers now delegate to the shared provider circuit breaker.


id: function:5f26677da9cffa5618c255a99a56b968
kind: function
name: recordProviderFailure
qualified_name: recordProviderFailure
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  provider: string | null | undefined,
  log?: { warn?: (...args: unknown[]) => void },
  connectionId?: string | null,
  profile?: ProviderBreakerProfile | null
): void


id: function:6392b22374118dc67316cc671ff02180
kind: function
name: getProvidersInCooldown
qualified_name: getProvidersInCooldown
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(): Array<{
  provider: string;
  failureCount: number;
  cooldownRemainingMs: number | null;
  lastFailureAt: number | null;
}>


id: function:c470c441889591eb068a0324836f499f
kind: function
name: isProviderExhaustedReason
qualified_name: isProviderExhaustedReason
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(result: {
  reason?: string;
  creditsExhausted?: boolean;
  dailyQuotaExhausted?: boolean;
}): boolean


id: function:9973e3f8cd14e96936a46c813bc0f4e3
kind: function
name: checkFallbackError
qualified_name: checkFallbackError
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  status: number,
  errorText: string | null,
  backoffLevel: number = 0,
  _model: string | null = null,
  provider: string | null = null,
  headers: Headers | Record<string, string> | null = null,
  profileOverride: ProviderProfile | null = null,
  structuredError?: { code?: string | null; type?: string | null } | null
): {
  shouldFallback: boolean;
  cooldownMs: number;
  baseCooldownMs?: number;
  newBackoffLevel?: number;
  usedUpstreamRetryHint?: boolean;
  reason?: string;
  permanent?: boolean;
  creditsExhausted?: boolean;
  dailyQuotaExhausted?: boolean;
}


id: function:faf525d328650c90ab1b37dd401b4cd8
kind: function
name: applyErrorState
qualified_name: applyErrorState
file_path: open-sse/services/accountFallback.ts
language: typescript
signature:
(
  account: T,
  status: number,
  errorText: string | null,
  provider: string | null = null
): T | AccountState


id: function:8ee7d8879172afefbd882220f2ab4717
kind: function
name: acquire
qualified_name: acquire
file_path: open-sse/services/accountSemaphore.ts
language: typescript
signature:
(
  semaphoreKey: string,
  {
    maxConcurrency = null,
    timeoutMs = DEFAULT_TIMEOUT_MS,
    signal = null,
    maxQueueSize = DEFAULT_MAX_QUEUE_SIZE,
  }: AcquireAccountSemaphoreOptions = {}
): Promise<() => void>


id: constant:ba9c40f8a7a22c85ff1c234e57880c9c
kind: constant
name: CREDITS_EXHAUSTED_KEYWORDS
qualified_name: CREDITS_EXHAUSTED_KEYWORDS
file_path: open-sse/services/antigravity429Engine.ts
language: typescript
signature:
= [
  "google_one_ai",
  "insufficient credit",
  "insufficient credits",
  "not enough credit",
  "no...


id: import:88ecf157f2c710a5f0601cedb3000643
kind: import
name: @/shared/constants/antigravityClientProfile
qualified_name: @/shared/constants/antigravityClientProfile
file_path: open-sse/services/antigravityClientProfile.ts
language: typescript
signature:
import {
  DEFAULT_ANTIGRAVITY_CLIENT_PROFILE,
  normalizeAntigravityClientProfile,
  type AntigravityClientProfile,
} from "@/shared/constants/antigravityClientProfile";


id: import:4ccb079bfd1de5fd188fde82a0a95930
kind: import
name: ./antigravityIdentity.ts
qualified_name: ./antigravityIdentity.ts
file_path: open-sse/services/antigravityClientProfile.ts
language: typescript
signature:
import {
  deriveAntigravityMachineId,
  getAntigravityVscodeSessionId,
  type AntigravityCredentialsLike,
} from "./antigravityIdentity.ts";


id: import:53459fa3d086cd946f991091b9056fc8
kind: import
name: ./antigravityHeaders.ts
qualified_name: ./antigravityHeaders.ts
file_path: open-sse/services/antigravityClientProfile.ts
language: typescript
signature:
import {
  antigravityUserAgent,
  ANTIGRAVITY_CREDIT_PROBE_API_CLIENT,
  ANTIGRAVITY_NODE_API_CLIENT,
  getAntigravityLoadCodeAssistMetadata,
} from "./antigravityHeaders.ts";


id: function:c4c200232a2b7a598a6f6405f96ccddd
kind: function
name: getHarnessPlatformArch
qualified_name: getHarnessPlatformArch
file_path: open-sse/services/antigravityClientProfile.ts
language: typescript
signature:
(
  platform: NodeJS.Platform | string = getRuntimePlatform(),
  arch: NodeJS.Architecture | string = getRuntimeArch()
): string


id: function:40ddbc999968ee7da3348e755700fa82
kind: function
name: antigravityHarnessUserAgent
qualified_name: antigravityHarnessUserAgent
file_path: open-sse/services/antigravityClientProfile.ts
language: typescript
signature:
(
  version = getCachedAntigravityVersion(),
  platform: NodeJS.Platform | string = getRuntimePlatform(),
  arch: NodeJS.Architecture | string = getRuntimeArch()
): string


id: function:4b02f1e312b215d1bfaa9b8ac98f7bd0
kind: function
name: applyAntigravityClientProfileHeaders
qualified_name: applyAntigravityClientProfileHeaders
file_path: open-sse/services/antigravityClientProfile.ts
language: typescript
signature:
(
  headers: Record<string, string>,
  credentials: AntigravityProfileCredentials | null | undefined,
  body: unknown
): AntigravityClientProfile


id: constant:44c1c744673b84747b7be330aab2eb5b
kind: constant
name: HEADERS_TO_REMOVE
qualified_name: HEADERS_TO_REMOVE
file_path: open-sse/services/antigravityHeaderScrub.ts
language: typescript
docstring:
Antigravity header scrubbing.
Real Antigravity is a Node.js app. Its outbound HTTP requests never include
proxy tracing headers, Stainless SDK headers, or Chromium Sec-Ch-* headers.
Sending any of these reveals the request came through a third-party proxy.
Based on CLIProxyAPI's ScrubProxyAndFingerprintHeaders (misc/header_utils.go).

signature:
= [
  // Proxy tracing
  "x-forwarded-for",
  "x-forwarded-host",
  "x-forwarded-proto",
  "x-forwarde...


id: import:06dfb23a0d5cc0fbfb4f49a1d5c393f6
kind: import
name: ./antigravityVersion.ts
qualified_name: ./antigravityVersion.ts
file_path: open-sse/services/antigravityHeaders.ts
language: typescript
signature:
import {
  ANTIGRAVITY_FALLBACK_VERSION,
  getCachedAntigravityVersion,
  resolveAntigravityVersion,
} from "./antigravityVersion.ts";


id: type_alias:76eb748e356775ca47c05249902218b1
kind: type_alias
name: AntigravityHeaderProfile
qualified_name: AntigravityHeaderProfile
file_path: open-sse/services/antigravityHeaders.ts
language: typescript
docstring:
Antigravity header utilities.
Generates User-Agent strings and API client headers that match
the real Antigravity client flows.
Based on CLIProxyAPI's misc/header_utils.go.


id: function:2c9196d7c1d80bd7b863b3e3854fd0d1
kind: function
name: antigravityUserAgent
qualified_name: antigravityUserAgent
file_path: open-sse/services/antigravityHeaders.ts
language: typescript
signature:
(
  version = getCachedAntigravityVersion(),
  platform: NodeJS.Platform = process.platform
): string


id: constant:b4dfe2e84f96a2d444fdbd8a7fb68e69
kind: constant
name: ZWJ
qualified_name: ZWJ
file_path: open-sse/services/antigravityObfuscation.ts
language: typescript
signature: = "\u200d"
docstring:
Sensitive word obfuscation for Antigravity requests.
Obfuscates client tool names (OpenCode, Cursor, Claude Code, etc.) using
zero-width joiners so Google's backend can't grep for them in request logs.
Matching ZeroGravity's ZEROGRAVITY_SENSITIVE_WORDS and CLIProxyAPI's cloak system.


id: constant:41c9a9baae83c23f0eb5b13984ffe4a8
kind: constant
name: DEFAULT_WORDS
qualified_name: DEFAULT_WORDS
file_path: open-sse/services/antigravityObfuscation.ts
language: typescript
signature:
= [
  "opencode",
  "open-code",
  "cline",
  "roo-cline",
  "roo_cline",
  "cursor",
  "windsurf",
  ...


id: import:c9a875af7a590a0d564dc47a0db01856
kind: import
name: ./antigravityHeaders.ts
qualified_name: ./antigravityHeaders.ts
file_path: open-sse/services/antigravityProjectBootstrap.ts
language: typescript
signature:
import {
  getAntigravityHeaders,
  getAntigravityLoadCodeAssistMetadata,
} from "./antigravityHeaders.ts";


id: import:8602d014a9fb897b8e0fae4dcb560f17
kind: import
name: ./antigravityClientProfile.ts
qualified_name: ./antigravityClientProfile.ts
file_path: open-sse/services/antigravityProjectBootstrap.ts
language: typescript
signature:
import {
  getAntigravityBootstrapHeaders,
  type AntigravityClientProfile,
} from "./antigravityClientProfile.ts";


id: function:536b3f7509f7b144f71ab2ef436d0fb6
kind: function
name: tryLoadCodeAssist
qualified_name: tryLoadCodeAssist
file_path: open-sse/services/antigravityProjectBootstrap.ts
language: typescript
docstring:
Attempt loadCodeAssist against each known base URL in order.
Returns the discovered project id, or null if all endpoints fail.

signature:
(
  accessToken: string,
  fetchImpl: FetchLike,
  clientProfile: AntigravityClientProfile
): Promise<string | null>


id: function:f639146d8fac2e4b08e621bfc55f3751
kind: function
name: ensureAntigravityProjectAssigned
qualified_name: ensureAntigravityProjectAssigned
file_path: open-sse/services/antigravityProjectBootstrap.ts
language: typescript
signature:
(
  accessToken: string,
  fetchImpl: FetchLike = fetch,
  clientProfile: AntigravityClientProfile = "ide"
): Promise<string | undefined>


id: constant:a18b132795bad1f452a4309cb794c3dc
kind: constant
name: _keyIndexes
qualified_name: _keyIndexes
file_path: open-sse/services/apiKeyRotator.ts
language: typescript
signature: = new Map<string, number>()
docstring:
apiKeyRotator.ts — T07: API Key Round-Robin with Health Tracking
Rotates between a primary API key and extra API keys stored in
providerSpecificData.extraApiKeys[]. Uses round-robin by default.
Extra keys are stored as plain strings in providerSpecificData.extraApiKeys.
Example: { extraApiKeys: ["sk-abc...", "sk-def...", "sk-ghi..."] }
The in-memory rotation index resets on process restart, which is intentional —
it ensures even distribution across restarts without persistence overhead.
Health tracking: monitors per-key authentication failures. Keys that fail
3+ consecutive times are marked as "invalid" and skipped during rotation.
Health status is persisted in providerSpecificData.apiKeyHealth.
In-memory round-robin index per connection


id: constant:09e2e2412f446a63f5dcc8c6287ba682
kind: constant
name: _connectionExtraKeys
qualified_name: _connectionExtraKeys
file_path: open-sse/services/apiKeyRotator.ts
language: typescript
signature: = new Map<string, boolean>()
docstring:
Tracks which connections have extra API keys (for A3 guard in chatCore.ts)
Used to prevent disabling an entire connection when only one key fails.


id: interface:bad9da372b00587b520c1061cf49c078
kind: interface
name: KeyHealth
qualified_name: KeyHealth
file_path: open-sse/services/apiKeyRotator.ts
language: typescript
docstring:
In-memory health status (synced to DB on state changes)
Key format: "primary" | "extra_0" | "extra_1" | ...


id: function:5fcea8989f12c1d1b636ec011fcdf44f
kind: function
name: getOrCreateHealth
qualified_name: getOrCreateHealth
file_path: open-sse/services/apiKeyRotator.ts
language: typescript
signature: (connectionId: string, keyId: string): KeyHealth
docstring:
Mark as invalid after 2 consecutive failures
Get or create health status for a specific key within a connection scope.


id: function:f48269119676571883f26586c6363f09
kind: function
name: getValidApiKey
qualified_name: getValidApiKey
file_path: open-sse/services/apiKeyRotator.ts
language: typescript
signature:
(
  connectionId: string,
  primaryKey: string,
  extraKeys: string[] = [],
  health?: Record<string, KeyHealth>
): { key: string; keyId: string } | null


id: function:d4ec8973f495f97449a48aa16ae43e56
kind: function
name: getKeyHealthStats
qualified_name: getKeyHealthStats
file_path: open-sse/services/apiKeyRotator.ts
language: typescript
signature:
(
  connectionId: string,
  primaryKey: string,
  extraKeys: string[] = [],
  health?: Record<string, KeyHealth>
): {
  total: number;
  active: number;
  warning: number;
  invalid: number;
}


id: function:a238637d0182ed143c9678a964330b9d
kind: function
name: resolveKeyForRequest
qualified_name: resolveKeyForRequest
file_path: open-sse/services/apiKeyRotator.ts
language: typescript
signature:
(
  connectionId: string,
  primaryKey: string,
  extraKeys: string[],
  selectedKeyId: string | null
): { key: string; keyId: string } | null


id: import:67f587fc7e4e4bd9004239ff63f92068
kind: import
name: ../providerDiversity
qualified_name: ../providerDiversity
file_path: open-sse/services/autoCombo/__tests__/providerDiversity.test.ts
language: typescript
signature:
import {
  recordProviderUsage,
  calculateDiversityScore,
  getProviderDiversityBoost,
  getDiversityReport,
  resetDiversity,
  configureDiversity,
} from "../providerDiversity";


id: import:403eb0f136023fc98e397a14577624ea
kind: import
name: ./scoring
qualified_name: ./scoring
file_path: open-sse/services/autoCombo/engine.ts
language: typescript
signature:
import {
  scorePool,
  validateWeights,
  DEFAULT_WEIGHTS,
  type ScoringWeights,
  type ProviderCandidate,
  type ScoredProvider,
} from "./scoring";


id: function:c84fdab19f9c93360bad58d3b2cf7859
kind: function
name: selectProvider
qualified_name: selectProvider
file_path: open-sse/services/autoCombo/engine.ts
language: typescript
signature:
(
  config: AutoComboConfig,
  candidates: ProviderCandidate[],
  taskType: string = "default",
  promptMessages?: Array<{ role: string; content: unknown }>
): SelectionResult


id: constant:f37b44bfd32fd36272a68297880f4fe2
kind: constant
name: MODE_PACKS
qualified_name: MODE_PACKS
file_path: open-sse/services/autoCombo/modePacks.ts
language: typescript
signature:
= {
  // Prioritize latency → health. tierPriority replaces 0.05 from stability.
  // tierAffinity/spe...


id: import:980402ec9044aeef45662256c09ec6e7
kind: import
name: ../../../src/domain/pipeline.ts
qualified_name: ../../../src/domain/pipeline.ts
file_path: open-sse/services/autoCombo/pipelineRouter.ts
language: typescript
signature:
import {
  executePipeline,
  buildPipelineConfig,
  type TaskType,
  type PipelineResult,
  type FitnessTier,
} from "../../../src/domain/pipeline.ts";


id: constant:e7be1e7ba79b27ac15bc5d7ca8a7143b
kind: constant
name: FITNESS_TIERS
qualified_name: FITNESS_TIERS
file_path: open-sse/services/autoCombo/pipelineRouter.ts
language: typescript
signature:
= {
  "best-reasoning": { minFitness: 0.85 },
  cheapest: { maxFitness: 0.75 },
  moderate: { minFitne...


id: constant:afe905d0636c6f6e29d5f445579ab74c
kind: constant
name: INTENT_TO_TASK
qualified_name: INTENT_TO_TASK
file_path: open-sse/services/autoCombo/pipelineRouter.ts
language: typescript
docstring:
---------------------------------------------------------------------------
Intent → TaskType mapping
---------------------------------------------------------------------------

signature:
= {
  code: "code",
  math: "math",
  reasoning: "reasoning",
  creative: "creative",
  medium: "mediu...


id: function:304f912999e80221bbcd4ddf6a8d2a23
kind: function
name: resolveModelForTier
qualified_name: resolveModelForTier
file_path: open-sse/services/autoCombo/pipelineRouter.ts
language: typescript
signature: ( tier: FitnessTier, availableModels: string[], taskType: string ): string
docstring:
---------------------------------------------------------------------------
Model resolver — maps fitness tiers to actual model strings
---------------------------------------------------------------------------
Resolve a fitness tier to a concrete model string using the available models
from the combo's candidate pool. Falls back to sensible defaults.


id: function:68b8645795e49636559f1bfdeca1ea91
kind: function
name: createStageExecutor
qualified_name: createStageExecutor
file_path: open-sse/services/autoCombo/pipelineRouter.ts
language: typescript
docstring:
---------------------------------------------------------------------------
Stage executor factory
---------------------------------------------------------------------------
Create a stageExecutor that wraps handleChatCore for pipeline stage execution.
- Intermediate stages (stream:false): buffer the response, extract text
- Final stage (stream:true): return raw Response for SSE streaming
- Each stage gets a model override based on its fitness tier

signature:
(
  body: Record<string, unknown>,
  handleChatCore: (body: Record<string, unknown>, modelStr?: string) => Promise<Response>,
  log: { info: (...args: unknown[]) => void; warn: (...args: unknown[]) => void },
  availableModels: string[],
  taskType: string
): (args: StageExecutorArgs & { fitnessTier?: FitnessTier }) => Promise<StageExecutorResult>


id: function:da91b8c1cf6be2551983bca2a8276d18
kind: function
name: estimateTokens
qualified_name: estimateTokens
file_path: open-sse/services/autoCombo/pipelineRouter.ts
language: typescript
signature: (messages: Array<{ role: string; content: unknown }>): number
docstring:
---------------------------------------------------------------------------
Token estimation
---------------------------------------------------------------------------
Rough token estimate from message content (4 chars ≈ 1 token).


id: function:e670b99e32c588342d937694ab81d9b1
kind: function
name: handlePipelineCombo
qualified_name: handlePipelineCombo
file_path: open-sse/services/autoCombo/pipelineRouter.ts
language: typescript
signature:
({
  body,
  combo,
  handleChatCore,
  log,
  settings,
  signal,
}: PipelineComboParams): Promise<PipelineResult | Response>


id: interface:e7cb2accf995f640a752266b4c2f0ee5
kind: interface
name: UsageEntry
qualified_name: UsageEntry
file_path: open-sse/services/autoCombo/providerDiversity.ts
language: typescript
docstring:
Provider Diversity Tracking via Shannon Entropy
Measures and tracks how evenly distributed requests are across providers.
A system routing 90% of traffic to one provider has a catastrophic single
point of failure. This module provides a diversity score [0..1] that can
be used as a scoring factor in auto-combo selection.
Shannon entropy normalized to [0..1]:
  - 0.0 = all requests go to one provider (maximum risk)
  - 1.0 = perfectly even distribution (minimum risk)
@see https://en.wikipedia.org/wiki/Entropy_(information_theory)
Rolling window entry for provider usage tracking


id: function:2e7a4ed691ace737ac38007cbe2c5bf2
kind: function
name: getDiversityReport
qualified_name: getDiversityReport
file_path: open-sse/services/autoCombo/providerDiversity.ts
language: typescript
signature:
(): {
  score: number;
  totalRequests: number;
  providers: Record<string, { count: number; share: number }>;
  windowSize: number;
  ttlMs: number;
}


id: function:cc983926773d41c3e1be2d74abb65a7a
kind: function
name: selectWithStrategy
qualified_name: selectWithStrategy
file_path: open-sse/services/autoCombo/routerStrategy.ts
language: typescript
signature:
(
  pool: ProviderCandidate[],
  context: RoutingContext,
  strategyName = "rules"
): RoutingDecision


id: constant:892830bc7e7cb6b824ed2f7f1750f7d7
kind: constant
name: DEFAULT_WEIGHTS
qualified_name: DEFAULT_WEIGHTS
file_path: open-sse/services/autoCombo/scoring.ts
language: typescript
signature:
= {
  quota: 0.17,
  health: 0.22,
  costInv: 0.17,
  latencyInv: 0.13,
  taskFit: 0.08,
  stability: ...


id: function:ac11e9db8840bf764e91219b49973afc
kind: function
name: calculateFactors
qualified_name: calculateFactors
file_path: open-sse/services/autoCombo/scoring.ts
language: typescript
signature:
(
  candidate: ProviderCandidate,
  pool: ProviderCandidate[],
  taskType: string,
  getTaskFitness: (model: string, taskType: string) => number,
  manifestHint?: RoutingHint | null
): ScoringFactors


id: function:738f51551b83610f8eafe7c8c43fc02b
kind: function
name: scorePool
qualified_name: scorePool
file_path: open-sse/services/autoCombo/scoring.ts
language: typescript
signature:
(
  pool: ProviderCandidate[],
  taskType: string,
  weights: ScoringWeights = DEFAULT_WEIGHTS,
  getTaskFitness: (model: string, taskType: string) => number = () => 0.5,
  manifestHint?: RoutingHint | null
): ScoredProvider[]


id: method:ec8ff2122dfb2cfe9932f59daa7aa99f
kind: method
name: evaluate
qualified_name: SelfHealingManager::evaluate
file_path: open-sse/services/autoCombo/selfHealing.ts
language: typescript
docstring: Evaluate provider health and potentially exclude or re-admit.
signature:
(
    provider: string,
    score: number,
    circuitBreakerState: string
  ): {
    excluded: boolean;
    reason?: string;
    isProbe?: boolean;
  }


id: method:a8ef209f3388fdc407ab00e7fa475f7c
kind: method
name: getStatus
qualified_name: SelfHealingManager::getStatus
file_path: open-sse/services/autoCombo/selfHealing.ts
language: typescript
signature:
(): {
    exclusionCount: number;
    incidentMode: boolean;
    exclusions: Array<{ provider: string; reason: string; remainingMs: number }>;
  }


id: constant:554be43a8dbb1212e1fbcd258d8af029
kind: constant
name: FITNESS_TABLE
qualified_name: FITNESS_TABLE
file_path: open-sse/services/autoCombo/taskFitness.ts
language: typescript
docstring:
Task Fitness Lookup Table
Maps model patterns × task types → fitness score [0..1].
Supports wildcards and prefix matching.

signature:
= {
  coding: {
    "claude-sonnet": 0.95,
    "claude-opus": 0.92,
    "claude-haiku": 0.78,
    "gpt...


id: constant:b3aa550a0e72eb4012600773f85b4275
kind: constant
name: WILDCARD_BOOSTS
qualified_name: WILDCARD_BOOSTS
file_path: open-sse/services/autoCombo/taskFitness.ts
language: typescript
docstring: Wildcard patterns: model substrings → task type boosts
signature:
= [
  { pattern: "coder", taskType: "coding", boost: 0.15 },
  { pattern: "code", taskType: "coding", ...


id: interface:f5506f11c4d4370d0b93291f3c7cecaf
kind: interface
name: DegradationConfig
qualified_name: DegradationConfig
file_path: open-sse/services/backgroundTaskDetector.ts
language: typescript
docstring:
Background Task Detector — Feature 3
Detects when CLI tools send "background" requests (title generation,
summarization, short descriptions) and provides model degradation
recommendations to save premium model quota.
Detection heuristics:
- System prompt patterns indicating background/utility tasks
- Very short conversations with summary-like system prompts
- X-Request-Priority header
── Configuration ───────────────────────────────────────────────────────────


id: constant:ce225f6e4a7435d9c5b0867e49b3e2c6
kind: constant
name: DEFAULT_DETECTION_PATTERNS
qualified_name: DEFAULT_DETECTION_PATTERNS
file_path: open-sse/services/backgroundTaskDetector.ts
language: typescript
signature:
= [
  "generate a title",
  "generate title",
  "create a title",
  "create a short",
  "summarize thi...


id: constant:2abab7e62a298802c92af64c35ec2a16
kind: constant
name: DEFAULT_DEGRADATION_MAP
qualified_name: DEFAULT_DEGRADATION_MAP
file_path: open-sse/services/backgroundTaskDetector.ts
language: typescript
signature:
= {
  // Premium → Cheap alternatives
  "claude-opus-4-6": "gemini-3-flash",
  "claude-opus-4-6-thinki...


id: variable:ff17f0417d655127f3103a7003fda7d9
kind: variable
name: _config
qualified_name: _config
file_path: open-sse/services/backgroundTaskDetector.ts
language: typescript
docstring: ── State ───────────────────────────────────────────────────────────────────
signature:
= {
  enabled: false, // Disabled by default — user must opt in
  degradationMap: { ...DEFAULT_DEGRADA...


id: function:cc45c410329a4df6e782d5abca0c1658
kind: function
name: getBackgroundTaskReason
qualified_name: getBackgroundTaskReason
file_path: open-sse/services/backgroundTaskDetector.ts
language: typescript
signature:
(
  body: BackgroundTaskBody | unknown,
  headers: Record<string, string> | null = null
): string | null


id: constant:351aad186ebff485b7f3f7eca3ad6cef
kind: constant
name: BAILIAN_QUOTA_HOSTS
qualified_name: BAILIAN_QUOTA_HOSTS
file_path: open-sse/services/bailianQuotaFetcher.ts
language: typescript
docstring: Bailian quota hosts (international / china fallback)
signature:
= {
  international: "https://modelstudio.console.alibabacloud.com",
  china: "https://bailian.console...


id: constant:dd53c66f415b4dcbefda0ddfd5cd3fcd
kind: constant
name: BAILIAN_QUOTA_PATH
qualified_name: BAILIAN_QUOTA_PATH
file_path: open-sse/services/bailianQuotaFetcher.ts
language: typescript
signature:
= "/data/api.json?action=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2&product...


id: constant:87834305887b309fd11e7aed81fe7682
kind: constant
name: _cacheCleanup
qualified_name: _cacheCleanup
file_path: open-sse/services/bailianQuotaFetcher.ts
language: typescript
docstring: Auto-cleanup stale entries every 5 minutes
signature:
= setInterval(() => {
  const now = Date.now();
  for (const [key, entry] of quotaCache) {
    if (now...


id: import:598d378ea16fe407233e1835c997bfef
kind: import
name: @/lib/localDb
qualified_name: @/lib/localDb
file_path: open-sse/services/batchProcessor.ts
language: typescript
signature:
import {
  createFile,
  deleteFile,
  getApiKeyById,
  getBatch,
  getFileContent,
  getPendingBatches,
  getTerminalBatches,
  listFiles,
  updateBatch,
} from "@/lib/localDb";


id: function:546cbbcbf66cc1ec66d38614379640aa
kind: function
name: recoverOrphanedBatches
qualified_name: recoverOrphanedBatches
file_path: open-sse/services/batchProcessor.ts
language: typescript
signature: (): void
docstring:
Mark any in_progress/finalizing batches as failed on startup.
These were orphaned by a server crash or restart and cannot be safely resumed.


id: function:a52106407a5636b3235f53d9f6eabeb4
kind: function
name: parseBatchItems
qualified_name: parseBatchItems
file_path: open-sse/services/batchProcessor.ts
language: typescript
signature:
(
  content: Buffer,
  batchEndpoint: SupportedBatchEndpoint
): { items: BatchRequestItem[]; error: null } | { items: null; error: string }


id: constant:ed21aff49599431c812510d46ff95914
kind: constant
name: DEFAULT_PARAGRAPH_REMOVAL_ANCHORS
qualified_name: DEFAULT_PARAGRAPH_REMOVAL_ANCHORS
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
signature:
= [
  "github.com/anomalyco/opencode",
  "opencode.ai/docs",
  "github.com/cline/cline",
  "github.com...


id: constant:3c987fa81363d5c3e3a3c1d0246afc19
kind: constant
name: DEFAULT_TEXT_REPLACEMENTS
qualified_name: DEFAULT_TEXT_REPLACEMENTS
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
signature:
= [
  { match: "if OpenCode honestly", replacement: "if the assistant honestly" },
  {
    match: "Her...


id: constant:3bcd7eb9d40a8f8bb70d3bc2ae620548
kind: constant
name: DEFAULT_CC_BRIDGE_PIPELINE
qualified_name: DEFAULT_CC_BRIDGE_PIPELINE
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
signature:
= [
  // Sanitize caller-supplied system blocks first so dropped paragraphs do not
  // accidentally c...


id: interface:e2a2f295ce7e7abd7f5e4edf0172fa40
kind: interface
name: SystemBlock
qualified_name: SystemBlock
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
docstring:
────────────────────────────────────────────────────────────────────────────
Billing header value
────────────────────────────────────────────────────────────────────────────


id: interface:65539b29f3633d616a9c83dba0652c2d
kind: interface
name: RequestBody
qualified_name: RequestBody
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
docstring:
────────────────────────────────────────────────────────────────────────────
Body shape helpers
────────────────────────────────────────────────────────────────────────────


id: function:59c2b3a0e1c426df2144046c8d1a7aed
kind: function
name: applyDropParagraphIfContains
qualified_name: applyDropParagraphIfContains
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
signature: ( blocks: SystemBlock[], op: DropParagraphIfContainsOp ): SystemBlock[]
docstring:
────────────────────────────────────────────────────────────────────────────
Op executors
────────────────────────────────────────────────────────────────────────────


id: function:00fac1410ce91277f81d79b45bace0e0
kind: function
name: applyCcBridgeTransformPipeline
qualified_name: applyCcBridgeTransformPipeline
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
signature:
(
  body: RequestBody,
  config: CcBridgeTransformsConfig = getCcBridgeTransformsConfig()
): ApplyPipelineResult


id: variable:77f0ca28865c22d756f3ba834260d73d
kind: variable
name: _runtimeConfig
qualified_name: _runtimeConfig
file_path: open-sse/services/ccBridgeTransforms.ts
language: typescript
signature: = DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG
docstring:
────────────────────────────────────────────────────────────────────────────
Runtime singleton (mirrors cliFingerprints `_cliCompatProviders` pattern).
────────────────────────────────────────────────────────────────────────────


id: constant:735234301650658f7da9850fa178535b
kind: constant
name: DEFAULT_MAX_BYTES
qualified_name: DEFAULT_MAX_BYTES
file_path: open-sse/services/chatgptImageCache.ts
language: typescript
signature: = 256 * 1024 * 1024
docstring:
Per-entry images cap at 8 MB (enforced upstream in the executor) so 32 MB
covers ~4 large images. The byte cap matters more than entry count: a hot
loop of 8 MB images would otherwise pin 1.6 GB of RSS before count
eviction kicked in. Tune via OMNIROUTE_CGPT_WEB_IMAGE_CACHE_MAX_MB.


id: function:af9b58f9c29eb7d67a86fa8c0663a853
kind: function
name: storeChatGptImage
qualified_name: storeChatGptImage
file_path: open-sse/services/chatgptImageCache.ts
language: typescript
signature:
(
  bytes: Buffer,
  mime: string,
  ttlMs = DEFAULT_TTL_MS,
  context?: ChatGptImageConversationContext
): string


id: constant:2e7bfc3066122b72117f03cfdbd9c4a7
kind: constant
name: HARD_TIMEOUT_GRACE_MS
qualified_name: HARD_TIMEOUT_GRACE_MS
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
signature: = Number.parseInt(process.env.OMNIROUTE_CHATGPT_TLS_GRACE_MS || "", 10) || 10_000
docstring:
Grace period added to the binding's wire-level timeout before our JS-level
hard timeout fires. Under healthy operation `tls-client-node` honors
`timeoutMilliseconds` and rejects on its own; the JS-level race only wins
when the koffi-loaded native library is wedged (which the binding's own
timer can't escape). Keep the grace small so users don't wait noticeably
longer than the configured timeout when the binding is dead.


id: function:10c57c290be95d4263553b60ea0e6d2e
kind: function
name: resetClientCache
qualified_name: resetClientCache
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
signature: (): void
docstring:
Drop the cached client so the next `getClient()` call respawns it. Called
when a request observes the native binding has wedged — releasing the
reference lets a fresh TLSClient (and a fresh koffi load) take over without
a process restart.


id: function:f9ab6a521e4c8ecc6ea1e4aded536a22
kind: function
name: raceWithTimeout
qualified_name: raceWithTimeout
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
docstring:
Race a `client.request()` promise against (a) a JS-level hard timeout and
(b) the caller's abort signal. The native binding's `timeoutMilliseconds`
already covers the wire path; this guards the case where the koffi binding
itself deadlocks (observed after sustained load), where neither the
binding's own timer nor a post-call `signal.aborted` re-check can recover.

signature:
(
  promise: Promise<T>,
  timeoutMs: number,
  signal: AbortSignal | null | undefined
): Promise<T>


id: function:553d41325ad7b772a8ddc7f3c72a8808
kind: function
name: getClient
qualified_name: getClient
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
signature:
(): Promise<{
  request: (url: string, opts: Record<string, unknown>) => Promise<TlsResponseLike>;
}>


id: function:6526b21f79d99e5a61019ee186fb5983
kind: function
name: resolveProxyUrl
qualified_name: resolveProxyUrl
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
signature: (perCall: string | undefined): string | undefined
docstring:
Resolve the proxy URL for a tls-client request. Per-call value wins;
otherwise we use the standard proxy fetch resolution which reads from
the dashboard AsyncLocalStorage context or falls back to env vars.


id: variable:5e03142096168c775cd5b53dbed75e3f
kind: variable
name: testOverride
qualified_name: testOverride
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
signature: = null
docstring:
Test-only injection point. Tests call __setTlsFetchOverrideForTesting()
to replace the real TLS client with a mock; production never touches this.


id: function:7d010dbe8c282ab3f303d6047481fd08
kind: function
name: tlsFetchStreaming
qualified_name: tlsFetchStreaming
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
docstring:
─── Streaming via temp file ────────────────────────────────────────────────
tls-client-node's streaming primitive writes the response body chunk-by-chunk
to a file path, terminating when the upstream sends `streamOutputEOFSymbol`.
We tail the file from a worker and surface the bytes as a ReadableStream.

signature:
(
  client: { request: (url: string, opts: Record<string, unknown>) => Promise<TlsResponseLike> },
  url: string,
  requestOptions: Record<string, unknown>,
  eofSymbol = "[DONE]",
  signal: AbortSignal | null = null,
  hardTimeoutMs: number = DEFAULT_TIMEOUT_MS + HARD_TIMEOUT_GRACE_MS
): Promise<TlsFetchResult>


id: function:b0e61487e10af4649290c8b2e6f321d3
kind: function
name: waitForContent
qualified_name: waitForContent
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
docstring:
Wait for the streaming output file to exist AND contain at least one byte.
Returns false if the request settles before any bytes arrive (so the caller
can drain `requestPromise` and surface the real upstream status). Returns
true as soon as the file has data — even one byte is enough for the SSE
heuristic to give a useful answer.

signature:
(
  path: string,
  timeoutMs: number,
  requestPromise: Promise<TlsResponseLike>
): Promise<boolean>


id: function:f66927328944c219ee6a610d1b007f22
kind: function
name: tailFile
qualified_name: tailFile
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
signature:
(
  path: string,
  eofSymbol: string,
  done: Promise<TlsResponseLike>,
  signal: AbortSignal | null = null
): ReadableStream<Uint8Array>


id: import:284ef212bb80f647b4c27c0926b01c09
kind: import
name: ./claudeCodeConstraints.ts
qualified_name: ./claudeCodeConstraints.ts
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
import {
  enforceThinkingTemperature,
  disableThinkingIfToolChoiceForced,
  enforceCacheControlLimit,
} from "./claudeCodeConstraints.ts";


id: import:08b6d0d65719ae29eec1dae5d1ef8afd
kind: import
name: ./contextManager.ts
qualified_name: ./contextManager.ts
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
import {
  fixToolPairs,
  fixToolAdjacency,
  stripTrailingAssistantOrphanToolUse,
} from "./contextManager.ts";


id: constant:4c2fd8c64523013a7ca7d2e3c825bf1f
kind: constant
name: CLAUDE_CODE_COMPATIBLE_ANTHROPIC_BETA
qualified_name: CLAUDE_CODE_COMPATIBLE_ANTHROPIC_BETA
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
= [
  "claude-code-20250219",
  "interleaved-thinking-2025-05-14",
  "effort-2025-11-24",
].join(",")


id: constant:ce420fd9723fc8cfeb57b97086a98ea2
kind: constant
name: CLAUDE_CODE_COMPATIBLE_DEFAULT_SYSTEM_BLOCKS
qualified_name: CLAUDE_CODE_COMPATIBLE_DEFAULT_SYSTEM_BLOCKS
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
= [
  {
    type: "text",
    text: "You are a Claude agent, built on Anthropic's Claude Agent SDK.",
...


id: function:b050ad7ba63a0ab2eaeab3fb4b55034c
kind: function
name: buildClaudeCodeCompatibleRequest
qualified_name: buildClaudeCodeCompatibleRequest
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
({
  sourceBody,
  normalizedBody,
  claudeBody,
  model,
  stream = false,
  cwd = process.cwd(),
  sessionId,
  preserveCacheControl = false,
  preserveClaudeMessages = false,
}: BuildRequestOptions)


id: function:38bb9664abb9859c4fbf0848a1587368
kind: function
name: buildAndSignClaudeCodeRequest
qualified_name: buildAndSignClaudeCodeRequest
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
(
  options: BuildRequestOptions & { apiKey: string; enableObfuscation?: boolean }
): Promise<{ bodyString: string; headers: Record<string, string> }>


id: function:987f1bbeb4050fd6a4082d03a62b5794
kind: function
name: resolveClaudeCodeCompatibleEffort
qualified_name: resolveClaudeCodeCompatibleEffort
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
(
  sourceBody?: Record<string, unknown> | null,
  normalizedBody?: Record<string, unknown> | null,
  model?: string | null
): "low" | "medium" | "high" | "xhigh"


id: function:af6baea04d5a90fc8156e2edfa690467
kind: function
name: resolveClaudeCodeCompatibleMaxTokens
qualified_name: resolveClaudeCodeCompatibleMaxTokens
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
(
  sourceBody?: Record<string, unknown> | null,
  normalizedBody?: Record<string, unknown> | null
): number


id: function:f4350ecbf290a9fd24131a237746f66d
kind: function
name: buildClaudeCodeCompatibleSystemBlocks
qualified_name: buildClaudeCodeCompatibleSystemBlocks
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
({
  messages,
  systemBlocks,
  preserveCacheControl,
}: {
  messages: MessageLike[] | undefined;
  systemBlocks?: Array<Record<string, unknown>> | undefined;
  preserveCacheControl: boolean;
})


id: function:69d06c1dbeb255d3284063de127d22b1
kind: function
name: buildClaudeCodeCompatibleTools
qualified_name: buildClaudeCodeCompatibleTools
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
(
  normalizedBody?: Record<string, unknown> | null,
  sourceBody?: Record<string, unknown> | null
)


id: function:cde0594f261822f02c8a648d6987b998
kind: function
name: extractClaudeBodyFromSource
qualified_name: extractClaudeBodyFromSource
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
(
  sourceBody: Record<string, unknown>,
  preserveCacheControl: boolean
): Record<string, unknown> | null


id: function:fdc44839cfda2b86d9912accafaa27cd
kind: function
name: resolveClaudeCodeCompatibleMetadata
qualified_name: resolveClaudeCodeCompatibleMetadata
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
({
  claudeBody,
  sourceBody,
  normalizedBody,
  cwd,
  sessionId,
}: {
  claudeBody?: Record<string, unknown> | null;
  sourceBody?: Record<string, unknown> | null;
  normalizedBody?: Record<string, unknown> | null;
  cwd: string;
  sessionId: string;
})


id: function:22c802f5b83b93fc9164a1205e8b088e
kind: function
name: resolveClaudeCodeCompatibleThinking
qualified_name: resolveClaudeCodeCompatibleThinking
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
({
  claudeBody,
  sourceBody,
  normalizedBody,
}: {
  claudeBody?: Record<string, unknown> | null;
  sourceBody?: Record<string, unknown> | null;
  normalizedBody?: Record<string, unknown> | null;
})


id: function:2ae0c8f6b7ff57c9f2523bfa46fbde2d
kind: function
name: resolveClaudeCodeCompatibleOutputConfig
qualified_name: resolveClaudeCodeCompatibleOutputConfig
file_path: open-sse/services/claudeCodeCompatible.ts
language: typescript
signature:
({
  claudeBody,
  sourceBody,
  normalizedBody,
  model,
  effort,
}: {
  claudeBody?: Record<string, unknown> | null;
  sourceBody?: Record<string, unknown> | null;
  normalizedBody?: Record<string, unknown> | null;
  model?: string | null;
  effort: "low" | "medium" | "high" | "xhigh";
})


id: constant:0a8639ff9e5c3b494c30c86f8ea78c96
kind: constant
name: ZWJ
qualified_name: ZWJ
file_path: open-sse/services/claudeCodeObfuscation.ts
language: typescript
signature: = "\u200d"
docstring:
Sensitive word obfuscation for Claude Code requests.
Obfuscates configurable words in user messages to prevent detection
by upstream content filters. Uses zero-width characters to break
pattern matching while preserving readability.
Unicode zero-width joiner inserted between characters


id: constant:2c858c352d8e02b23e379d9d5c45361e
kind: constant
name: TOOL_RENAME_MAP
qualified_name: TOOL_RENAME_MAP
file_path: open-sse/services/claudeCodeToolRemapper.ts
language: typescript
signature:
= {
  ...EXTRA_TOOL_RENAME_MAP,
  bash: "Bash",
  read: "Read",
  write: "Write",
  edit: "Edit",
  gl...


id: constant:2f7528067506dfc212e3f58873d2969b
kind: constant
name: tokenCache
qualified_name: tokenCache
file_path: open-sse/services/claudeTurnstileSolver.ts
language: typescript
signature: = new Map< string, { token: string; expiresAt: number; } >()
docstring:
Cache for recently solved cf_clearance tokens
Reduces unnecessary challenge solving for rapid requests


id: function:c1a41982fe047645ba28721584ef4b65
kind: function
name: fetchWithAutoRefresh
qualified_name: fetchWithAutoRefresh
file_path: open-sse/services/claudeWebAutoRefresh.ts
language: typescript
signature:
(
  fetchFn: (cookie: string) => Promise<T>,
  initialCookie: string,
  options?: CookieRefreshOptions
): Promise<{ result: T; cookie: string; refreshed: boolean }>


id: type_alias:f8eb356a5b6e7966c8f0f62bc9d9f529
kind: type_alias
name: JsonRecord
qualified_name: JsonRecord
file_path: open-sse/services/codeAssistSubscription.ts
language: typescript
docstring:
Code Assist (loadCodeAssist) subscription tier extraction.
Mirrors Antigravity-Manager src-tauri/src/modules/quota.rs fetch_project_id().


id: interface:f25f3bdc108eb38b6ac382740c5c29db
kind: interface
name: CodexConnectionMeta
qualified_name: CodexConnectionMeta
file_path: open-sse/services/codexQuotaFetcher.ts
language: typescript
docstring:
─── Connection registry ─────────────────────────────────────────────────────
We need the accessToken + workspaceId to call the API.
chatCore.ts registers connection metadata here before requests.


id: function:446a434e093b231ddfbcf1ddcdcb8638
kind: function
name: getDominantResetAt
qualified_name: getDominantResetAt
file_path: open-sse/services/codexQuotaFetcher.ts
language: typescript
signature:
(quota: {
  window5h: { percentUsed: number; resetAt: string | null };
  window7d: { percentUsed: number; resetAt: string | null };
}): string | null


id: function:cdea91b20b5f69eb65ad6e64609d7284
kind: function
name: fetchCodexQuota
qualified_name: fetchCodexQuota
file_path: open-sse/services/codexQuotaFetcher.ts
language: typescript
signature:
(
  connectionId: string,
  connection?: Record<string, unknown>
): Promise<CodexDualWindowQuota | null>


id: import:7e8a01cd1285d82ff8173d69c90af0f4
kind: import
name: ./accountFallback.ts
qualified_name: ./accountFallback.ts
file_path: open-sse/services/combo.ts
language: typescript
signature:
import {
  checkFallbackError,
  formatRetryAfter,
  getRuntimeProviderProfile,
  recordProviderFailure,
  isProviderFailureCode,
  isProviderExhaustedReason,
} from "./accountFallback.ts";


id: import:e08389c14bcc40cc5c31c82b8eb7994f
kind: import
name: ./autoCombo/scoring.ts
qualified_name: ./autoCombo/scoring.ts
file_path: open-sse/services/combo.ts
language: typescript
signature:
import {
  calculateFactors,
  calculateScore,
  DEFAULT_WEIGHTS,
  type ProviderCandidate,
  type ScoringWeights,
} from "./autoCombo/scoring.ts";


id: import:0d69316637a8a989688906e371be63e0
kind: import
name: ../../src/lib/combos/steps.ts
qualified_name: ../../src/lib/combos/steps.ts
file_path: open-sse/services/combo.ts
language: typescript
signature:
import {
  getComboModelString,
  getComboStepTarget,
  getComboStepWeight,
  normalizeComboStep,
} from "../../src/lib/combos/steps.ts";


id: import:658812fee82be4eeff330db0f9b36b8d
kind: import
name: ../../src/domain/tagRouter.ts
qualified_name: ../../src/domain/tagRouter.ts
file_path: open-sse/services/combo.ts
language: typescript
signature:
import {
  getConnectionRoutingTags,
  matchesRoutingTags,
  resolveRequestRoutingTags,
  type RoutingTagMatchMode,
} from "../../src/domain/tagRouter.ts";


id: constant:269d9b348bac1459557408c30cd3b5c4
kind: constant
name: ALL_ACCOUNTS_RATE_LIMITED_PATTERNS
qualified_name: ALL_ACCOUNTS_RATE_LIMITED_PATTERNS
file_path: open-sse/services/combo.ts
language: typescript
signature: = [/unavailable/i, /service temporarily unavailable/i]
docstring:
Patterns that signal all accounts for a provider are rate-limited / exhausted.
Used to detect 503 responses from handleNoCredentials so combo can fallback.


id: constant:2766335fd7b6e38dac107e323c6bfea3
kind: constant
name: DEFAULT_MODEL_P95_MS
qualified_name: DEFAULT_MODEL_P95_MS
file_path: open-sse/services/combo.ts
language: typescript
docstring: Bootstrap defaults from ClawRouter benchmark (used when no local latency history exists yet)
signature:
= {
  "grok-4-fast-non-reasoning": 1143,
  "grok-4-1-fast-non-reasoning": 1244,
  "gemini-2.5-flash": ...


id: constant:9898c819fd19d9aa455ba728789154bd
kind: constant
name: OUTPUT_TOKEN_RATIO
qualified_name: OUTPUT_TOKEN_RATIO
file_path: open-sse/services/combo.ts
language: typescript
signature: = 0.4
docstring:
Assumed fraction of tokens that are output when blending input+output prices
for auto-combo cost scoring. 0.4 = 40% output, 60% input.
Matches the example in GitHub issue #1812 (e.g. o3-like model: $3 input/$15 output).


id: constant:15b861a462607879763b3ee2d7b339a7
kind: constant
name: RESET_AWARE_DEFAULTS
qualified_name: RESET_AWARE_DEFAULTS
file_path: open-sse/services/combo.ts
language: typescript
signature:
= {
  sessionWeight: 0.35,
  weeklyWeight: 0.65,
  tieBandPercent: 5,
  exhaustionGuardPercent: 10,
}


id: function:b3000cbe2f936536b4e4b362ab43b3b3
kind: function
name: validateResponseQuality
qualified_name: validateResponseQuality
file_path: open-sse/services/combo.ts
language: typescript
signature:
(
  response: Response,
  isStreaming: boolean,
  log: { warn?: (...args: unknown[]) => void }
): Promise<{ valid: boolean; reason?: string; clonedResponse?: Response }>


id: constant:d62642d684215644c36fa31de029e74d
kind: constant
name: rrCounters
qualified_name: rrCounters
file_path: open-sse/services/combo.ts
language: typescript
signature: = new Map()
docstring:
In-memory atomic counter per combo for round-robin distribution
Resets on server restart (by design — no stale state)


id: function:e3f17805a77fc38fe6dc7e901b896508
kind: function
name: normalizeModelEntry
qualified_name: normalizeModelEntry
file_path: open-sse/services/combo.ts
language: typescript
signature: (entry)
docstring:
Normalize a model entry to { model, weight }
Supports both legacy string format and new object format


id: function:ce64842cee30c10be25854f78f4cb5e2
kind: function
name: sortModelsByCost
qualified_name: sortModelsByCost
file_path: open-sse/services/combo.ts
language: typescript
signature: (models)
docstring:
shuffleArray and getNextModelFromDeck moved to src/shared/utils/shuffleDeck.ts
combo.ts now uses the shared, mutex-protected getNextFromDeck with "combo:" namespace.
Sort models by pricing (cheapest first) for cost-optimized strategy
@param {Array<string>} models - Model strings in "provider/model" format
@returns {Promise<Array<string>>} Sorted model strings


id: function:2a16099f39c9055daf2d2e8e9df31f60
kind: function
name: sortModelsByUsage
qualified_name: sortModelsByUsage
file_path: open-sse/services/combo.ts
language: typescript
signature: (models, comboName)
docstring:
Sort models by usage count (least-used first) for least-used strategy
@param {Array<string>} models - Model strings
@param {string} comboName - Combo name for metrics lookup
@returns {Array<string>} Sorted model strings


id: function:972308f7c46de6f4927ceb0371774021
kind: function
name: sortModelsByContextSize
qualified_name: sortModelsByContextSize
file_path: open-sse/services/combo.ts
language: typescript
signature: (models)
docstring:
Sort models by context window size (largest first) for context-optimized strategy.
Uses models.dev synced capabilities to get context limits.
@param {Array<string>} models - Model strings in "provider/model" format
@returns {Array<string>} Sorted model strings (largest context first)


id: function:d53dd822529801320ef63234cf15c95b
kind: function
name: getQuotaWindow
qualified_name: getQuotaWindow
file_path: open-sse/services/combo.ts
language: typescript
signature:
(
  quota: unknown,
  key: "window5h" | "window7d" | "windowWeekly" | "windowMonthly"
): { percentUsed: number | null; resetAt: string | null } | null


id: function:73602960351c57d7a8a2aa15c946510c
kind: function
name: getQuotaAwareConnectionsForTarget
qualified_name: getQuotaAwareConnectionsForTarget
file_path: open-sse/services/combo.ts
language: typescript
signature:
(
  target: ResolvedComboTarget,
  connectionCache: Map<string, Array<Record<string, unknown>>>,
  connectionLoadPromises: Map<string, Promise<Array<Record<string, unknown>>>>,
  comboName: string,
  log: { warn?: (...args: unknown[]) => void }
)


id: function:7ee2a34ad47e58db62818b016af26ece
kind: function
name: mapWithConcurrency
qualified_name: mapWithConcurrency
file_path: open-sse/services/combo.ts
language: typescript
signature:
(
  items: T[],
  concurrency: number,
  mapper: (item: T, index: number) => Promise<R>
): Promise<R[]>


id: function:15a6d1ef88068e97378772f93206c8d2
kind: function
name: orderTargetsByResetAwareQuota
qualified_name: orderTargetsByResetAwareQuota
file_path: open-sse/services/combo.ts
language: typescript
signature:
(
  targets: ResolvedComboTarget[],
  comboName: string,
  configSource: Record<string, unknown> | null | undefined,
  log: { warn?: (...args: unknown[]) => void },
  apiKeyAllowedConnectionIds?: string[] | null
)


id: function:ef78080154689577b5515a1fbb398eec
kind: function
name: applyRequestTagRouting
qualified_name: applyRequestTagRouting
file_path: open-sse/services/combo.ts
language: typescript
signature:
(
  targets: ResolvedComboTarget[],
  body: Record<string, unknown> | null | undefined,
  log: { info?: (...args: unknown[]) => void; warn?: (...args: unknown[]) => void }
): Promise<ResolvedComboTarget[]>


id: function:3efdc573a08dac3dcc7620c864bd13c3
kind: function
name: scoreAutoTargets
qualified_name: scoreAutoTargets
file_path: open-sse/services/combo.ts
language: typescript
signature:
(
  targets: ResolvedComboTarget[],
  candidates: ProviderCandidate[],
  taskType: string | null,
  weights: ScoringWeights
)


id: function:7f645006fb6bfeb1bf78e8af5d6a8cbd
kind: function
name: handleComboChat
qualified_name: handleComboChat
file_path: open-sse/services/combo.ts
language: typescript
signature:
({
  body,
  combo,
  handleSingleModel,
  isModelAvailable,
  log,
  settings,
  allCombos,
  relayOptions,
  signal,
  apiKeyAllowedConnections = null,
})


id: function:e2fd86246ef1ad7a22b7a142aa0994ae
kind: function
name: handleRoundRobinCombo
qualified_name: handleRoundRobinCombo
file_path: open-sse/services/combo.ts
language: typescript
docstring:
Handle round-robin combo: each request goes to the next model in circular order.
Uses semaphore-based concurrency control with queue + rate-limit awareness.
Flow:
1. Pick target model via atomic counter (counter % models.length)
2. Acquire semaphore slot (may queue if at max concurrency)
3. Send request to target model
4. On 429 → mark model rate-limited, try next model in rotation
5. On semaphore timeout → fallback to next available model

signature:
({
  body,
  combo,
  handleSingleModel,
  isModelAvailable,
  log,
  settings,
  allCombos,
  signal,
})


id: interface:65e1150e6c4f2f39f94f7789c2166a98
kind: interface
name: ComboConfig
qualified_name: ComboConfig
file_path: open-sse/services/comboAgentMiddleware.ts
language: typescript
docstring:
comboAgentMiddleware.ts — Combo Agent Features
Implements the "combo as agent" features from issues #399 and #401:
1. **System Message Override** (#399): If the combo defines a `system_message`,
   it is injected as the first system message, replacing any existing system message.
2. **Tool Filter Regex** (#399): If the combo defines a `tool_filter_regex`,
   only tools whose name matches the pattern are forwarded to the provider.
3. **Context Caching Protection** (#401): If the combo enables
   `context_cache_protection`, the proxy:
   a. On response: injects `<omniModel>provider/model</omniModel>` tag into
      the first assistant message content string.
   b. On request: scans the message history for the tag, and if found,
      overrides the requested model with the pinned one.
All features are opt-in per combo and backward compatible with existing setups.


id: constant:8f9e64e83c03e8e8847d32cb3114acdf
kind: constant
name: CACHE_TAG_PATTERN
qualified_name: CACHE_TAG_PATTERN
file_path: open-sse/services/comboAgentMiddleware.ts
language: typescript
signature: = /(?:\\n|\n|\r)*<omniModel>([^<]+)<\/omniModel>(?:\\n|\n|\r)*/
docstring:
── Context Caching Tag ─────────────────────────────────────────────────────
Handles both actual newlines (U+000A) and literal \n sequences injected
by combo.ts streaming around the <omniModel> tag (#531). Non-global so that
.exec() and .test() stay stateless; callers that need full replacement use
String.prototype.replace() which replaces all non-overlapping matches.


id: function:4439b7d2fa749a0a016898e3712f72e4
kind: function
name: applyComboAgentMiddleware
qualified_name: applyComboAgentMiddleware
file_path: open-sse/services/comboAgentMiddleware.ts
language: typescript
signature:
(
  body: Record<string, unknown>,
  comboConfig: ComboConfig | null | undefined,
  providerModel: string // "provider/model" string for context caching
): { body: Record<string, unknown>; pinnedModel: string | null }


id: constant:7ae5673827ccd93d594f8b110fbc8f44
kind: constant
name: DEFAULT_COMBO_CONFIG
qualified_name: DEFAULT_COMBO_CONFIG
file_path: open-sse/services/comboConfig.ts
language: typescript
docstring:
Combo Configuration Resolver
Implements 3-layer cascade: Global Defaults → Provider Overrides → Per-Combo Config
Most specific wins.

signature:
= {
  strategy: "priority",
  maxRetries: 1,
  retryDelayMs: 2000,
  fallbackDelayMs: 0,
  concurrency...


id: function:66abd1e81f03f37f81cef0ce4fd0cd6b
kind: function
name: recordComboIntentWithSpecificity
qualified_name: recordComboIntentWithSpecificity
file_path: open-sse/services/comboManifestMetrics.ts
language: typescript
signature:
(
  comboName: string,
  specificityScore: number,
  specificityLevel: string,
  strategyModifier: string
): void


id: interface:224119736de6c29d261e8df69b80a6ab
kind: interface
name: ModelMetrics
qualified_name: ModelMetrics
file_path: open-sse/services/comboMetrics.ts
language: typescript
docstring:
In-memory combo metrics tracker
Tracks per-combo, per-model, and per-target request counts, latency, success/failure rates.
Provides API for reading metrics from the dashboard.


id: function:8ea763ec740fb34daf395f3c298e20b2
kind: function
name: recordComboRequest
qualified_name: recordComboRequest
file_path: open-sse/services/comboMetrics.ts
language: typescript
signature:
(
  comboName: string,
  modelStr: string | null,
  {
    success,
    latencyMs,
    fallbackCount = 0,
    strategy = "priority",
    target,
  }: {
    success: boolean;
    latencyMs: number;
    fallbackCount?: number;
    strategy?: string;
    target?: ComboRequestTargetMeta | null;
  }
): void


id: function:3c4d9a336f357da8e7eb97ea318a474e
kind: function
name: compressAggressive
qualified_name: compressAggressive
file_path: open-sse/services/compression/aggressive.ts
language: typescript
signature:
(
  messages: ChatMessage[],
  config?: Partial<AggressiveConfig>,
  stats?: CompressionStats
): AggressiveCompressionResult


id: import:94ed58f8550ecba27c9adad1a32aad67
kind: import
name: ./types.ts
qualified_name: ./types.ts
file_path: open-sse/services/compression/caveman.ts
language: typescript
signature:
import type {
  CavemanConfig,
  CavemanRule,
  CompressionResult,
  CompressionMode,
  CompressionStats,
} from "./types.ts";


id: constant:873b2fcc5463355d02910f8a661443d0
kind: constant
name: RULE_KEYWORDS
qualified_name: RULE_KEYWORDS
file_path: open-sse/services/compression/caveman.ts
language: typescript
signature:
= {
  redundant_phrasing: ["make sure", "be sure"],
  redundant_because: ["due to the fact", "the reas...


id: function:7e919d76f9bcaa100c9e0291698990fb
kind: function
name: createCavemanStats
qualified_name: createCavemanStats
file_path: open-sse/services/compression/caveman.ts
language: typescript
signature:
(
  originalTokens: number,
  compressedTokens: number,
  techniquesUsed: string[],
  rulesApplied: string[] | undefined,
  durationMs: number
): CompressionStats


id: constant:b367606562029c40adc0ace743b5fa09
kind: constant
name: PROTECTED_STRUCTURE_RE
qualified_name: PROTECTED_STRUCTURE_RE
file_path: open-sse/services/compression/caveman.ts
language: typescript
signature:
= /```|~~~|`|https?:\/\/|\[[^\]\n]{1,1000}\]\([^)[ \t\n]{1,2000}(?:[ \t]+"[^"]{0,1000}")?\)|^#{1,6}\s+...


id: constant:2bd458d9c84540d81d3ef0297340b0e4
kind: constant
name: CAVEMAN_RULES
qualified_name: CAVEMAN_RULES
file_path: open-sse/services/compression/cavemanRules.ts
language: typescript
signature:
= [
  // ── Category 1: Filler Removal (10+ rules) ──────────────────────────

  {
    name: "redundan...


id: function:5e99e56d97cb58e0056168542aeb8230
kind: function
name: getRulesForContext
qualified_name: getRulesForContext
file_path: open-sse/services/compression/cavemanRules.ts
language: typescript
signature:
(
  context: string,
  intensity: "lite" | "full" | "ultra" = "full",
  language = "en"
): CavemanRule[]


id: function:7f647224f6db38e7a147e5315c8e9539
kind: function
name: getDiffSkipWarning
qualified_name: getDiffSkipWarning
file_path: open-sse/services/compression/diffHelper.ts
language: typescript
signature:
(
  original: string,
  compressed: string,
  options: CompressionPreviewDiffOptions = {}
): string | null


id: function:1074939d5e513f81a82c5f168ac5b1e1
kind: function
name: buildCompressionPreviewDiff
qualified_name: buildCompressionPreviewDiff
file_path: open-sse/services/compression/diffHelper.ts
language: typescript
signature:
(
  original: string,
  compressed: string,
  stats: CompressionStats | null | undefined,
  options: CompressionPreviewDiffOptions = {}
): CompressionPreviewDiff


id: import:6f2fd0cc711c40582d7528e97ae327f0
kind: import
name: ../types.ts
qualified_name: ../types.ts
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
import {
  DEFAULT_AGGRESSIVE_CONFIG,
  DEFAULT_ULTRA_CONFIG,
  type CavemanIntensity,
} from "../types.ts";


id: constant:0c0c894f9d0457b43a8a6738c7b5551f
kind: constant
name: CAVEMAN_SCHEMA
qualified_name: CAVEMAN_SCHEMA
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
= [
  {
    key: "intensity",
    type: "select",
    label: "Intensity",
    defaultValue: "full",
  ...


id: constant:3f857b92a7115148462ea7c3f9cef02a
kind: constant
name: AGGRESSIVE_SCHEMA
qualified_name: AGGRESSIVE_SCHEMA
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
= [
  {
    key: "summarizerEnabled",
    type: "boolean",
    label: "Summarizer enabled",
    defaul...


id: constant:5e9e69f003e15177ada7b4a69e1092a5
kind: constant
name: ULTRA_SCHEMA
qualified_name: ULTRA_SCHEMA
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
= [
  {
    key: "enabled",
    type: "boolean",
    label: "Enabled",
    defaultValue: DEFAULT_ULTRA...


id: function:a6e1e70977fac57675a511b6d9148960
kind: function
name: validateNumberRange
qualified_name: validateNumberRange
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
(
  config: Record<string, unknown>,
  key: string,
  min: number,
  max: number,
  errors: string[]
): void


id: constant:e775ee1e93509b242c36e3efb7ad7cff
kind: constant
name: liteEngine
qualified_name: liteEngine
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
= {
  id: "lite",
  name: "Lite",
  description: "Fast whitespace, tool-result and image URL reduction...


id: constant:2aae4e428f57d0986e5e7923215fc095
kind: constant
name: cavemanEngine
qualified_name: cavemanEngine
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
= {
  id: "caveman",
  name: "Caveman",
  description: "Rule-based message compression with preservati...


id: constant:76bfd31aa04b3b1b37e423d98b9d013d
kind: constant
name: aggressiveEngine
qualified_name: aggressiveEngine
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
= {
  id: "aggressive",
  name: "Aggressive",
  description: "Summarization, tool result compression a...


id: constant:a6359e72d66c8ca12703d1673736d648
kind: constant
name: ultraEngine
qualified_name: ultraEngine
file_path: open-sse/services/compression/engines/cavemanAdapter.ts
language: typescript
signature:
= {
  id: "ultra",
  name: "Ultra",
  description: "Heuristic token pruning with optional local SLM fa...


id: constant:b19acb38dab14c1af92e638329904e71
kind: constant
name: MCP_ACCESSIBILITY_DEFAULTS
qualified_name: MCP_ACCESSIBILITY_DEFAULTS
file_path: open-sse/services/compression/engines/mcpAccessibility/constants.ts
language: typescript
signature:
= {
  maxTextChars: 50000,
  collapseThreshold: 30,
  collapseKeepHead: 10,
  collapseKeepTail: 5,
  m...


id: constant:43929ffa98a23bfbe603a3c3da3a24f8
kind: constant
name: DEFAULT_MCP_ACCESSIBILITY_CONFIG
qualified_name: DEFAULT_MCP_ACCESSIBILITY_CONFIG
file_path: open-sse/services/compression/engines/mcpAccessibility/constants.ts
language: typescript
signature:
= {
  enabled: true,
  maxTextChars: MCP_ACCESSIBILITY_DEFAULTS.maxTextChars,
  collapseThreshold: MCP...


id: constant:2fd55f5ac2ebc48d66f4da90270d7b44
kind: constant
name: LANGUAGE_ALIASES
qualified_name: LANGUAGE_ALIASES
file_path: open-sse/services/compression/engines/rtk/codeStripper.ts
language: typescript
signature:
= {
  js: "javascript",
  jsx: "javascript",
  javascript: "javascript",
  ts: "typescript",
  tsx: "t...


id: function:fd151b86a5f25781dd9d0ddd0f3b6e17
kind: function
name: stripCode
qualified_name: stripCode
file_path: open-sse/services/compression/engines/rtk/codeStripper.ts
language: typescript
signature:
(
  text: string,
  language: CodeLanguage = "unknown",
  options: CodeStripperOptions = {}
): {
  text: string;
  strippedLines: number;
  language: CodeLanguage;
}


id: constant:b5ee1adb47fc568d018c6edbbd868690
kind: constant
name: COMMAND_PREFIXES
qualified_name: COMMAND_PREFIXES
file_path: open-sse/services/compression/engines/rtk/commandDetector.ts
language: typescript
signature:
= [
  "git",
  "make",
  "terraform",
  "tofu",
  "opentofu",
  "systemctl",
  "npm",
  "pnpm",
  "yar...


id: constant:d0abc3c7ec4aed1ed91bba77ee1c2a64
kind: constant
name: DETECTORS
qualified_name: DETECTORS
file_path: open-sse/services/compression/engines/rtk/commandDetector.ts
language: typescript
signature:
= [
  {
    type: "git-status",
    category: "git",
    commandPatterns: [/^git\s+status\b/i],
    co...


id: constant:1ccae9adbc7ad730b8bbdeb8278afa16
kind: constant
name: regexCache
qualified_name: regexCache
file_path: open-sse/services/compression/engines/rtk/filterLoader.ts
language: typescript
signature: = new Map<string, RegExp>()
docstring:
RegExp cache for matchPatterns — same pattern strings are tested against
many different lines across requests; avoid compiling them every time.


id: function:8bc70cd3fa66da82a11014d2f275a971
kind: function
name: getRtkFilterCatalog
qualified_name: getRtkFilterCatalog
file_path: open-sse/services/compression/engines/rtk/filterLoader.ts
language: typescript
signature:
(): Array<
  Pick<
    RtkFilterDefinition,
    "id" | "name" | "description" | "commandTypes" | "category" | "priority"
  >
>


id: function:df519eb1d838d93ac451ff16621b59fe
kind: function
name: matchRtkFilter
qualified_name: matchRtkFilter
file_path: open-sse/services/compression/engines/rtk/filterLoader.ts
language: typescript
signature:
(
  text: string,
  command?: string | null,
  options: RtkFilterLoadOptions = {}
): RtkFilterDefinition | null


id: constant:e5f9fecbdd00883e1650ece08196149c
kind: constant
name: rtkFilterCategorySchema
qualified_name: rtkFilterCategorySchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z.enum([
  "git",
  "test",
  "build",
  "shell",
  "docker",
  "package",
  "infra",
  "cloud",
  "...


id: constant:00d1bb79e1ca8e272a80bb4736ebfc76
kind: constant
name: rtkMatchOutputRuleSchema
qualified_name: rtkMatchOutputRuleSchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z
  .object({
    pattern: z.string().min(1),
    message: z.string(),
    unless: z.string().min(1)...


id: constant:905d6985968229996da3e788657fcb71
kind: constant
name: rtkInlineTestSchema
qualified_name: rtkInlineTestSchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z
  .object({
    name: z.string().min(1),
    input: z.string(),
    expected: z.string(),
    comm...


id: constant:2a9c40b9bbc766c90f4b73e87baffd5b
kind: constant
name: rtkFilterMatchSchema
qualified_name: rtkFilterMatchSchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z
  .object({
    commands: z.array(z.string().min(1)).default([]),
    patterns: z.array(z.string()...


id: constant:42f4cba8b5f30f5f868718f58be53478
kind: constant
name: rtkFilterRulesSchema
qualified_name: rtkFilterRulesSchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z
  .object({
    stripAnsi: z.boolean().default(false),
    replace: z.array(rtkReplaceRuleSchema)....


id: constant:d422753c14732cd797e9f174c3357203
kind: constant
name: rtkFilterPreserveSchema
qualified_name: rtkFilterPreserveSchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z
  .object({
    errorPatterns: z.array(z.string()).default([]),
    summaryPatterns: z.array(z.str...


id: constant:cb03b437ec8fc4c86b4010a75cea30cf
kind: constant
name: rtkFilterPackSchema
qualified_name: rtkFilterPackSchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z
  .object({
    id: z.string().min(1),
    label: z.string().min(1),
    description: z.string().d...


id: constant:bae4566e19861dab9e5cfc7be9fd1bdc
kind: constant
name: legacyRtkFilterSchema
qualified_name: legacyRtkFilterSchema
file_path: open-sse/services/compression/engines/rtk/filterSchema.ts
language: typescript
signature:
= z
  .object({
    id: z.string().min(1),
    name: z.string().min(1),
    description: z.string().de...


id: constant:070d9f43d56dda162b48e587b6456045
kind: constant
name: RTK_SCHEMA
qualified_name: RTK_SCHEMA
file_path: open-sse/services/compression/engines/rtk/index.ts
language: typescript
signature:
= [
  {
    key: "intensity",
    type: "select",
    label: "Intensity",
    defaultValue: DEFAULT_RT...


id: function:7c6e6fee4fd48f831fb51fa74eb7d94b
kind: function
name: processRtkCodeBlocksOnly
qualified_name: processRtkCodeBlocksOnly
file_path: open-sse/services/compression/engines/rtk/index.ts
language: typescript
signature:
(
  content: Message["content"],
  config: RtkConfig
): {
  content: Message["content"];
  compressed: boolean;
  techniquesUsed: string[];
  rulesApplied: string[];
  rawOutputPointers: RtkRawOutputPointer[];
}


id: function:4e37bc831510e884c4c489b2e7478afb
kind: function
name: processRtkText
qualified_name: processRtkText
file_path: open-sse/services/compression/engines/rtk/index.ts
language: typescript
signature:
(
  text: string,
  options: { command?: string | null; config?: Partial<RtkConfig> } = {}
): RtkProcessResult


id: function:3f60ff72007d620f12629c6629fcdfc2
kind: function
name: applyRtkCompression
qualified_name: applyRtkCompression
file_path: open-sse/services/compression/engines/rtk/index.ts
language: typescript
signature:
(
  body: Record<string, unknown>,
  options: { config?: Partial<RtkConfig>; stepConfig?: Record<string, unknown> } = {}
): CompressionResult


id: constant:b14f82458355eed8d316302dab855e49
kind: constant
name: rtkEngine
qualified_name: rtkEngine
file_path: open-sse/services/compression/engines/rtk/index.ts
language: typescript
signature:
= {
  id: "rtk",
  name: "RTK",
  description: "Command-aware tool output compression with declarative...


id: constant:f7ba5e8ab67b1ea93a50b5a1da544f81
kind: constant
name: regexCache
qualified_name: regexCache
file_path: open-sse/services/compression/engines/rtk/lineFilter.ts
language: typescript
signature: = new Map<string, RegExp>()
docstring:
──────────────── RegExp cache ────────────────

Patterns are static (loaded from filter JSON files on boot) but were being
compiled via `new RegExp(...)` on every call to applyLineFilter().  For a
busy proxy this means thousands of redundant RegExp instantiations per
second.  Cache them here once.


id: constant:942a21186a1d04cdf2e5cb9f51347971
kind: constant
name: SECRET_PATTERNS
qualified_name: SECRET_PATTERNS
file_path: open-sse/services/compression/engines/rtk/rawOutput.ts
language: typescript
signature:
= [
  [/\b(sk-[A-Za-z0-9_-]{16,})\b/g, "[REDACTED_OPENAI_KEY]"],
  [/\b(xox[baprs]-[A-Za-z0-9-]{16,})\...


id: function:d0d3b28e02ebfe1d15c83ac94fa7d14c
kind: function
name: maybePersistRtkRawOutput
qualified_name: maybePersistRtkRawOutput
file_path: open-sse/services/compression/engines/rtk/rawOutput.ts
language: typescript
signature:
(
  raw: string,
  options: {
    retention: RtkRawOutputRetention;
    command?: string | null;
    maxBytes?: number;
    failure?: boolean;
  }
): RtkRawOutputPointer | null


id: function:d73476434864b400e5149eedb1379576
kind: function
name: smartTruncate
qualified_name: smartTruncate
file_path: open-sse/services/compression/engines/rtk/smartTruncate.ts
language: typescript
signature:
(
  text: string,
  options: SmartTruncateOptions = {}
): {
  text: string;
  truncated: boolean;
  droppedLines: number;
}


id: import:4997a525079dd9a96fa24ae96acefe21
kind: import
name: ./filterLoader.ts
qualified_name: ./filterLoader.ts
file_path: open-sse/services/compression/engines/rtk/verify.ts
language: typescript
signature:
import {
  getRtkFilterLoadDiagnostics,
  loadRtkFilters,
  type RtkFilterLoadDiagnostic,
} from "./filterLoader.ts";


id: function:928a4aa82c8e5ff91db5c445ab27de84
kind: function
name: runRtkFilterTests
qualified_name: runRtkFilterTests
file_path: open-sse/services/compression/engines/rtk/verify.ts
language: typescript
signature:
(
  options: {
    requireAll?: boolean;
    customFiltersEnabled?: boolean;
    trustProjectFilters?: boolean;
  } = {}
): RtkVerifyResult


id: constant:ed0c4449fefa74af12ebf90b27b234cc
kind: constant
name: LANGUAGE_HINTS
qualified_name: LANGUAGE_HINTS
file_path: open-sse/services/compression/languageDetector.ts
language: typescript
signature:
= {
  "pt-BR": [/\b(?:voce|você|preciso|arquivo|codigo|código|erro|falha|obrigado)\b/i],
  es: [/\b(?:...


id: function:cbc102775a0554255cc6272eff947cea
kind: function
name: collapseWhitespace
qualified_name: collapseWhitespace
file_path: open-sse/services/compression/lite.ts
language: typescript
signature:
(
  body: ChatBody,
  options: LiteCompressionOptions = {}
): {
  body: ChatBody;
  applied: boolean;
}


id: function:cb0cb0c7964206ac6858a6edcb8d95c6
kind: function
name: replaceImageUrls
qualified_name: replaceImageUrls
file_path: open-sse/services/compression/lite.ts
language: typescript
signature:
(
  body: ChatBody,
  options?: LiteCompressionOptions | string
): { body: ChatBody; applied: boolean }


id: constant:4958a1703442de1ac18cc03b235c4395
kind: constant
name: SHARED_BOUNDARIES
qualified_name: SHARED_BOUNDARIES
file_path: open-sse/services/compression/outputMode.ts
language: typescript
signature:
= "Code blocks, file paths, commands, errors, URLs: keep exact. Security warnings, irreversible action...


id: constant:68100c958a7bf0fba9db4c3d2407c619
kind: constant
name: CAVEMAN_INSTRUCTION_BY_LANGUAGE
qualified_name: CAVEMAN_INSTRUCTION_BY_LANGUAGE
file_path: open-sse/services/compression/outputMode.ts
language: typescript
signature:
= {
  en: {
    lite: `Respond concise. Drop filler, pleasantries, hedging. Keep full sentences, techn...


id: function:91b7299d6a40a7d86e0cc5ef9bdc65d3
kind: function
name: applyCavemanOutputMode
qualified_name: applyCavemanOutputMode
file_path: open-sse/services/compression/outputMode.ts
language: typescript
signature:
(
  body: ChatRequestBody,
  options?: Partial<CavemanOutputModeConfig>,
  language = "en"
): CavemanOutputModeResult


id: function:ecd139922073b68856016f2c74f763c3
kind: function
name: replacePattern
qualified_name: replacePattern
file_path: open-sse/services/compression/preservation.ts
language: typescript
signature:
(
  text: string,
  pattern: RegExp,
  kind: string,
  addBlock: (content: string, kind: string) => string
): string


id: function:c2fd13e4f75b351aec6d86a16adabdd2
kind: function
name: applyAging
qualified_name: applyAging
file_path: open-sse/services/compression/progressiveAging.ts
language: typescript
signature:
(
  messages: unknown[],
  thresholds?: AgingThresholds,
  summarizer?: Summarizer,
  preserveSystemPrompt = true
): { messages: unknown[]; saved: number }


id: import:50751eae223b5b13af8b55d83a049f5c
kind: import
name: ./types.ts
qualified_name: ./types.ts
file_path: open-sse/services/compression/stats.ts
language: typescript
signature:
import {
  type CompressionMode,
  type CompressionStats,
  type CompressionConfig,
  DEFAULT_COMPRESSION_CONFIG,
  DEFAULT_CAVEMAN_CONFIG,
  DEFAULT_RTK_CONFIG,
  DEFAULT_COMPRESSION_LANGUAGE_CONFIG,
} from "./types.ts";


id: function:fe626e927f3420925043655e169489d0
kind: function
name: createCompressionStats
qualified_name: createCompressionStats
file_path: open-sse/services/compression/stats.ts
language: typescript
signature:
(
  originalBody: Record<string, unknown>,
  compressedBody: Record<string, unknown>,
  mode: CompressionMode,
  techniquesUsed: string[],
  rulesApplied?: string[],
  durationMs?: number
): CompressionStats


id: import:7b88080d0ee8c9b90081e071b136d453
kind: import
name: ./types.ts
qualified_name: ./types.ts
file_path: open-sse/services/compression/strategySelector.ts
language: typescript
signature:
import type {
  CompressionConfig,
  CompressionMode,
  CompressionPipelineStep,
  CompressionResult,
  CompressionStats,
} from "./types.ts";


id: import:c821c161aacbb8c10ab8f2c12358fa6c
kind: import
name: ./cachingAware.ts
qualified_name: ./cachingAware.ts
file_path: open-sse/services/compression/strategySelector.ts
language: typescript
signature:
import {
  detectCachingContext,
  getCacheAwareStrategy,
  type CachingDetectionContext,
} from "./cachingAware.ts";


id: function:b508644823b878920666db274efb752a
kind: function
name: getEffectiveMode
qualified_name: getEffectiveMode
file_path: open-sse/services/compression/strategySelector.ts
language: typescript
signature:
(
  config: CompressionConfig,
  comboId: string | null,
  estimatedTokens: number
): CompressionMode


id: function:5ac721387c8544a3a9fb1b32a10e5986
kind: function
name: selectCompressionStrategy
qualified_name: selectCompressionStrategy
file_path: open-sse/services/compression/strategySelector.ts
language: typescript
signature:
(
  config: CompressionConfig,
  comboId: string | null,
  estimatedTokens: number,
  body?: Record<string, unknown>,
  context?: CachingDetectionContext
): CompressionMode


id: function:74ae23dbebe6c79a8f4dfb2676220bf2
kind: function
name: applyCompression
qualified_name: applyCompression
file_path: open-sse/services/compression/strategySelector.ts
language: typescript
signature:
(
  body: Record<string, unknown>,
  mode: CompressionMode,
  options?: { model?: string; supportsVision?: boolean | null; config?: CompressionConfig }
): CompressionResult


id: function:025d548448addee9eef952a880d1320d
kind: function
name: applyStackedCompression
qualified_name: applyStackedCompression
file_path: open-sse/services/compression/strategySelector.ts
language: typescript
signature:
(
  body: Record<string, unknown>,
  pipeline?: Array<CompressionPipelineStep | string>,
  options?: {
    model?: string;
    supportsVision?: boolean | null;
    config?: CompressionConfig;
    compressionComboId?: string | null;
  }
): CompressionResult


id: constant:eacc5be7b5b2262eb79a6190fe305f8e
kind: constant
name: FILE_EXTENSIONS
qualified_name: FILE_EXTENSIONS
file_path: open-sse/services/compression/summarizer.ts
language: typescript
signature:
= new Set([
  "ts",
  "tsx",
  "js",
  "jsx",
  "py",
  "md",
  "json",
  "sql",
  "css",
  "html",
  ...


id: constant:c3982363a28fb9c460c73ef0f1342549
kind: constant
name: DEFAULT_COMPRESSION_CONFIG
qualified_name: DEFAULT_COMPRESSION_CONFIG
file_path: open-sse/services/compression/types.ts
language: typescript
signature:
= {
  enabled: false,
  defaultMode: "off",
  autoTriggerMode: "lite",
  autoTriggerTokens: 0,
  cache...


id: constant:4c3e151e77860bb585d686583bb4d4c0
kind: constant
name: DEFAULT_CAVEMAN_CONFIG
qualified_name: DEFAULT_CAVEMAN_CONFIG
file_path: open-sse/services/compression/types.ts
language: typescript
signature:
= {
  enabled: false,
  compressRoles: ["user"],
  skipRules: [],
  minMessageLength: 50,
  // Protect...


id: constant:c5eceef0926e9ec4bc4308ec0b96769c
kind: constant
name: DEFAULT_RTK_CONFIG
qualified_name: DEFAULT_RTK_CONFIG
file_path: open-sse/services/compression/types.ts
language: typescript
signature:
= {
  enabled: false,
  intensity: "minimal",
  applyToToolResults: true,
  applyToCodeBlocks: false,
...


id: constant:d7e539127189afd0d06725d78067406b
kind: constant
name: DEFAULT_AGGRESSIVE_CONFIG
qualified_name: DEFAULT_AGGRESSIVE_CONFIG
file_path: open-sse/services/compression/types.ts
language: typescript
signature:
= {
  thresholds: { fullSummary: 5, moderate: 3, light: 2, verbatim: 2 },
  toolStrategies: {
    file...


id: constant:04dfa0a17fc40d356e9996a56d47ef91
kind: constant
name: DEFAULT_ULTRA_CONFIG
qualified_name: DEFAULT_ULTRA_CONFIG
file_path: open-sse/services/compression/types.ts
language: typescript
signature:
= {
  enabled: false,
  compressionRate: 0.5,
  minScoreThreshold: 0.3,
  slmFallbackToAggressive: tru...


id: constant:9712f17ff875c3299b9acf4381f815c0
kind: constant
name: STOPWORDS
qualified_name: STOPWORDS
file_path: open-sse/services/compression/ultraHeuristic.ts
language: typescript
signature:
= new Set([
  "a",
  "an",
  "the",
  "is",
  "are",
  "was",
  "were",
  "be",
  "been",
  "being",
 ...


id: import:c0224947e362e49869bc2d4bb3077d11
kind: import
name: ../../src/lib/db/contextHandoffs.ts
qualified_name: ../../src/lib/db/contextHandoffs.ts
file_path: open-sse/services/contextHandoff.ts
language: typescript
signature:
import {
  cleanupExpiredHandoffs,
  hasActiveHandoff,
  type HandoffPayload,
  upsertHandoff,
} from "../../src/lib/db/contextHandoffs.ts";


id: constant:abbab5d5d6d44b54d0cec1da1a394ecc
kind: constant
name: HANDOFF_PROMPT_TEMPLATE
qualified_name: HANDOFF_PROMPT_TEMPLATE
file_path: open-sse/services/contextHandoff.ts
language: typescript
signature:
= `You are a context summarizer. Analyze the conversation below and generate a structured handoff summ...


id: function:928d7a5c0342560b7d46598a139dc05a
kind: function
name: generateHandoffAsync
qualified_name: generateHandoffAsync
file_path: open-sse/services/contextHandoff.ts
language: typescript
signature:
(options: {
  sessionId: string;
  comboName: string;
  connectionId: string;
  percentUsed: number;
  messages: MessageLike[];
  model: string;
  expiresAt: string | null;
  config?: ContextRelayConfig | null;
  handleSingleModel: (body: Record<string, unknown>, modelStr: string) => Promise<Response>;
}): Promise<void>


id: function:f9bbcb6631be796726abc2ad62ca23e3
kind: function
name: maybeGenerateHandoff
qualified_name: maybeGenerateHandoff
file_path: open-sse/services/contextHandoff.ts
language: typescript
signature:
(options: {
  sessionId: string | null;
  comboName: string;
  connectionId: string | null;
  percentUsed: number;
  messages: MessageLike[];
  model: string;
  expiresAt: string | null;
  config?: ContextRelayConfig | null;
  handleSingleModel: (body: Record<string, unknown>, modelStr: string) => Promise<Response>;
}): void


id: function:867fb616f5a2f7aa74c2270a327fa791
kind: function
name: compressContext
qualified_name: compressContext
file_path: open-sse/services/contextManager.ts
language: typescript
signature:
(
  body: Record<string, unknown>,
  options: { provider?: string; model?: string; maxTokens?: number; reserveTokens?: number } = {}
)


id: method:129212bbf28d74c04446689e25eaff79
kind: method
name: acquire
qualified_name: CursorSessionManager::acquire
file_path: open-sse/services/cursorSessionManager.ts
language: typescript
signature: (conversationId: string): CursorSession | undefined
docstring:
Try to reacquire an existing session for this conversation. Returns
undefined if there isn't one, if it's still running, or if it's idle
past the TTL (in which case it's closed as a side-effect).


id: method:d4045cd0a91cf4797ed8d4bd90b13e5c
kind: method
name: open
qualified_name: CursorSessionManager::open
file_path: open-sse/services/cursorSessionManager.ts
language: typescript
docstring:
Register a freshly-opened h2 stream as the session for this conversation.
Any pre-existing session for the same conversation is closed first.

signature:
(
    conversationId: string,
    h2Client: ClientHttp2Session,
    h2Req: ClientHttp2Stream,
    blobStore: Map<string, Buffer>
  ): CursorSession


id: method:0e75d4a6669c471899678ac09e877ddf
kind: method
name: release
qualified_name: CursorSessionManager::release
file_path: open-sse/services/cursorSessionManager.ts
language: typescript
signature: (session: CursorSession, finalState: "awaiting_tool_result" | "idle" | "closed"): void
docstring:
Mark a session as no longer in-flight. If finalState is
"awaiting_tool_result" the h2 stream stays open and the next acquire()
for this conversation_id can reuse it. If "idle" or "closed" the
h2 is torn down here.


id: method:f2b4f407fef91ce314dc6f7c464aa246
kind: method
name: sendToolResult
qualified_name: CursorSessionManager::sendToolResult
file_path: open-sse/services/cursorSessionManager.ts
language: typescript
docstring:
Send an MCP tool result on this session's open h2 stream. Returns true
if the openAIToolCallId matched a pending call we'd previously seen
mcp_args for; false otherwise (caller should fall back to cold-resume).

signature:
(
    session: CursorSession,
    openAIToolCallId: string,
    content: string,
    isError: boolean
  ): boolean


id: constant:bb529938696320e64e0f952c14af8d5d
kind: constant
name: EMERGENCY_FALLBACK_CONFIG
qualified_name: EMERGENCY_FALLBACK_CONFIG
file_path: open-sse/services/emergencyFallback.ts
language: typescript
signature:
= {
  enabled: true,
  provider: "nvidia",
  model: "openai/gpt-oss-120b",
  triggerOn402: true,
  tri...


id: function:24232cbf86c274731f2c3a95c13880cb
kind: function
name: shouldUseFallback
qualified_name: shouldUseFallback
file_path: open-sse/services/emergencyFallback.ts
language: typescript
signature:
(
  status: number,
  errorBody: string,
  requestHasTools: boolean,
  config: EmergencyFallbackConfig = EMERGENCY_FALLBACK_CONFIG
): FallbackResult


id: import:41ad5bc83086cc454d87471f77962985
kind: import
name: ./accountFallback.ts
qualified_name: ./accountFallback.ts
file_path: open-sse/services/errorClassifier.ts
language: typescript
signature:
import {
  isAccountDeactivated,
  isCreditsExhausted,
  isDailyQuotaExhausted,
  isOAuthInvalidToken,
} from "./accountFallback.ts";


id: constant:cb486d1a166431ed866e65f8d9fc2d58
kind: constant
name: PROVIDER_ERROR_TYPES
qualified_name: PROVIDER_ERROR_TYPES
file_path: open-sse/services/errorClassifier.ts
language: typescript
signature:
= {
  RATE_LIMITED: "rate_limited",
  UNAUTHORIZED: "unauthorized",
  ACCOUNT_DEACTIVATED: "account_de...


id: constant:a17da8204ea9e801d4ffab488b13ff26
kind: constant
name: CONTEXT_OVERFLOW_SIGNALS
qualified_name: CONTEXT_OVERFLOW_SIGNALS
file_path: open-sse/services/errorClassifier.ts
language: typescript
signature:
= [
  "context overflow",
  "prompt too large",
  "context window",
  "maximum context",
  "exceeds co...


id: import:87da9ebc418894640b23ab9c0b24cb80
kind: import
name: ./cloudCodeHeaders.ts
qualified_name: ./cloudCodeHeaders.ts
file_path: open-sse/services/geminiCliHeaders.ts
language: typescript
signature:
import {
  getCloudCodeNodeApiClientHeader,
  normalizeCloudCodeArch,
  normalizeCloudCodePlatform,
} from "./cloudCodeHeaders.ts";


id: function:2ab0ca72ed11ddc34d1a29961f8cb3b5
kind: function
name: getGeminiCliHeaders
qualified_name: getGeminiCliHeaders
file_path: open-sse/services/geminiCliHeaders.ts
language: typescript
signature:
(
  model: string,
  accessToken: string,
  accept: "application/json" | "*/*"
): Record<string, string>


id: import:cc4db47973342765b256db85af148693
kind: import
name: ./quotaPreflight.ts
qualified_name: ./quotaPreflight.ts
file_path: open-sse/services/genericQuotaFetcher.ts
language: typescript
signature:
import {
  getQuotaFetcher,
  registerQuotaFetcher,
  registerQuotaWindows,
  type QuotaFetcher,
  type QuotaInfo,
} from "./quotaPreflight.ts";


id: constant:4531e72483f4b31a6d39ebd05306552c
kind: constant
name: CACHE_TTL_MS
qualified_name: CACHE_TTL_MS
file_path: open-sse/services/genericQuotaFetcher.ts
language: typescript
signature: = 60_000
docstring:
60s — matches Codex's TTL. Long enough to avoid hammering upstream usage
endpoints on every routing decision, short enough that a near-exhausted
account is skipped within one minute of crossing its threshold.


id: constant:884ef8b8b449fdf44b64bfaed6e718a2
kind: constant
name: _cacheCleanup
qualified_name: _cacheCleanup
file_path: open-sse/services/genericQuotaFetcher.ts
language: typescript
docstring: Auto-cleanup stale entries — same shape as codexQuotaFetcher.
signature:
= setInterval(() => {
  const now = Date.now();
  for (const [key, entry] of cache) {
    if (now - en...


id: function:eefd1d6ee11cd26185b17b8fcd02d9e0
kind: function
name: percentUsedForQuota
qualified_name: percentUsedForQuota
file_path: open-sse/services/genericQuotaFetcher.ts
language: typescript
signature: (entry: unknown): number | null
docstring:
Compute percentUsed (0-1) for a single quota entry. Prefers the explicit
remainingPercentage / used / total fields surfaced by per-provider
fetchers (see `usage.ts`). Returns null when the entry is unlimited or
doesn't expose enough data to compute a percent — preflight ignores
those windows.


id: constant:2b2aeab20e61ea874e0a57af0693c879
kind: constant
name: CODE_KEYWORDS
qualified_name: CODE_KEYWORDS
file_path: open-sse/services/intentClassifier.ts
language: typescript
signature:
= [
  // English
  "function",
  "class",
  "import",
  "def",
  "SELECT",
  "async",
  "await",
  "co...


id: constant:99ec590f1c11f05b95f25dff99761c10
kind: constant
name: REASONING_KEYWORDS
qualified_name: REASONING_KEYWORDS
file_path: open-sse/services/intentClassifier.ts
language: typescript
signature:
= [
  // English
  "prove",
  "theorem",
  "derive",
  "step by step",
  "chain of thought",
  "formal...


id: constant:4b7757f5e4087d778a591d0c780c4753
kind: constant
name: MATH_KEYWORDS
qualified_name: MATH_KEYWORDS
file_path: open-sse/services/intentClassifier.ts
language: typescript
signature:
= [
  // English
  "calculate",
  "solve",
  "equation",
  "proof",
  "formula",
  "integral",
  "deri...


id: constant:1a8cd41afd2c0c65a4e1e81d701f6862
kind: constant
name: CREATIVE_KEYWORDS
qualified_name: CREATIVE_KEYWORDS
file_path: open-sse/services/intentClassifier.ts
language: typescript
signature:
= [
  // English
  "write",
  "story",
  "poem",
  "creative",
  "brainstorm",
  "blog",
  "article",
...


id: constant:d830be7bbafe230da5e9ced801b43a11
kind: constant
name: SIMPLE_KEYWORDS
qualified_name: SIMPLE_KEYWORDS
file_path: open-sse/services/intentClassifier.ts
language: typescript
signature:
= [
  // English
  "what is",
  "define",
  "translate",
  "hello",
  "yes or no",
  "summarize",
  "l...


id: variable:99bf66d1d3902dd247f449f6f6173b3e
kind: variable
name: _config
qualified_name: _config
file_path: open-sse/services/ipFilter.ts
language: typescript
docstring: In-memory IP lists
signature:
= {
  enabled: false,
  mode: "blacklist", // "blacklist" | "whitelist" | "whitelist-priority"
  black...


id: import:a9997dcc7fcaed0caebb385bf148fd2c
kind: import
name: ./specificityDetector
qualified_name: ./specificityDetector
file_path: open-sse/services/manifestAdapter.ts
language: typescript
signature:
import {
  analyzeSpecificity,
  getSpecificityLevel,
  getRecommendedMinTier,
} from "./specificityDetector";


id: function:61d6cb8d123de8c7eb87c0459aa2b67a
kind: function
name: determineStrategyModifier
qualified_name: determineStrategyModifier
file_path: open-sse/services/manifestAdapter.ts
language: typescript
signature:
(
  level: SpecificityLevel,
  eligibleCount: number,
  underqualifiedCount: number
): StrategyModifier


id: constant:e9153ba1c2a629c262049b3b1b944f08
kind: constant
name: ALIAS_TO_PROVIDER_ID
qualified_name: ALIAS_TO_PROVIDER_ID
file_path: open-sse/services/model.ts
language: typescript
signature: = {}
docstring:
Derive alias→provider mapping from the single source of truth (PROVIDER_ID_TO_ALIAS)
This prevents the two maps from drifting out of sync


id: constant:9953fd42ef14d8bd6eae637fed1157c8
kind: constant
name: PROVIDER_MODEL_ALIASES
qualified_name: PROVIDER_MODEL_ALIASES
file_path: open-sse/services/model.ts
language: typescript
docstring:
Provider-scoped legacy model aliases. Used to normalize provider/model inputs
and keep backward compatibility when upstream IDs change.

signature:
= {
  github: {
    "claude-4.5-opus": "claude-opus-4-5-20251101",
    "claude-opus-4.5": "claude-opus...


id: constant:57c66634930bc983feaa08ee2275efc6
kind: constant
name: CROSS_PROXY_MODEL_ALIASES
qualified_name: CROSS_PROXY_MODEL_ALIASES
file_path: open-sse/services/model.ts
language: typescript
signature:
= {
  "gpt-oss:120b": "gpt-oss-120b",
  "deepseek-v3.2-chat": "deepseek-v3.2",
  "deepseek-v3-2": "dee...


id: constant:4e55724b67a3fb32c1e3398f2500d22e
kind: constant
name: CROSS_PROXY_MODEL_ALIASES_LOWER
qualified_name: CROSS_PROXY_MODEL_ALIASES_LOWER
file_path: open-sse/services/model.ts
language: typescript
signature:
= Object.fromEntries(
  Object.entries(CROSS_PROXY_MODEL_ALIASES).map(([alias, canonical]) => [
    al...


id: constant:def17b9353730c9eaaedd66f96a0b6f6
kind: constant
name: BUILT_IN_ALIASES
qualified_name: BUILT_IN_ALIASES
file_path: open-sse/services/modelDeprecation.ts
language: typescript
docstring:
Model Deprecation Auto-Forward — Feature 2
Maps deprecated model IDs to their replacements so user configs
don't break when providers rename or retire models.
Supports both built-in aliases (static) and custom aliases (persisted via Settings API).
── Built-in Deprecation Aliases ────────────────────────────────────────────
These are known renames/retirements across providers.
Format: deprecated ID → current ID

signature:
= {
  // Gemini legacy → current
  "gemini-pro": "gemini-2.5-pro",
  "gemini-pro-vision": "gemini-2.5-...


id: constant:814340d15b963549c33069e61aca66b7
kind: constant
name: MODEL_FAMILIES
qualified_name: MODEL_FAMILIES
file_path: open-sse/services/modelFamilyFallback.ts
language: typescript
docstring:
── Model Family Definitions ─────────────────────────────────────────────────
Ordered candidate lists per model family.
First entry is the most preferred; fallback proceeds in order.

signature:
= {
  // Gemini 3 / 3.1 Pro family — ordered by preference
  "gemini-3-pro": [
    "gemini-3.1-pro-pre...


id: constant:c8882968b3393d38d6c6b3eb8b6bd111
kind: constant
name: MODEL_UNAVAILABLE_FRAGMENTS
qualified_name: MODEL_UNAVAILABLE_FRAGMENTS
file_path: open-sse/services/modelFamilyFallback.ts
language: typescript
docstring:
── Error Detection ──────────────────────────────────────────────────────────
Error message fragments that indicate the requested model is unavailable
for the current account/provider, as opposed to a transient error.

signature:
= [
  "model not found",
  "model_not_found",
  "model not available",
  "model is not available",
  "...


id: function:3eb5d887e6ffaaca7d7cb3938b8628ab
kind: function
name: stripIncompatibleMessageContent
qualified_name: stripIncompatibleMessageContent
file_path: open-sse/services/modelStrip.ts
language: typescript
signature:
(
  messages: unknown,
  stripTypes: readonly string[]
): { messages: unknown; removedParts: number }


id: constant:1f6e071adb6710909f5105a8399b2b77
kind: constant
name: MODELSCOPE_THROTTLE_SIGNALS
qualified_name: MODELSCOPE_THROTTLE_SIGNALS
file_path: open-sse/services/modelscopePolicy.ts
language: typescript
signature:
= [
  "throttling",
  "throttled",
  "rate limit",
  "too many requests",
  "batch requests",
  "alloc...


id: function:661e91dde8e7b7ab9cca6ababd557cc4
kind: function
name: applyPayloadRules
qualified_name: applyPayloadRules
file_path: open-sse/services/payloadRules.ts
language: typescript
signature:
(
  payload: JsonRecord,
  model: string,
  protocol: string | string[],
  rules: PayloadRulesConfig
)


id: import:84f192e97e350167c6bc1c0744720f6e
kind: import
name: ./claudeCodeCompatible.ts
qualified_name: ./claudeCodeCompatible.ts
file_path: open-sse/services/provider.ts
language: typescript
signature:
import {
  buildClaudeCodeCompatibleHeaders,
  CLAUDE_CODE_COMPATIBLE_DEFAULT_CHAT_PATH,
  joinClaudeCodeCompatibleUrl,
} from "./claudeCodeCompatible.ts";


id: function:fa5671f08943826f25afc929c59fa272
kind: function
name: buildProviderUrl
qualified_name: buildProviderUrl
file_path: open-sse/services/provider.ts
language: typescript
signature:
(
  provider,
  model,
  stream = true,
  options: {
    baseUrl?: string;
    baseUrlIndex?: number;
    providerSpecificData?: Record<string, unknown> | null;
  } = {}
)


id: constant:ef3f26d45d7c86681a760db0ae6d9adc
kind: constant
name: KNOWN_MODEL_PRICING
qualified_name: KNOWN_MODEL_PRICING
file_path: open-sse/services/providerCostData.ts
language: typescript
signature:
= {
  "gpt-4o": { inputCostPer1M: 2.5, outputCostPer1M: 10.0, isFree: false },
  "gpt-4o-mini": { inpu...


id: constant:bb3765d62f5bff0f5b137fda91fc7580
kind: constant
name: QODER_STATIC_MODELS
qualified_name: QODER_STATIC_MODELS
file_path: open-sse/services/qoderCli.ts
language: typescript
signature:
= [
  { id: "qoder-rome-30ba3b", name: "Qoder ROME" },
  { id: "qwen3-coder-plus", name: "Qwen3 Coder ...


id: function:292708fe7bca870e2f476936906f9e91
kind: function
name: buildQoderChunk
qualified_name: buildQoderChunk
file_path: open-sse/services/qoderCli.ts
language: typescript
signature:
({
  id,
  model,
  created,
  delta,
  finishReason = null,
}: {
  id: string;
  model: string;
  created: number;
  delta: Record<string, unknown>;
  finishReason?: string | null;
})


id: constant:623bbbbfebdeaff5ffcb2e7a06821c4b
kind: constant
name: PUBLIC_KEY
qualified_name: PUBLIC_KEY
file_path: open-sse/services/qoderCli.ts
language: typescript
signature:
= `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
4k6Pz1E...


id: function:99ce173a137793316df7baab1278200c
kind: function
name: validateQoderCliPat
qualified_name: validateQoderCliPat
file_path: open-sse/services/qoderCli.ts
language: typescript
signature:
({
  apiKey,
  providerSpecificData = {},
}: {
  apiKey: string;
  providerSpecificData?: JsonRecord;
})


id: function:65f3119e7915d7cbbef06b17c25b6582
kind: function
name: startQuotaMonitor
qualified_name: startQuotaMonitor
file_path: open-sse/services/quotaMonitor.ts
language: typescript
signature:
(
  sessionId: string,
  provider: string,
  accountId: string,
  connection: Record<string, unknown>
): void


id: constant:30b1360d354b23c6e80950227754bc37
kind: constant
name: quotaWindowsRegistry
qualified_name: quotaWindowsRegistry
file_path: open-sse/services/quotaPreflight.ts
language: typescript
signature: = new Map<string, readonly string[]>()
docstring:
Registry of named quota windows per provider. Used by the dashboard to
discover which inputs to render in the cutoffs modal. Providers without
multiple windows can skip registration — preflight falls back to the
single-signal `percentUsed` path in that case.


id: constant:fc6d656014d2a8fc853e647fffe64b1a
kind: constant
name: DEFAULT_MIN_REMAINING_PERCENT
qualified_name: DEFAULT_MIN_REMAINING_PERCENT
file_path: open-sse/services/quotaPreflight.ts
language: typescript
signature: = 2
docstring:
Thresholds use "minimum remaining %" semantics so the numbers match the
dashboard's quota bars (which show remaining %). A cutoff of 2 means
"block when only 2% remaining" (= 98% used). Warn fires earlier — at
20% remaining (= 80% used) by default.


id: function:0ddc6c696c6483149f65601b146487ca
kind: function
name: resolveOrDefault
qualified_name: resolveOrDefault
file_path: open-sse/services/quotaPreflight.ts
language: typescript
signature:
(
  resolver: ((window: string | null) => number) | undefined,
  window: string | null,
  fallbackPercent: number
): number


id: function:a498b297d10e59ec3a7f72a5ea0a3e42
kind: function
name: preflightQuota
qualified_name: preflightQuota
file_path: open-sse/services/quotaPreflight.ts
language: typescript
signature:
(
  provider: string,
  connectionId: string,
  connection: Record<string, unknown>,
  thresholds?: PreflightQuotaThresholds
): Promise<PreflightQuotaResult>


id: import:15e44f4b49cb273290409b3645b15362
kind: import
name: ../../src/lib/resilience/settings
qualified_name: ../../src/lib/resilience/settings
file_path: open-sse/services/rateLimitManager.ts
language: typescript
signature:
import {
  DEFAULT_RESILIENCE_SETTINGS,
  resolveResilienceSettings,
  type RequestQueueSettings,
} from "../../src/lib/resilience/settings";


id: constant:22f71051f6bc51e6f9122a4498b472b4
kind: constant
name: lastDispatchAt
qualified_name: lastDispatchAt
file_path: open-sse/services/rateLimitManager.ts
language: typescript
signature: = new Map<string, number>()
docstring:
Watchdog: detect Bottleneck limiters that are wedged (queue has work, but no
jobs are dispatched). When the reservoir/refresh state desyncs from reality,
this catches it and force-resets so traffic isn't stuck forever.


id: constant:9cdbc188d1b65f40dd039ceaf52b58ba
kind: constant
name: WEDGE_THRESHOLD_MS
qualified_name: WEDGE_THRESHOLD_MS
file_path: open-sse/services/rateLimitManager.ts
language: typescript
signature: = 120_000
docstring:
Threshold has to exceed any *legitimate* gap between dispatches:
- default reservoirRefreshInterval is 60s
- adaptive minTime can climb to ~60s for 1-RPM providers (see updateFromHeaders)
120s gives a 2× margin against both, while still catching the actual wedge
case we observed (queue stalled for 3+ minutes with no progress).


id: function:cc84a2da43bf64cb6767c12111081eec
kind: function
name: isAutoEnableActive
qualified_name: isAutoEnableActive
file_path: open-sse/services/rateLimitManager.ts
language: typescript
signature: (settings: RequestQueueSettings): boolean
docstring:
Env-var override for the auto-enable safety net. Highest priority — wins
over the persisted dashboard setting. Use to disable in an incident without
needing dashboard access.
  RATE_LIMIT_AUTO_ENABLE=false  → never auto-enable
  RATE_LIMIT_AUTO_ENABLE=true   → force on regardless of dashboard
  (unset)                        → use dashboard setting


id: function:bc1ea92213e699b29019965b2d6979f0
kind: function
name: shutdownLimiters
qualified_name: shutdownLimiters
file_path: open-sse/services/rateLimitManager.ts
language: typescript
signature: (): void
docstring:
Gracefully stop all limiters for process shutdown.
ONLY call this from SIGTERM/SIGINT handlers — not during runtime resets.
Calling .stop() during runtime (e.g. on 429 or connection disable) permanently
rejects future .schedule() calls, causing 502 bursts. This function is the
sole legitimate use of limiter.stop() in this module.


id: function:75786f06b365b19f7a4c91f692f502ec
kind: function
name: trackAsyncOperation
qualified_name: trackAsyncOperation
file_path: open-sse/services/rateLimitManager.ts
language: typescript
signature: (promise: Promise<T>): Promise<T>
docstring:
Only register shutdown handlers when there are active limiters to shut down.
Guard with once() so repeated registrations (e.g. test resets) don't stack.
Note: these are registered lazily in startRateLimitWatchdog() to avoid
interfering with test runner subprocess IPC teardown.


id: constant:ae526cdf37e2d461a40fa58d4ad52b72
kind: constant
name: STANDARD_HEADERS
qualified_name: STANDARD_HEADERS
file_path: open-sse/services/rateLimitManager.ts
language: typescript
docstring:
─── Header Parsing ──────────────────────────────────────────────────────────
Standard headers used by most providers (OpenAI, Fireworks, etc.)

signature:
= {
  limit: "x-ratelimit-limit-requests",
  remaining: "x-ratelimit-remaining-requests",
  reset: "x-...


id: constant:122f406a0d3ce0860d2b3fdf884a4aa8
kind: constant
name: ANTHROPIC_HEADERS
qualified_name: ANTHROPIC_HEADERS
file_path: open-sse/services/rateLimitManager.ts
language: typescript
docstring: Anthropic uses custom headers
signature:
= {
  limit: "anthropic-ratelimit-requests-limit",
  remaining: "anthropic-ratelimit-requests-remainin...


id: function:c69b80f49cbc31c778838687e701ca77
kind: function
name: parseResetTime
qualified_name: parseResetTime
file_path: open-sse/services/rateLimitManager.ts
language: typescript
signature: (value)
docstring:
Parse a reset time string into milliseconds.
Formats: "1s", "1m", "1h", "1ms", "60", ISO date, Unix timestamp


id: function:222694cea5e8689b2ab7040aaabf5802
kind: function
name: recordLearnedLimit
qualified_name: recordLearnedLimit
file_path: open-sse/services/rateLimitManager.ts
language: typescript
docstring: Record a learned limit for debounced persistence.
signature:
(
  provider: string,
  connectionId: string,
  limits: Partial<Omit<LearnedLimitEntry, "provider" | "connectionId" | "lastUpdated">>,
  model: string | null = null
)


id: constant:edba046dc1cfd2de2b19df61e3d61c28
kind: constant
name: gates
qualified_name: gates
file_path: open-sse/services/rateLimitSemaphore.ts
language: typescript
signature: = new Map()
docstring:
Rate-Limit Semaphore
Per-model concurrency limiter with FIFO queue for round-robin combo strategy.
When a model is at max concurrency, requests wait in a queue instead of failing.
When a model hits rate-limits, it's temporarily paused and queued requests wait.
All state is in-memory — resets on server restart (by design, since rate-limit
windows are typically short-lived).
@typedef {Object} ModelGate
@property {number} running - Currently running requests
@property {number} max - Max concurrent requests
@property {Array<{resolve: Function, reject: Function, timer: NodeJS.Timeout}>} queue - FIFO wait queue
@property {number|null} rateLimitedUntil - Timestamp when rate-limit expires (null = not limited)
@type {Map<string, ModelGate>}


id: function:9c905af77f2fb1301d28f81a427a8c15
kind: function
name: getGate
qualified_name: getGate
file_path: open-sse/services/rateLimitSemaphore.ts
language: typescript
signature: (modelStr, maxConcurrency = 3)
docstring:
Get or create gate for a model
@param {string} modelStr
@param {number} maxConcurrency
@returns {ModelGate}


id: import:bc98b12ba95aa6549df34d7d88c2c7ac
kind: import
name: ../../src/lib/db/reasoningCache.ts
qualified_name: ../../src/lib/db/reasoningCache.ts
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature:
import {
  clearAllReasoningCache,
  cleanupExpiredReasoning,
  deleteReasoningCache,
  getReasoningCache,
  getReasoningCacheEntries,
  getReasoningCacheStats,
  setReasoningCache,
} from "../../src/lib/db/reasoningCache.ts";


id: constant:5821c9fc4a941c81958411d918878160
kind: constant
name: REASONING_REPLAY_PROVIDERS
qualified_name: REASONING_REPLAY_PROVIDERS
file_path: open-sse/services/reasoningCache.ts
language: typescript
docstring: ──────────────── Provider/Model Detection ────────────────
signature:
= new Set([
  "deepseek",
  "opencode-go",
  "siliconflow",
  "nebius",
  "deepinfra",
  "sambanova",
...


id: constant:b78e0c2d310fe735eb219817e438dc64
kind: constant
name: REASONING_REPLAY_MODEL_PATTERNS
qualified_name: REASONING_REPLAY_MODEL_PATTERNS
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature:
= [
  /deepseek-r1/i,
  /deepseek-reasoner/i,
  /deepseek-chat/i,
  /deepseek[-/]v4[-.](flash|pro)/i,
...


id: function:9dc93844c1dfdc8e3c6ccd763b7c0c72
kind: function
name: requiresReasoningReplay
qualified_name: requiresReasoningReplay
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature:
(params: {
  provider: string;
  model: string;
  thinkingEnabled?: boolean;
  supportsReasoning?: boolean;
}): boolean


id: function:3472cf2f6ee857c366303db4a2db6501
kind: function
name: evictOldest
qualified_name: evictOldest
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature: (): void
docstring:
──────────────── Core Operations ────────────────
Evict the oldest entry from the memory cache when full.


id: function:8d4bed648dbb4616500d004b6630d86e
kind: function
name: cacheReasoningFromAssistantMessage
qualified_name: cacheReasoningFromAssistantMessage
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature:
(
  message: AssistantMessageLike | null | undefined,
  provider: string,
  model: string,
  context?: AssistantMessageCacheContext
): number


id: function:03c412e924a6c347e2f9cd1c75f3ec73
kind: function
name: getReasoningCacheServiceStats
qualified_name: getReasoningCacheServiceStats
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature:
(): {
  memoryEntries: number;
  dbEntries: number;
  totalEntries: number;
  totalChars: number;
  hits: number;
  misses: number;
  replays: number;
  replayRate: string;
  byProvider: Record<string, { entries: number; chars: number }>;
  byModel: Record<string, { entries: number; chars: number }>;
  oldestEntry: string | null;
  newestEntry: string | null;
}


id: function:0ed7fa8d59844347f9decf1119a6aecb
kind: function
name: getReasoningCacheServiceEntries
qualified_name: getReasoningCacheServiceEntries
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature:
(
  opts: {
    limit?: number;
    offset?: number;
    provider?: string;
    model?: string;
  } = {}
): unknown[]


id: constant:220415ba5d3c1fdbfa28917636b67393
kind: constant
name: DEFAULT_CLEANUP_INTERVAL_MS
qualified_name: DEFAULT_CLEANUP_INTERVAL_MS
file_path: open-sse/services/reasoningCache.ts
language: typescript
signature: = 30 * 60 * 1000
docstring:
──────────────── Auto-start periodic cleanup ────────────────

server-init.ts was supposed to start the cleanup job, but that module is
never imported anywhere (it is stranded/dead code).  As a result, the
reasoning_cache SQLite table accumulates expired entries indefinitely.

Fix: start the periodic cleanup directly from this module so it runs
regardless of how the server boots.  On first import we run one
immediate sweep, then schedule a 30-minute interval.

See: src/lib/jobs/reasoningCacheCleanupJob.ts (the original job module,
which also remains valid if server-init.ts ever gets wired in).


id: function:3c5a7aa52d2426a8b099cd399924f73f
kind: function
name: deduplicate
qualified_name: deduplicate
file_path: open-sse/services/requestDedup.ts
language: typescript
signature:
(
  hash: string,
  fn: () => Promise<T>,
  config: DedupConfig = DEFAULT_DEDUP_CONFIG
): Promise<DedupResult<T>>


id: function:014779fcf5be8a917999cd1b7457d441
kind: function
name: sanitizeFunctionName
qualified_name: sanitizeFunctionName
file_path: open-sse/services/responsesInputSanitizer.ts
language: typescript
signature: (name: string): string
docstring:
OpenAI Responses API enforces two constraints on name fields in input items:
1. Max 128 characters
2. Must match ^[a-zA-Z0-9_-]+$
Sanitize after cloning so upstream never sees an invalid name.


id: constant:eaefb2b749fb20376548476b378ab0b5
kind: constant
name: PROVIDERS_WITHOUT_SYSTEM_ROLE
qualified_name: PROVIDERS_WITHOUT_SYSTEM_ROLE
file_path: open-sse/services/roleNormalizer.ts
language: typescript
docstring:
Role Normalizer — Converts message roles for provider compatibility.
Fixes Issues:
1. GLM/ZhipuAI rejects `system` role → merged into first `user` message
2. OpenAI `developer` role not understood by non-OpenAI providers → normalized to `system`
3. Some providers don't support `system` role at all → prepended to user message
Provider capability matrix is defined here rather than in the registry to
avoid breaking changes to the existing RegistryEntry interface.
── Provider capabilities ──────────────────────────────────────────────────
Providers that do NOT support the `system` role in messages.
For these, system messages are merged into the first user message.
Note: This applies only to OpenAI-format passthrough providers.
Claude and Gemini have their own system message handling in dedicated translators.

signature:
= new Set([
  // Known to reject system role (from troubleshooting report)
  // GLM uses Claude format...


id: constant:5c9a34a18008b73252b411644e77a87e
kind: constant
name: PROVIDERS_PRESERVING_DEVELOPER_ROLE
qualified_name: PROVIDERS_PRESERVING_DEVELOPER_ROLE
file_path: open-sse/services/roleNormalizer.ts
language: typescript
signature: = new Set(["openai", "azure-openai", "azure", "github"])
docstring:
Providers known to natively accept the OpenAI `developer` role.
Issue #2281: When the upstream provider is OpenAI-compatible but NOT in
this allowlist (DeepSeek, MiniMax, Mimo, GLM, etc.), the default behavior
maps `developer` → `system`. Without this, requests from Codex/Responses
API clients fail with "unknown variant `developer`" 400 errors.
Operators can still force preservation per-model via the dashboard
"Compatibility → preserveOpenAIDeveloperRole = true" toggle.


id: constant:80ab2e45d47eb49c1c0785ffdd937b95
kind: constant
name: MODELS_WITHOUT_SYSTEM_ROLE
qualified_name: MODELS_WITHOUT_SYSTEM_ROLE
file_path: open-sse/services/roleNormalizer.ts
language: typescript
docstring:
Models that are known to reject the `system` role regardless of provider.
Uses prefix matching (e.g., "glm-" matches "glm-4.7", "glm-4.5", etc.)

signature:
= [
  "glm-", // ZhipuAI GLM models (prefix: glm-5.1, glm-4.7, etc.)
  "glm", // Exact match for model...


id: function:9c2f8175fa7b8a17f894c1b17c2abcbe
kind: function
name: normalizeDeveloperRole
qualified_name: normalizeDeveloperRole
file_path: open-sse/services/roleNormalizer.ts
language: typescript
signature:
(
  messages: NormalizedMessage[] | unknown,
  targetFormat: string,
  preserveDeveloperRole?: boolean,
  provider?: string
): NormalizedMessage[] | unknown


id: function:514b0adcf01da92193eded6e70098037
kind: function
name: normalizeSystemRole
qualified_name: normalizeSystemRole
file_path: open-sse/services/roleNormalizer.ts
language: typescript
signature:
(
  messages: NormalizedMessage[] | unknown,
  provider: string,
  model: string
): NormalizedMessage[] | unknown


id: function:15b3b9e4824b040c8afdf05f2d0ba68f
kind: function
name: normalizeRoles
qualified_name: normalizeRoles
file_path: open-sse/services/roleNormalizer.ts
language: typescript
signature:
(
  messages: NormalizedMessage[] | unknown,
  provider: string,
  model: string,
  targetFormat: string,
  preserveDeveloperRole?: boolean
): NormalizedMessage[] | unknown


id: function:ddb686d71fd0779f053a2edbd694d3aa
kind: function
name: normalizeQuery
qualified_name: normalizeQuery
file_path: open-sse/services/searchCache.ts
language: typescript
signature: (query: string): string
docstring:
Normalize a query for cache key computation.
NFKC normalization, lowercase, trim, collapse whitespace.


id: function:87a61b10f24a945f1a62b4a0831a5fa7
kind: function
name: computeCacheKey
qualified_name: computeCacheKey
file_path: open-sse/services/searchCache.ts
language: typescript
signature:
(
  query: string,
  provider: string,
  searchType: string,
  maxResults: number,
  country?: string,
  language?: string,
  filters?: unknown
): string


id: function:63bad81f2ac2f928ab0b088acd113cdb
kind: function
name: evictIfNeeded
qualified_name: evictIfNeeded
file_path: open-sse/services/searchCache.ts
language: typescript
signature: (): void
docstring:
Evict expired entries and enforce size bound.
Called lazily on writes. O(n) worst case but amortized O(1).


id: function:d21ba9672190903028141a86656c8b74
kind: function
name: getOrCoalesce
qualified_name: getOrCoalesce
file_path: open-sse/services/searchCache.ts
language: typescript
signature:
(
  key: string,
  ttlMs: number,
  fetchFn: () => Promise<T>
): Promise<{ data: T; cached: boolean }>


id: constant:4d9f00bb6253d8fe5de5db20bfc26669
kind: constant
name: sessions
qualified_name: sessions
file_path: open-sse/services/sessionManager.ts
language: typescript
signature: = new Map<string, SessionEntry>()
docstring:
In-memory session store with metadata
key: sessionId → { createdAt, lastActive, requestCount, connectionId? }


id: constant:458d4350295e7a3fb272826aea89b3a5
kind: constant
name: _cleanupTimer
qualified_name: _cleanupTimer
file_path: open-sse/services/sessionManager.ts
language: typescript
signature:
= setInterval(() => {
  const now = Date.now();
  for (const [key, entry] of sessions) {
    if (now -...


id: function:02622f2ec0c6efe35aeeae8d96ca997c
kind: function
name: generateSessionId
qualified_name: generateSessionId
file_path: open-sse/services/sessionManager.ts
language: typescript
signature:
(
  body: SessionBody | null | undefined,
  options: SessionFingerprintOptions = {}
): string | null


id: constant:e80612886b7876678bb94325df5cea4c
kind: constant
name: activeSessionsByKey
qualified_name: activeSessionsByKey
file_path: open-sse/services/sessionManager.ts
language: typescript
signature: = new Map<string, Set<string>>()
docstring:
─── T08: Per-API-Key Session Limit ─────────────────────────────────────────
Tracks concurrent sticky sessions per API key and enforces max_sessions limits.
Ref: sub2api PR #634 (fix: stabilize session hash + add user-level session limit)
Map: apiKeyId → Set<sessionId>


id: function:aece0d50d671f325f3c3245b937743c4
kind: function
name: checkSessionLimit
qualified_name: checkSessionLimit
file_path: open-sse/services/sessionManager.ts
language: typescript
signature:
(
  apiKeyId: string,
  maxSessions: number
): { code: "SESSION_LIMIT_EXCEEDED"; message: string; limit: number; current: number } | null


id: interface:a17da5063c52c63935f785e81b928c74
kind: interface
name: SignatureContext
qualified_name: SignatureContext
file_path: open-sse/services/signatureCache.ts
language: typescript
docstring:
Signature Cache — Phase 3
Dynamic 3-layer cache for thinking signatures (tool, model family, session).
Replaces hardcoded thinking signature patterns with adaptive detection.
3-layer cache: tool → model family → session
Each layer stores patterns detected from responses


id: constant:6345d2b39a15a99c0321e697ae1b7cc0
kind: constant
name: layers
qualified_name: layers
file_path: open-sse/services/signatureCache.ts
language: typescript
signature:
= {
  tool: new Map<string, Set<string>>(), // e.g. "cursor" → Set of signature patterns
  family: new...


id: constant:705fc3707f330f796f446d5b4f33cf77
kind: constant
name: DEFAULT_SIGNATURES
qualified_name: DEFAULT_SIGNATURES
file_path: open-sse/services/signatureCache.ts
language: typescript
docstring: Known default signatures (bootstrap — will be supplemented by learning)
signature:
= [
  "<antThinking>",
  "</antThinking>",
  "<thinking>",
  "</thinking>",
  "<internal_thought>",
  ...


id: import:adeeca3908b6b98c21d4ea103add0c2a
kind: import
name: ./specificityTypes
qualified_name: ./specificityTypes
file_path: open-sse/services/specificityDetector.ts
language: typescript
signature:
import type { SpecificityResult, SpecificityBreakdown, SpecificityLevel } from "./specificityTypes";


id: variable:e03abe3e2b91f385496a72d7667f972e
kind: variable
name: _config
qualified_name: _config
file_path: open-sse/services/systemPrompt.ts
language: typescript
signature: = { enabled: false, prompt: "", }
docstring:
System Prompt Injection — Phase 10
Injects a global system prompt into all requests at proxy level.
In-memory config


id: import:7d8eec209ba60fc76d4a53601beace46
kind: import
name: ./ccBridgeTransforms.ts
qualified_name: ./ccBridgeTransforms.ts
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature:
import {
  applyCcBridgeTransformPipeline,
  CLAUDE_AGENT_SDK_IDENTITY,
  DEFAULT_CC_BRIDGE_PIPELINE,
  DEFAULT_IDENTITY_PREFIXES,
  DEFAULT_PARAGRAPH_REMOVAL_ANCHORS,
  DEFAULT_TEXT_REPLACEMENTS,
} from "./ccBridgeTransforms.ts";


id: import:7f11e0952f800edae9794f8cc4efc44b
kind: import
name: ./ccBridgeTransforms.ts
qualified_name: ./ccBridgeTransforms.ts
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature:
import type {
  CcBridgeTransformsConfig,
  ReplaceTextOp,
  TransformOp as BaseTransformOp,
} from "./ccBridgeTransforms.ts";


id: constant:c169fac3ecc574ce08409ddf3fb023df
kind: constant
name: DEFAULT_OBFUSCATE_WORDS
qualified_name: DEFAULT_OBFUSCATE_WORDS
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature:
= [
  // legacy hardcoded set
  "opencode",
  "open-code",
  "cline",
  "roo-cline",
  "roo_cline",
  ...


id: constant:7ebb358176a9486977dd13a7bdb1bf7d
kind: constant
name: DEFAULT_CLAUDE_PIPELINE
qualified_name: DEFAULT_CLAUDE_PIPELINE
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature:
= [
  // Drop paragraphs containing 3rd-party-agent anchor URLs (anomalyco/opencode,
  // opencode.ai/...


id: constant:7c32aff506e8ebb300362e08cb357f87
kind: constant
name: DEFAULT_CC_BRIDGE_PROVIDER_PIPELINE
qualified_name: DEFAULT_CC_BRIDGE_PROVIDER_PIPELINE
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature:
= [
  // Extra Open WebUI anchors (the base pipeline only carries OpenCode/Cline/
  // Cursor/Continue...


id: constant:701a74da839c581ab29000b125e29a21
kind: constant
name: DEFAULT_SYSTEM_TRANSFORMS_CONFIG
qualified_name: DEFAULT_SYSTEM_TRANSFORMS_CONFIG
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature:
= {
  providers: {
    [PROVIDER_CLAUDE]: {
      // Enabled by default — matches the module-level doc...


id: interface:2ba8a13b10ff9663f38096cd98d47633
kind: interface
name: RequestBody
qualified_name: RequestBody
file_path: open-sse/services/systemTransforms.ts
language: typescript
docstring:
────────────────────────────────────────────────────────────────────────────
Body shape helpers (mirrors ccBridgeTransforms.ts internals).
────────────────────────────────────────────────────────────────────────────


id: function:beeb3b9ec5a3b879e8d62f48085a62da
kind: function
name: escapeRegex
qualified_name: escapeRegex
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature: (str: string): string
docstring:
────────────────────────────────────────────────────────────────────────────
Op: obfuscate_words (the only op kind beyond the base set).
────────────────────────────────────────────────────────────────────────────


id: function:f9be6bea3da121ac0de7b1f27269d494
kind: function
name: obfuscateWithList
qualified_name: obfuscateWithList
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature: (text: string, words: string[]): string
docstring:
Stateless variant of `obfuscateSensitiveWords` — uses the supplied word
list instead of the module-level singleton, so concurrent requests with
different op configs do not race.


id: function:16b1924c0e5c8c1bdd61eb5088f880a0
kind: function
name: applySystemTransformPipeline
qualified_name: applySystemTransformPipeline
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature:
(
  providerId: string,
  body: RequestBody,
  config: SystemTransformsConfig = getSystemTransformsConfig()
): ApplyPipelineResult


id: variable:84ac9f6b5bdadf2c4bf286d5505aee37
kind: variable
name: _systemTransformsConfig
qualified_name: _systemTransformsConfig
file_path: open-sse/services/systemTransforms.ts
language: typescript
signature: = DEFAULT_SYSTEM_TRANSFORMS_CONFIG
docstring:
────────────────────────────────────────────────────────────────────────────
Runtime singleton.
────────────────────────────────────────────────────────────────────────────


id: constant:965f51fc23094cc567465b430ebf9335
kind: constant
name: TASK_PATTERNS
qualified_name: TASK_PATTERNS
file_path: open-sse/services/taskAwareRouter.ts
language: typescript
docstring: ── Default detection patterns ───────────────────────────────────────────────
signature:
= {
  coding: {
    patterns: [
      "write code",
      "write a function",
      "implement",
     ...


id: constant:f8679dd02d5ff4d659e345c26790011a
kind: constant
name: DEFAULT_TASK_MODEL_MAP
qualified_name: DEFAULT_TASK_MODEL_MAP
file_path: open-sse/services/taskAwareRouter.ts
language: typescript
docstring: ── Default task → model map ─────────────────────────────────────────────────
signature:
= {
  coding: "deepseek/deepseek-chat", // DeepSeek V3.2 — best coding OSS
  creative: "", // No overr...


id: variable:9dab94f55de5b7e42bfa700e021aa102
kind: variable
name: _config
qualified_name: _config
file_path: open-sse/services/taskAwareRouter.ts
language: typescript
docstring: ── State ────────────────────────────────────────────────────────────────────
signature:
= {
  enabled: false, // User must explicitly enable
  taskModelMap: { ...DEFAULT_TASK_MODEL_MAP },
  ...


id: constant:06c65eeead443f0b1a1c95894c3ec34d
kind: constant
name: ThinkingMode
qualified_name: ThinkingMode
file_path: open-sse/services/thinkingBudget.ts
language: typescript
signature:
= {
  AUTO: "auto", // Let provider decide (remove client's budget)
  PASSTHROUGH: "passthrough", // N...


id: import:2ab3ccb9d1f4751c47385eca5373d520
kind: import
name: @/lib/modelCapabilities
qualified_name: @/lib/modelCapabilities
file_path: open-sse/services/thinkingBudget.ts
language: typescript
signature:
import {
  capThinkingBudget,
  getDefaultThinkingBudget,
  getResolvedModelCapabilities,
  supportsReasoning,
} from "@/lib/modelCapabilities";


id: constant:a9b3039b8c51711971d4b1f47aa7484a
kind: constant
name: EFFORT_BUDGETS
qualified_name: EFFORT_BUDGETS
file_path: open-sse/services/thinkingBudget.ts
language: typescript
signature:
= {
  none: 0,
  low: 1024,
  medium: 10240,
  high: 131072, // Handled globally by capThinkingBudget ...


id: constant:213fd46ebc5cf6c41b172f22feec2b4b
kind: constant
name: THINKING_LEVEL_MAP
qualified_name: THINKING_LEVEL_MAP
file_path: open-sse/services/thinkingBudget.ts
language: typescript
signature:
= {
  none: 0,
  low: 4096,
  medium: 8192,
  high: 24576,
  max: 131072, // T11: max = full Claude bu...


id: constant:ab378428b2e52f0a0777b002da034b83
kind: constant
name: DEFAULT_THINKING_CONFIG
qualified_name: DEFAULT_THINKING_CONFIG
file_path: open-sse/services/thinkingBudget.ts
language: typescript
signature:
= {
  mode: ThinkingMode.PASSTHROUGH,
  customBudget: 10240,
  effortLevel: "medium",
} satisfies Thin...


id: constant:95e32298cf443b5971fda179084e6739
kind: constant
name: modelTierOverrideSchema
qualified_name: modelTierOverrideSchema
file_path: open-sse/services/tierConfig.ts
language: typescript
signature:
= z.object({
  provider: z.string().min(1),
  modelPattern: z.string().min(1),
  tier: z.enum(["free",...


id: constant:69f41b9473994493abdcf101920261a2
kind: constant
name: tierConfigSchema
qualified_name: tierConfigSchema
file_path: open-sse/services/tierConfig.ts
language: typescript
signature:
= z.object({
  version: z.string().default("1.0.0"),
  defaults: z.object({
    freeThreshold: z.numbe...


id: constant:6bb3270a7d5b0db8dfb06160b67a23b8
kind: constant
name: DEFAULT_TIER_CONFIG
qualified_name: DEFAULT_TIER_CONFIG
file_path: open-sse/services/tierConfig.ts
language: typescript
signature:
= {
  version: "1.0.0",
  defaults: {
    freeThreshold: 0,
    cheapThreshold: 1.0,
  },
  providerOv...


id: constant:2b86e214b9e38fcacd9f85a85190d039
kind: constant
name: refreshPromiseCache
qualified_name: refreshPromiseCache
file_path: open-sse/services/tokenRefresh.ts
language: typescript
signature: = new Map()
docstring:
In-flight refresh promise cache to prevent race conditions
Key: "provider:sha256(refreshToken)" → Value: Promise<result>


id: constant:7ac9665a631ea8eff36a349ea678c2be
kind: constant
name: connectionRefreshMutex
qualified_name: connectionRefreshMutex
file_path: open-sse/services/tokenRefresh.ts
language: typescript
signature: = new Map()
docstring:
Per-connection mutex: prevents parallel OAuth refresh for rotating tokens.
Key: connectionId → Value: { promise, waiters }
Primary dedup when credentials.connectionId is present; refreshPromiseCache is fallback.


id: function:a9a58c1146903a3fb9f8c7a4d9d0c5a6
kind: function
name: refreshWindsurfToken
qualified_name: refreshWindsurfToken
file_path: open-sse/services/tokenRefresh.ts
language: typescript
signature:
(
  refreshToken: string,
  providerSpecificData: Record<string, unknown> | null | undefined,
  log: RefreshLogger,
  proxyConfig: unknown = null
)


id: function:6eb95ea4dc35feb192d52a4d88eb6389
kind: function
name: _getAccessTokenWithStalenessCheck
qualified_name: _getAccessTokenWithStalenessCheck
file_path: open-sse/services/tokenRefresh.ts
language: typescript
signature: (provider, credentials, log, proxyConfig)
docstring:
Internal helper: performs the DB staleness check then calls the actual refresh.
Only called from the per-connection mutex path (Layer 1 above).


id: constant:20fa1f5bf3beb4befe8c2aef662ef03a
kind: constant
name: _circuitBreaker
qualified_name: _circuitBreaker
file_path: open-sse/services/tokenRefresh.ts
language: typescript
signature: = {}
docstring:
Refresh token with retry and exponential backoff
Retries on failure with increasing delay: 1s, 2s, 3s...
Includes:
- Per-provider circuit breaker (5 consecutive failures → 30min pause)
- 30s timeout per refresh attempt to prevent hanging connections
@param {function} refreshFn - Async function that returns token or null
@param {number} maxRetries - Max retry attempts (default 3)
@param {object} log - Logger instance (optional)
@param {string} provider - Provider ID for circuit breaker tracking (optional)
@returns {Promise<object|null>} Token result or null if all retries fail
─── Circuit Breaker State ──────────────────────────────────────────────────


id: constant:83234216c9af9cb980db4f2d358fc40c
kind: constant
name: TOOL_LIMIT_PATTERNS
qualified_name: TOOL_LIMIT_PATTERNS
file_path: open-sse/services/toolLimitDetector.ts
language: typescript
signature:
= [
  /'tools':\s*maximum\s+number\s+of\s+items\s+is\s+(\d+)/i,
  /Maximum\s+number\s+of\s+tools\s+(?:...


id: constant:ebee2fc0193f817f8abdc486156859c8
kind: constant
name: TOOL_LIMIT_ERROR_INDICATORS
qualified_name: TOOL_LIMIT_ERROR_INDICATORS
file_path: open-sse/services/toolLimitDetector.ts
language: typescript
signature:
= [
  "maximum number of tools",
  "too many tools",
  "tools limit",
  "'tools'",
  "maximum number o...


id: constant:6268c22486a2522b91502114e323e27a
kind: constant
name: MAX_RECURSION_DEPTH
qualified_name: MAX_RECURSION_DEPTH
file_path: open-sse/services/toolSchemaSanitizer.ts
language: typescript
signature: = 32
docstring:
Sanitize OpenAI-format tool definitions for strict upstream JSON Schema
validators (e.g. Moonshot AI behind opencode-go/kimi-k2.6).
The concrete bug this was written for: ForgeCode emits enum schemas like
  { type: "string", enum: ["a", "b", "c", null], nullable: true }
for nullable optional fields. Lenient providers (Z.AI / GLM) accept the null
entry; Moonshot rejects with
  "At path 'properties.X.enum': enum value (<nil>) does not match any type
   in [string]"
before the request reaches the model.
The fix is to strip null/undefined from `enum` arrays. Everything else here
is defensive hygiene: ensures `parameters` is always a valid object schema,
filters `required[]` to keys that exist in `properties`, and normalizes a
few other shapes that strict validators tend to reject.


id: constant:1c0f4639fc6c1a4cc989d1350de9ea2f
kind: constant
name: GEMINI_CLI_USAGE_URL
qualified_name: GEMINI_CLI_USAGE_URL
file_path: open-sse/services/usage.ts
language: typescript
signature:
= process.env.OMNIROUTE_GEMINI_CLI_USAGE_URL ??
  "https://cloudcode-pa.googleapis.com/v1internal:load...


id: import:f191812174ad54d4a5478d8da5e5b425
kind: import
name: ../config/antigravityUpstream.ts
qualified_name: ../config/antigravityUpstream.ts
file_path: open-sse/services/usage.ts
language: typescript
signature:
import {
  getAntigravityFetchAvailableModelsUrls,
  ANTIGRAVITY_BASE_URLS,
} from "../config/antigravityUpstream.ts";


id: import:46c7724ad56f2b5c88a725513c64d90b
kind: import
name: ./antigravityClientProfile.ts
qualified_name: ./antigravityClientProfile.ts
file_path: open-sse/services/usage.ts
language: typescript
signature:
import {
  applyAntigravityClientProfileHeaders,
  getAntigravityBootstrapHeaders,
  getAntigravityClientProfile,
} from "./antigravityClientProfile.ts";


id: import:bd5761ab898d693c2eb96f74b1a3f0ea
kind: import
name: ./antigravityHeaders.ts
qualified_name: ./antigravityHeaders.ts
file_path: open-sse/services/usage.ts
language: typescript
signature:
import {
  antigravityUserAgent,
  getAntigravityHeaders,
  getAntigravityLoadCodeAssistMetadata,
} from "./antigravityHeaders.ts";


