@code-yeongyu/senpi-ai 2026.8.24 → 2026.8.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/anthropic-messages.d.ts +1 -5
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +25 -13
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.d.ts.map +1 -1
- package/dist/api/azure-openai-responses.js +2 -1
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +91 -5
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +4 -2
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-vertex.d.ts.map +1 -1
- package/dist/api/google-vertex.js +4 -2
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/mistral-conversations.d.ts.map +1 -1
- package/dist/api/mistral-conversations.js +2 -0
- package/dist/api/mistral-conversations.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +93 -54
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses.js +2 -5
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/transform-messages.js +1 -1
- package/dist/api/transform-messages.js.map +1 -1
- package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
- package/dist/auth/oauth/github-copilot.js +97 -46
- package/dist/auth/oauth/github-copilot.js.map +1 -1
- package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
- package/dist/auth/oauth/kimi-coding.js +1 -14
- package/dist/auth/oauth/kimi-coding.js.map +1 -1
- package/dist/auth/pool/slots.d.ts +50 -0
- package/dist/auth/pool/slots.d.ts.map +1 -0
- package/dist/auth/pool/slots.js +129 -0
- package/dist/auth/pool/slots.js.map +1 -0
- package/dist/auth/resolve.d.ts.map +1 -1
- package/dist/auth/resolve.js +3 -1
- package/dist/auth/resolve.js.map +1 -1
- package/dist/models.d.ts +8 -1
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +16 -3
- package/dist/models.js.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.d.ts +3 -1
- package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.js +10 -1
- package/dist/providers/cloudflare-ai-gateway.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/anthropic.json +1 -1
- package/dist/providers/data/azure-openai-responses.json +1 -1
- package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/providers/data/huggingface.json +1 -1
- package/dist/providers/data/nvidia.json +1 -1
- package/dist/providers/data/openai.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/opengateway.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/zai-coding-cn.json +1 -1
- package/dist/providers/data/zai.json +1 -1
- package/dist/providers/faux.d.ts +1 -0
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +1 -0
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +4 -0
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/overflow.d.ts +16 -0
- package/dist/utils/overflow.d.ts.map +1 -1
- package/dist/utils/overflow.js +17 -1
- package/dist/utils/overflow.js.map +1 -1
- package/dist/utils/retry-profile/backoff.d.ts +14 -0
- package/dist/utils/retry-profile/backoff.d.ts.map +1 -0
- package/dist/utils/retry-profile/backoff.js +24 -0
- package/dist/utils/retry-profile/backoff.js.map +1 -0
- package/dist/utils/retry-profile/classifiers.d.ts +36 -0
- package/dist/utils/retry-profile/classifiers.d.ts.map +1 -0
- package/dist/utils/retry-profile/classifiers.js +109 -0
- package/dist/utils/retry-profile/classifiers.js.map +1 -0
- package/dist/utils/retry-profile/failure.d.ts +12 -0
- package/dist/utils/retry-profile/failure.d.ts.map +1 -0
- package/dist/utils/retry-profile/failure.js +109 -0
- package/dist/utils/retry-profile/failure.js.map +1 -0
- package/dist/utils/retry-profile/index.d.ts +9 -0
- package/dist/utils/retry-profile/index.d.ts.map +1 -0
- package/dist/utils/retry-profile/index.js +6 -0
- package/dist/utils/retry-profile/index.js.map +1 -0
- package/dist/utils/retry-profile/planner.d.ts +46 -0
- package/dist/utils/retry-profile/planner.d.ts.map +1 -0
- package/dist/utils/retry-profile/planner.js +41 -0
- package/dist/utils/retry-profile/planner.js.map +1 -0
- package/dist/utils/retry-profile/profiles.d.ts +4 -0
- package/dist/utils/retry-profile/profiles.d.ts.map +1 -0
- package/dist/utils/retry-profile/profiles.js +93 -0
- package/dist/utils/retry-profile/profiles.js.map +1 -0
- package/dist/utils/retry-profile/types.d.ts +121 -0
- package/dist/utils/retry-profile/types.d.ts.map +1 -0
- package/dist/utils/retry-profile/types.js +11 -0
- package/dist/utils/retry-profile/types.js.map +1 -0
- package/dist/utils/retry.d.ts +12 -0
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +25 -5
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/sleep.d.ts +2 -0
- package/dist/utils/sleep.d.ts.map +1 -0
- package/dist/utils/sleep.js +15 -0
- package/dist/utils/sleep.js.map +1 -0
- package/package.json +19 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mistral-conversations.js","sourceRoot":"","sources":["../../src/api/mistral-conversations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAejE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B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AAC;AAED,SAAS,kBAAkB,CAC1B,KAAqC,EACrC,KAA2D;IAE3D,OAAO,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,KAAK,CAAC,IAAI,MAAM,CAA2B,CAAC;AAC9E,CAAC;AAED,SAAS,aAAa,CACrB,MAAoC;IAEpC,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAC9B,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,UAAU,EAAE,CAAC;QACzF,OAAO,MAAM,CAAC;IACf,CAAC;IACD,OAAO;QACN,IAAI,EAAE,UAAU;QAChB,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE;KACxC,CAAC;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,MAAqB;IAC/C,IAAI,MAAM,KAAK,IAAI;QAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;IACnD,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,MAAM;YACV,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,KAAK,QAAQ,CAAC;QACd,KAAK,cAAc;YAClB,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;QACjC,KAAK,YAAY;YAChB,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;QAClC,KAAK,OAAO;YACX,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,CAAC;QAC9E;YACC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,EAAE,0BAA0B,MAAM,EAAE,EAAE,CAAC;IACnF,CAAC;AACF,CAAC","sourcesContent":["import { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tContext,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n} from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { getJsonSchemaToolParameters, resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { applyExtraBody, buildBaseOptions, MISTRAL_RESERVED_BODY_KEYS } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\nconst MISTRAL_TOOL_CALL_ID_LENGTH = 9;\nconst MAX_MISTRAL_ERROR_BODY_CHARS = 4000;\n\n/**\n * Provider-specific options for the Mistral API.\n */\ntype MistralReasoningEffort = \"none\" | \"high\";\n\nexport interface MistralOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } };\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n}\n\ntype MistralContentChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"image_url\"; imageUrl: string }\n\t| { type: \"thinking\"; thinking: Array<{ type: \"text\"; text: string }> };\n\ntype MistralRequestToolCall = {\n\tid: string;\n\ttype: \"function\";\n\tfunction: { name: string; arguments: string };\n\tindex: number;\n};\n\ntype MistralChatMessage = {\n\trole: \"system\" | \"user\" | \"assistant\" | \"tool\";\n\tcontent?: string | MistralContentChunk[];\n\ttoolCalls?: MistralRequestToolCall[];\n\ttoolCallId?: string;\n\tname?: string;\n\tprefix?: boolean;\n};\n\ntype MistralFunctionTool = {\n\ttype: \"function\";\n\tfunction: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: Record<string, unknown>;\n\t\tstrict: boolean;\n\t};\n};\n\ntype MistralChatPayload = {\n\t[key: string]: unknown;\n\tmodel: string;\n\tstream: boolean;\n\tmessages: MistralChatMessage[];\n\ttools?: MistralFunctionTool[];\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttoolChoice?: Exclude<MistralOptions[\"toolChoice\"], undefined>;\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n\tpromptCacheKey?: string;\n};\n\ntype MistralStreamContentChunk = {\n\ttype: string;\n\ttext?: string;\n\tthinking?: Array<{ text?: string }>;\n};\n\ntype MistralStreamToolCall = {\n\tid?: string;\n\tindex?: number;\n\tfunction: {\n\t\tname: string;\n\t\targuments: string | Record<string, unknown>;\n\t};\n};\n\ntype MistralCompletionEvent = {\n\tdata: {\n\t\tid?: string;\n\t\tusage?: {\n\t\t\t[key: string]: unknown;\n\t\t\tprompt_tokens?: number;\n\t\t\tcompletion_tokens?: number;\n\t\t\ttotal_tokens?: number;\n\t\t};\n\t\tchoices: Array<{\n\t\t\tfinish_reason?: string | null;\n\t\t\tdelta: {\n\t\t\t\tcontent?: string | MistralStreamContentChunk[] | null;\n\t\t\t\ttool_calls?: MistralStreamToolCall[] | null;\n\t\t\t};\n\t\t}>;\n\t};\n};\n\n/**\n * Stream responses from the native Mistral Chat Completions endpoint.\n */\nexport const stream: StreamFunction<\"mistral-conversations\", MistralOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: MistralOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output = createOutput(model);\n\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\n\t\t\tconst normalizeMistralToolCallId = createMistralToolCallIdNormalizer();\n\t\t\tconst preserveThinking = options?.promptMode === \"reasoning\" || options?.reasoningEffort !== undefined;\n\t\t\tconst transformedMessages = transformMessages(\n\t\t\t\tcontext.messages,\n\t\t\t\tmodel,\n\t\t\t\t(id) => normalizeMistralToolCallId(id),\n\t\t\t\t{\n\t\t\t\t\tpreserveThinking,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tlet payload = buildChatPayload(model, context, transformedMessages, options);\n\t\t\tconst nextPayload = await options?.onPayload?.(payload, model);\n\t\t\tif (nextPayload !== undefined) {\n\t\t\t\tpayload = nextPayload as MistralChatPayload;\n\t\t\t}\n\t\t\tconst mistralStream = await requestMistralStream(model, payload, apiKey, options);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tawait consumeChatStream(model, output, stream, mistralStream);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Mistral stream ended without a finish reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\t// partialArgs is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatMistralError(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Maps provider-agnostic `SimpleStreamOptions` to Mistral options.\n */\nexport const streamSimple: StreamFunction<\"mistral-conversations\", SimpleStreamOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t} satisfies MistralOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoning = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst shouldUseReasoning = model.reasoning && reasoning !== undefined;\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tpromptMode: shouldUseReasoning && usesPromptModeReasoning(model) ? \"reasoning\" : undefined,\n\t\treasoningEffort:\n\t\t\tshouldUseReasoning && usesReasoningEffort(model) ? mapReasoningEffort(model, reasoning) : undefined,\n\t} satisfies MistralOptions);\n};\n\nfunction createOutput(model: Model<\"mistral-conversations\">): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"pending\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createMistralToolCallIdNormalizer(): (id: string) => string {\n\tconst idMap = new Map<string, string>();\n\tconst reverseMap = new Map<string, string>();\n\n\treturn (id: string): string => {\n\t\tconst existing = idMap.get(id);\n\t\tif (existing) return existing;\n\n\t\tlet attempt = 0;\n\t\twhile (true) {\n\t\t\tconst candidate = deriveMistralToolCallId(id, attempt);\n\t\t\tconst owner = reverseMap.get(candidate);\n\t\t\tif (!owner || owner === id) {\n\t\t\t\tidMap.set(id, candidate);\n\t\t\t\treverseMap.set(candidate, id);\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\tattempt++;\n\t\t}\n\t};\n}\n\nfunction deriveMistralToolCallId(id: string, attempt: number): string {\n\tconst normalized = id.replace(/[^a-zA-Z0-9]/g, \"\");\n\tif (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH) return normalized;\n\tconst seedBase = normalized || id;\n\tconst seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`;\n\treturn shortHash(seed)\n\t\t.replace(/[^a-zA-Z0-9]/g, \"\")\n\t\t.slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);\n}\n\nfunction formatMistralError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst httpError = error as Error & { statusCode?: unknown; body?: unknown };\n\t\tconst statusCode = typeof httpError.statusCode === \"number\" ? httpError.statusCode : undefined;\n\t\tconst bodyText = typeof httpError.body === \"string\" ? httpError.body.trim() : undefined;\n\t\tif (statusCode !== undefined && bodyText) {\n\t\t\treturn `Mistral API error (${statusCode}): ${truncateErrorText(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS)}`;\n\t\t}\n\t\tif (statusCode !== undefined) return `Mistral API error (${statusCode}): ${error.message}`;\n\t\treturn error.message;\n\t}\n\treturn safeJsonStringify(error);\n}\n\nfunction truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nasync function requestMistralStream(\n\tmodel: Model<\"mistral-conversations\">,\n\tpayload: MistralChatPayload,\n\tapiKey: string,\n\toptions?: MistralOptions,\n): Promise<AsyncIterable<MistralCompletionEvent>> {\n\tconst baseUrl = new URL(model.baseUrl);\n\tbaseUrl.pathname = `${baseUrl.pathname.replace(/\\/+$/u, \"\")}/`;\n\tconst url = new URL(\"v1/chat/completions\", baseUrl);\n\tconst headers = buildMistralHeaders(model, apiKey, options);\n\tconst timeoutSignal = AbortSignal.timeout(options?.timeoutMs ?? 60_000);\n\tconst signal = options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;\n\tconst response = await (options?.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(toMistralWirePayload(payload)),\n\t\tsignal,\n\t});\n\n\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\n\tif (!response.ok) {\n\t\tconst body = await response.text();\n\t\tthrow new MistralHttpError(response.status, body, response.statusText);\n\t}\n\tif (!response.body) {\n\t\tthrow new Error(\"Mistral response has no body\");\n\t}\n\n\treturn readMistralEvents(response.body, signal);\n}\n\nclass MistralHttpError extends Error {\n\tstatusCode: number;\n\tbody: string;\n\n\tconstructor(statusCode: number, body: string, statusText: string) {\n\t\tsuper(statusText || `Request failed with status ${statusCode}`);\n\t\tthis.name = \"MistralHttpError\";\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n}\n\nfunction buildMistralHeaders(model: Model<\"mistral-conversations\">, apiKey: string, options?: MistralOptions): Headers {\n\tconst headers = new Headers({\n\t\taccept: \"text/event-stream\",\n\t\tauthorization: `Bearer ${apiKey}`,\n\t\t\"content-type\": \"application/json\",\n\t});\n\tapplyMistralHeaderOverrides(headers, model.headers);\n\tapplyMistralHeaderOverrides(headers, options?.headers);\n\n\tconst hasExplicitAffinity =\n\t\thasMistralHeaderOverride(model.headers, \"x-affinity\") || hasMistralHeaderOverride(options?.headers, \"x-affinity\");\n\tif (shouldUsePromptCaching(options) && !hasExplicitAffinity) {\n\t\theaders.set(\"x-affinity\", options.sessionId);\n\t}\n\n\treturn headers;\n}\n\nfunction applyMistralHeaderOverrides(headers: Headers, overrides?: Record<string, string | null>): void {\n\tif (!overrides) return;\n\tfor (const [name, value] of Object.entries(overrides)) {\n\t\tif (value === null) headers.delete(name);\n\t\telse headers.set(name, value);\n\t}\n}\n\nfunction hasMistralHeaderOverride(overrides: Record<string, string | null> | undefined, target: string): boolean {\n\treturn !!overrides && Object.keys(overrides).some((name) => name.toLowerCase() === target);\n}\n\nfunction toMistralWirePayload(payload: MistralChatPayload): Record<string, unknown> {\n\tconst wirePayload: Record<string, unknown> = { ...payload };\n\tfor (const [source, target] of [\n\t\t[\"topP\", \"top_p\"],\n\t\t[\"maxTokens\", \"max_tokens\"],\n\t\t[\"randomSeed\", \"random_seed\"],\n\t\t[\"responseFormat\", \"response_format\"],\n\t\t[\"toolChoice\", \"tool_choice\"],\n\t\t[\"presencePenalty\", \"presence_penalty\"],\n\t\t[\"frequencyPenalty\", \"frequency_penalty\"],\n\t\t[\"parallelToolCalls\", \"parallel_tool_calls\"],\n\t\t[\"reasoningEffort\", \"reasoning_effort\"],\n\t\t[\"promptMode\", \"prompt_mode\"],\n\t\t[\"promptCacheKey\", \"prompt_cache_key\"],\n\t\t[\"safePrompt\", \"safe_prompt\"],\n\t] as const) {\n\t\tremapMistralProperty(wirePayload, source, target);\n\t}\n\twirePayload.messages = payload.messages.map((message) => toMistralWireMessage(message));\n\n\tconst responseFormat = wirePayload.response_format;\n\tif (isMistralRecord(responseFormat)) {\n\t\tconst wireResponseFormat = { ...responseFormat };\n\t\tremapMistralProperty(wireResponseFormat, \"jsonSchema\", \"json_schema\");\n\t\tconst jsonSchema = wireResponseFormat.json_schema;\n\t\tif (isMistralRecord(jsonSchema)) {\n\t\t\tconst wireJsonSchema = { ...jsonSchema };\n\t\t\tremapMistralProperty(wireJsonSchema, \"schemaDefinition\", \"schema\");\n\t\t\twireResponseFormat.json_schema = wireJsonSchema;\n\t\t}\n\t\twirePayload.response_format = wireResponseFormat;\n\t}\n\n\treturn wirePayload;\n}\n\nfunction toMistralWireMessage(message: MistralChatMessage): Record<string, unknown> {\n\tconst wireMessage: Record<string, unknown> = { ...message };\n\tremapMistralProperty(wireMessage, \"toolCalls\", \"tool_calls\");\n\tremapMistralProperty(wireMessage, \"toolCallId\", \"tool_call_id\");\n\tif (Array.isArray(message.content)) {\n\t\twireMessage.content = message.content.map((chunk) => toMistralWireContentChunk(chunk));\n\t}\n\treturn wireMessage;\n}\n\nfunction toMistralWireContentChunk(chunk: MistralContentChunk): Record<string, unknown> {\n\tconst wireChunk: Record<string, unknown> = { ...chunk };\n\tfor (const [source, target] of [\n\t\t[\"imageUrl\", \"image_url\"],\n\t\t[\"documentUrl\", \"document_url\"],\n\t\t[\"documentName\", \"document_name\"],\n\t\t[\"fileId\", \"file_id\"],\n\t\t[\"referenceIds\", \"reference_ids\"],\n\t\t[\"inputAudio\", \"input_audio\"],\n\t] as const) {\n\t\tremapMistralProperty(wireChunk, source, target);\n\t}\n\treturn wireChunk;\n}\n\nfunction remapMistralProperty(record: Record<string, unknown>, source: string, target: string): void {\n\tif (!(source in record)) return;\n\trecord[target] = record[source];\n\tdelete record[source];\n}\n\nfunction isMistralRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst MISTRAL_STREAM_DONE = Symbol(\"mistral-stream-done\");\n\nasync function* readMistralEvents(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal: AbortSignal,\n): AsyncGenerator<MistralCompletionEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tbuffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n\n\t\t\tlet boundary = findMistralEventBoundary(buffer);\n\t\t\twhile (boundary) {\n\t\t\t\tconst event = parseMistralEvent(buffer.slice(0, boundary.index));\n\t\t\t\tbuffer = buffer.slice(boundary.index + boundary.length);\n\t\t\t\tif (event === MISTRAL_STREAM_DONE) return;\n\t\t\t\tif (event) yield event;\n\t\t\t\tboundary = findMistralEventBoundary(buffer);\n\t\t\t}\n\n\t\t\tif (done) break;\n\t\t}\n\n\t\tif (buffer.trim()) {\n\t\t\tconst event = parseMistralEvent(buffer);\n\t\t\tif (event !== MISTRAL_STREAM_DONE && event) yield event;\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {}\n\t}\n}\n\nfunction findMistralEventBoundary(buffer: string): { index: number; length: number } | undefined {\n\tconst match = /\\r\\n\\r\\n|\\r\\n\\r|\\r\\n\\n|\\r\\r\\n|\\n\\r\\n|\\r\\r|\\n\\r|\\n\\n/u.exec(buffer);\n\treturn match?.index === undefined ? undefined : { index: match.index, length: match[0].length };\n}\n\nfunction parseMistralEvent(raw: string): MistralCompletionEvent | typeof MISTRAL_STREAM_DONE | undefined {\n\tconst data = raw\n\t\t.split(/\\r\\n|\\r|\\n/u)\n\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t.map((line) => line.slice(5).trimStart())\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tif (!data) return undefined;\n\tif (data === \"[DONE]\") return MISTRAL_STREAM_DONE;\n\n\tconst parsed: unknown = JSON.parse(data);\n\tif (!isMistralRecord(parsed) || !Array.isArray(parsed.choices)) {\n\t\tthrow new Error(\"Invalid Mistral streaming event\");\n\t}\n\treturn { data: parsed as MistralCompletionEvent[\"data\"] };\n}\n\nfunction buildChatPayload(\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\tmessages: Message[],\n\toptions?: MistralOptions,\n): MistralChatPayload {\n\tconst payload: MistralChatPayload = {\n\t\tmodel: model.id,\n\t\tstream: true,\n\t\tmessages: toChatMessages(messages, model.input.includes(\"image\")),\n\t};\n\n\tif (context.tools?.length) payload.tools = toFunctionTools(context.tools);\n\tif (options?.temperature !== undefined) payload.temperature = options.temperature;\n\tif (options?.maxTokens !== undefined) payload.maxTokens = options.maxTokens;\n\tif (options?.toolChoice) payload.toolChoice = mapToolChoice(options.toolChoice);\n\tif (options?.promptMode) payload.promptMode = options.promptMode;\n\tif (options?.reasoningEffort) payload.reasoningEffort = options.reasoningEffort;\n\tif (shouldUsePromptCaching(options)) payload.promptCacheKey = options.sessionId;\n\n\tif (context.systemPrompt) {\n\t\tpayload.messages.unshift({\n\t\t\trole: \"system\",\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tapplyExtraBody(payload, options?.extraBody, MISTRAL_RESERVED_BODY_KEYS);\n\n\treturn payload;\n}\n\nfunction shouldUsePromptCaching(options?: MistralOptions): options is MistralOptions & { sessionId: string } {\n\treturn options?.cacheRetention !== \"none\" && !!options?.sessionId;\n}\n\nfunction getMistralCachedPromptTokens(usage: unknown, promptTokens: number): number {\n\tconst rawUsage = usage as {\n\t\tpromptTokensDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_tokens_details?: { cached_tokens?: unknown } | null;\n\t\tpromptTokenDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_token_details?: { cached_tokens?: unknown } | null;\n\t\tnumCachedTokens?: unknown;\n\t\tnum_cached_tokens?: unknown;\n\t};\n\tconst rawCachedTokens =\n\t\trawUsage.promptTokensDetails?.cachedTokens ??\n\t\trawUsage.prompt_tokens_details?.cached_tokens ??\n\t\trawUsage.promptTokenDetails?.cachedTokens ??\n\t\trawUsage.prompt_token_details?.cached_tokens ??\n\t\trawUsage.numCachedTokens ??\n\t\trawUsage.num_cached_tokens ??\n\t\t0;\n\tconst cachedTokens = typeof rawCachedTokens === \"number\" && Number.isFinite(rawCachedTokens) ? rawCachedTokens : 0;\n\treturn Math.min(promptTokens, Math.max(0, cachedTokens));\n}\n\nasync function consumeChatStream(\n\tmodel: Model<\"mistral-conversations\">,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmistralStream: AsyncIterable<MistralCompletionEvent>,\n): Promise<void> {\n\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\tconst toolBlocksByKey = new Map<string, number>();\n\n\tconst finishCurrentBlock = (block?: typeof currentBlock) => {\n\t\tif (!block) return;\n\t\tif (block.type === \"text\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (block.type === \"thinking\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t};\n\n\tfor await (const event of mistralStream) {\n\t\tconst chunk = event.data;\n\t\t// Mistral's streamed CompletionChunk carries an id field. Keep the first non-empty one,\n\t\t// mirroring how OpenAI-style streaming exposes a stable response identifier per stream.\n\t\toutput.responseId ||= chunk.id;\n\n\t\tif (chunk.usage) {\n\t\t\tconst promptTokens = chunk.usage.prompt_tokens || 0;\n\t\t\tconst cachedPromptTokens = getMistralCachedPromptTokens(chunk.usage, promptTokens);\n\n\t\t\toutput.usage.input = Math.max(0, promptTokens - cachedPromptTokens);\n\t\t\toutput.usage.output = chunk.usage.completion_tokens || 0;\n\t\t\toutput.usage.cacheRead = cachedPromptTokens;\n\t\t\toutput.usage.cacheWrite = 0;\n\t\t\toutput.usage.totalTokens =\n\t\t\t\tchunk.usage.total_tokens ||\n\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\tcalculateCost(model, output.usage);\n\t\t}\n\n\t\tconst choice = chunk.choices[0];\n\t\tif (!choice) continue;\n\n\t\tif (choice.finish_reason) {\n\t\t\toutput.rawStopReason = choice.finish_reason;\n\t\t\tconst stopReasonResult = mapChatStopReason(choice.finish_reason);\n\t\t\toutput.stopReason = stopReasonResult.stopReason;\n\t\t\tif (stopReasonResult.errorMessage) {\n\t\t\t\toutput.errorMessage = stopReasonResult.errorMessage;\n\t\t\t}\n\t\t}\n\n\t\tconst delta = choice.delta;\n\t\tif (delta.content !== null && delta.content !== undefined) {\n\t\t\tconst contentItems = typeof delta.content === \"string\" ? [delta.content] : delta.content;\n\t\t\tfor (const item of contentItems) {\n\t\t\t\tif (typeof item === \"string\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item);\n\t\t\t\t\tif (currentBlock?.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"thinking\") {\n\t\t\t\t\tconst deltaText = (item.thinking ?? [])\n\t\t\t\t\t\t.map((part) => part.text ?? \"\")\n\t\t\t\t\t\t.filter((text) => text.length > 0)\n\t\t\t\t\t\t.join(\"\");\n\t\t\t\t\tconst thinkingDelta = sanitizeSurrogates(deltaText);\n\t\t\t\t\tif (!thinkingDelta) continue;\n\t\t\t\t\tif (currentBlock?.type !== \"thinking\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.thinking += thinkingDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: thinkingDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item.text ?? \"\");\n\t\t\t\t\tif (currentBlock?.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst toolCalls = delta.tool_calls || [];\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tif (currentBlock) {\n\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\tcurrentBlock = null;\n\t\t\t}\n\t\t\tconst callId =\n\t\t\t\ttoolCall.id && toolCall.id !== \"null\"\n\t\t\t\t\t? toolCall.id\n\t\t\t\t\t: deriveMistralToolCallId(`toolcall:${toolCall.index ?? 0}`, 0);\n\t\t\tconst key = `${callId}:${toolCall.index || 0}`;\n\t\t\tconst existingIndex = toolBlocksByKey.get(key);\n\t\t\tlet block: (ToolCall & { partialArgs?: string }) | undefined;\n\n\t\t\tif (existingIndex !== undefined) {\n\t\t\t\tconst existing = output.content[existingIndex];\n\t\t\t\tif (existing?.type === \"toolCall\") {\n\t\t\t\t\tblock = existing as ToolCall & { partialArgs?: string };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!block) {\n\t\t\t\tblock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: callId,\n\t\t\t\t\tname: toolCall.function.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(block);\n\t\t\t\ttoolBlocksByKey.set(key, output.content.length - 1);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t}\n\n\t\t\tconst argsDelta =\n\t\t\t\ttypeof toolCall.function.arguments === \"string\"\n\t\t\t\t\t? toolCall.function.arguments\n\t\t\t\t\t: JSON.stringify(toolCall.function.arguments || {});\n\t\t\tblock.partialArgs = (block.partialArgs || \"\") + argsDelta;\n\t\t\tblock.arguments = parseStreamingJson<Record<string, unknown>>(block.partialArgs);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\tcontentIndex: toolBlocksByKey.get(key)!,\n\t\t\t\tdelta: argsDelta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t}\n\n\tfinishCurrentBlock(currentBlock);\n\tfor (const index of toolBlocksByKey.values()) {\n\t\tconst block = output.content[index];\n\t\tif (block.type !== \"toolCall\") continue;\n\t\tconst toolBlock = block as ToolCall & { partialArgs?: string };\n\t\ttoolBlock.arguments = parseStreamingJson<Record<string, unknown>>(toolBlock.partialArgs);\n\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t// carries parsed arguments.\n\t\tdelete toolBlock.partialArgs;\n\t\tstream.push({\n\t\t\ttype: \"toolcall_end\",\n\t\t\tcontentIndex: index,\n\t\t\ttoolCall: toolBlock,\n\t\t\tpartial: output,\n\t\t});\n\t}\n}\n\nfunction toFunctionTools(tools: Tool[]): MistralFunctionTool[] {\n\treturn tools.map((tool) => {\n\t\tconst strict = resolveJsonSchemaStrictSampling(tool, true);\n\t\treturn {\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: stripSymbolKeys(getJsonSchemaToolParameters(tool, strict)) as Record<string, unknown>,\n\t\t\t\tstrict: strict ?? false,\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction stripSymbolKeys(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) => stripSymbolKeys(item));\n\t}\n\n\tif (value && typeof value === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\tresult[key] = stripSymbolKeys(entry);\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn value;\n}\n\nfunction toChatMessages(messages: Message[], supportsImages: boolean): MistralChatMessage[] {\n\tconst result: MistralChatMessage[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tresult.push({ role: \"user\", content: sanitizeSurrogates(msg.content) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst hadImages = msg.content.some((item) => item.type === \"image\");\n\t\t\tconst content: MistralContentChunk[] = msg.content\n\t\t\t\t.filter((item) => item.type === \"text\" || supportsImages)\n\t\t\t\t.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") return { type: \"text\", text: sanitizeSurrogates(item.text) };\n\t\t\t\t\treturn { type: \"image_url\", imageUrl: `data:${item.mimeType};base64,${item.data}` };\n\t\t\t\t});\n\t\t\tif (content.length > 0) {\n\t\t\t\tresult.push({ role: \"user\", content });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (hadImages && !supportsImages) {\n\t\t\t\tresult.push({ role: \"user\", content: \"(image omitted: model does not support images)\" });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst contentParts: MistralContentChunk[] = [];\n\t\t\tconst toolCalls: MistralRequestToolCall[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (block.text.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({ type: \"text\", text: sanitizeSurrogates(block.text) });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinking.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: [{ type: \"text\", text: sanitizeSurrogates(block.thinking) }],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type !== \"toolCall\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttoolCalls.push({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments || {}) },\n\t\t\t\t\tindex: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst assistantMessage: MistralChatMessage = { role: \"assistant\", prefix: false };\n\t\t\tif (contentParts.length > 0) assistantMessage.content = contentParts;\n\t\t\tif (toolCalls.length > 0) assistantMessage.toolCalls = toolCalls;\n\t\t\tif (contentParts.length > 0 || toolCalls.length > 0) result.push(assistantMessage);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst toolContent: MistralContentChunk[] = [];\n\t\tconst textResult = msg.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => (part.type === \"text\" ? sanitizeSurrogates(part.text) : \"\"))\n\t\t\t.join(\"\\n\");\n\t\tconst hasImages = msg.content.some((part) => part.type === \"image\");\n\t\tconst toolText = buildToolResultText(textResult, hasImages, supportsImages, msg.isError);\n\t\ttoolContent.push({ type: \"text\", text: toolText });\n\t\tfor (const part of msg.content) {\n\t\t\tif (!supportsImages) continue;\n\t\t\tif (part.type !== \"image\") continue;\n\t\t\ttoolContent.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timageUrl: `data:${part.mimeType};base64,${part.data}`,\n\t\t\t});\n\t\t}\n\t\tresult.push({\n\t\t\trole: \"tool\",\n\t\t\ttoolCallId: msg.toolCallId,\n\t\t\tname: msg.toolName,\n\t\t\tcontent: toolContent,\n\t\t});\n\t}\n\n\treturn result;\n}\n\nfunction buildToolResultText(text: string, hasImages: boolean, supportsImages: boolean, isError: boolean): string {\n\tconst trimmed = text.trim();\n\tconst errorPrefix = isError ? \"[tool error] \" : \"\";\n\n\tif (trimmed.length > 0) {\n\t\tconst imageSuffix = hasImages && !supportsImages ? \"\\n[tool image omitted: model does not support images]\" : \"\";\n\t\treturn `${errorPrefix}${trimmed}${imageSuffix}`;\n\t}\n\n\tif (hasImages) {\n\t\tif (supportsImages) {\n\t\t\treturn isError ? \"[tool error] (see attached image)\" : \"(see attached image)\";\n\t\t}\n\t\treturn isError\n\t\t\t? \"[tool error] (image omitted: model does not support images)\"\n\t\t\t: \"(image omitted: model does not support images)\";\n\t}\n\n\treturn isError ? \"[tool error] (no tool output)\" : \"(no tool output)\";\n}\n\nfunction usesReasoningEffort(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.id === \"mistral-small-2603\" || model.id === \"mistral-small-latest\" || model.id === \"mistral-medium-3.5\";\n}\n\nfunction usesPromptModeReasoning(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.reasoning && !usesReasoningEffort(model);\n}\n\nfunction mapReasoningEffort(\n\tmodel: Model<\"mistral-conversations\">,\n\tlevel: Exclude<SimpleStreamOptions[\"reasoning\"], undefined>,\n): MistralReasoningEffort {\n\treturn (model.thinkingLevelMap?.[level] ?? \"high\") as MistralReasoningEffort;\n}\n\nfunction mapToolChoice(\n\tchoice: MistralOptions[\"toolChoice\"],\n): \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } } | undefined {\n\tif (!choice) return undefined;\n\tif (choice === \"auto\" || choice === \"none\" || choice === \"any\" || choice === \"required\") {\n\t\treturn choice;\n\t}\n\treturn {\n\t\ttype: \"function\",\n\t\tfunction: { name: choice.function.name },\n\t};\n}\n\nfunction mapChatStopReason(reason: string | null): { stopReason: StopReason; errorMessage?: string } {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\tcase \"model_length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider stopped with: error\" };\n\t\tdefault:\n\t\t\treturn { stopReason: \"error\", errorMessage: `Provider stopped with: ${reason}` };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mistral-conversations.js","sourceRoot":"","sources":["../../src/api/mistral-conversations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAejE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AACzG,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACnG,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,MAAM,2BAA2B,GAAG,CAAC,CAAC;AACtC,MAAM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,EAAE,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE;KACxC,CAAC;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,MAAqB;IAC/C,IAAI,MAAM,KAAK,IAAI;QAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;IACnD,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,MAAM;YACV,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,KAAK,QAAQ,CAAC;QACd,KAAK,cAAc;YAClB,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;QACjC,KAAK,YAAY;YAChB,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;QAClC,KAAK,OAAO;YACX,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,CAAC;QAC9E;YACC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,EAAE,0BAA0B,MAAM,EAAE,EAAE,CAAC;IACnF,CAAC;AACF,CAAC","sourcesContent":["import { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tContext,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n} from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { getJsonSchemaToolParameters, resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { applyExtraBody, buildBaseOptions, MISTRAL_RESERVED_BODY_KEYS } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\nconst MISTRAL_TOOL_CALL_ID_LENGTH = 9;\nconst MAX_MISTRAL_ERROR_BODY_CHARS = 4000;\n\n/**\n * Provider-specific options for the Mistral API.\n */\ntype MistralReasoningEffort = \"none\" | \"high\";\n\nexport interface MistralOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } };\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n}\n\ntype MistralContentChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"image_url\"; imageUrl: string }\n\t| { type: \"thinking\"; thinking: Array<{ type: \"text\"; text: string }> };\n\ntype MistralRequestToolCall = {\n\tid: string;\n\ttype: \"function\";\n\tfunction: { name: string; arguments: string };\n\tindex: number;\n};\n\ntype MistralChatMessage = {\n\trole: \"system\" | \"user\" | \"assistant\" | \"tool\";\n\tcontent?: string | MistralContentChunk[];\n\ttoolCalls?: MistralRequestToolCall[];\n\ttoolCallId?: string;\n\tname?: string;\n\tprefix?: boolean;\n};\n\ntype MistralFunctionTool = {\n\ttype: \"function\";\n\tfunction: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: Record<string, unknown>;\n\t\tstrict: boolean;\n\t};\n};\n\ntype MistralChatPayload = {\n\t[key: string]: unknown;\n\tmodel: string;\n\tstream: boolean;\n\tmessages: MistralChatMessage[];\n\ttools?: MistralFunctionTool[];\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttoolChoice?: Exclude<MistralOptions[\"toolChoice\"], undefined>;\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n\tpromptCacheKey?: string;\n};\n\ntype MistralStreamContentChunk = {\n\ttype: string;\n\ttext?: string;\n\tthinking?: Array<{ text?: string }>;\n};\n\ntype MistralStreamToolCall = {\n\tid?: string;\n\tindex?: number;\n\tfunction: {\n\t\tname: string;\n\t\targuments: string | Record<string, unknown>;\n\t};\n};\n\ntype MistralCompletionEvent = {\n\tdata: {\n\t\tid?: string;\n\t\tusage?: {\n\t\t\t[key: string]: unknown;\n\t\t\tprompt_tokens?: number;\n\t\t\tcompletion_tokens?: number;\n\t\t\ttotal_tokens?: number;\n\t\t};\n\t\tchoices: Array<{\n\t\t\tfinish_reason?: string | null;\n\t\t\tdelta: {\n\t\t\t\tcontent?: string | MistralStreamContentChunk[] | null;\n\t\t\t\ttool_calls?: MistralStreamToolCall[] | null;\n\t\t\t};\n\t\t}>;\n\t};\n};\n\n/**\n * Stream responses from the native Mistral Chat Completions endpoint.\n */\nexport const stream: StreamFunction<\"mistral-conversations\", MistralOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: MistralOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output = createOutput(model);\n\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\n\t\t\tconst normalizeMistralToolCallId = createMistralToolCallIdNormalizer();\n\t\t\tconst preserveThinking = options?.promptMode === \"reasoning\" || options?.reasoningEffort !== undefined;\n\t\t\tconst transformedMessages = transformMessages(\n\t\t\t\tcontext.messages,\n\t\t\t\tmodel,\n\t\t\t\t(id) => normalizeMistralToolCallId(id),\n\t\t\t\t{\n\t\t\t\t\tpreserveThinking,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tlet payload = buildChatPayload(model, context, transformedMessages, options);\n\t\t\tconst nextPayload = await options?.onPayload?.(payload, model);\n\t\t\tif (nextPayload !== undefined) {\n\t\t\t\tpayload = nextPayload as MistralChatPayload;\n\t\t\t}\n\t\t\tconst mistralStream = await requestMistralStream(model, payload, apiKey, options);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tawait consumeChatStream(model, output, stream, mistralStream);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Mistral stream ended without a finish reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\t// partialArgs is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatMistralError(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Maps provider-agnostic `SimpleStreamOptions` to Mistral options.\n */\nexport const streamSimple: StreamFunction<\"mistral-conversations\", SimpleStreamOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t} satisfies MistralOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoning = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst shouldUseReasoning = model.reasoning && reasoning !== undefined;\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tpromptMode: shouldUseReasoning && usesPromptModeReasoning(model) ? \"reasoning\" : undefined,\n\t\treasoningEffort:\n\t\t\tshouldUseReasoning && usesReasoningEffort(model) ? mapReasoningEffort(model, reasoning) : undefined,\n\t} satisfies MistralOptions);\n};\n\nfunction createOutput(model: Model<\"mistral-conversations\">): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"pending\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createMistralToolCallIdNormalizer(): (id: string) => string {\n\tconst idMap = new Map<string, string>();\n\tconst reverseMap = new Map<string, string>();\n\n\treturn (id: string): string => {\n\t\tconst existing = idMap.get(id);\n\t\tif (existing) return existing;\n\n\t\tlet attempt = 0;\n\t\twhile (true) {\n\t\t\tconst candidate = deriveMistralToolCallId(id, attempt);\n\t\t\tconst owner = reverseMap.get(candidate);\n\t\t\tif (!owner || owner === id) {\n\t\t\t\tidMap.set(id, candidate);\n\t\t\t\treverseMap.set(candidate, id);\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\tattempt++;\n\t\t}\n\t};\n}\n\nfunction deriveMistralToolCallId(id: string, attempt: number): string {\n\tconst normalized = id.replace(/[^a-zA-Z0-9]/g, \"\");\n\tif (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH) return normalized;\n\tconst seedBase = normalized || id;\n\tconst seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`;\n\treturn shortHash(seed)\n\t\t.replace(/[^a-zA-Z0-9]/g, \"\")\n\t\t.slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);\n}\n\nfunction formatMistralError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst httpError = error as Error & { statusCode?: unknown; body?: unknown };\n\t\tconst statusCode = typeof httpError.statusCode === \"number\" ? httpError.statusCode : undefined;\n\t\tconst bodyText = typeof httpError.body === \"string\" ? httpError.body.trim() : undefined;\n\t\tif (statusCode !== undefined && bodyText) {\n\t\t\treturn `Mistral API error (${statusCode}): ${truncateErrorText(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS)}`;\n\t\t}\n\t\tif (statusCode !== undefined) return `Mistral API error (${statusCode}): ${error.message}`;\n\t\treturn error.message;\n\t}\n\treturn safeJsonStringify(error);\n}\n\nfunction truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nasync function requestMistralStream(\n\tmodel: Model<\"mistral-conversations\">,\n\tpayload: MistralChatPayload,\n\tapiKey: string,\n\toptions?: MistralOptions,\n): Promise<AsyncIterable<MistralCompletionEvent>> {\n\tconst baseUrl = new URL(model.baseUrl);\n\tbaseUrl.pathname = `${baseUrl.pathname.replace(/\\/+$/u, \"\")}/`;\n\tconst url = new URL(\"v1/chat/completions\", baseUrl);\n\tconst headers = buildMistralHeaders(model, apiKey, options);\n\tconst timeoutSignal = AbortSignal.timeout(options?.timeoutMs ?? 60_000);\n\tconst signal = options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;\n\tconst response = await (options?.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(toMistralWirePayload(payload)),\n\t\tsignal,\n\t});\n\n\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\n\tif (!response.ok) {\n\t\tconst body = await response.text();\n\t\tthrow new MistralHttpError(response.status, body, response.statusText);\n\t}\n\tif (!response.body) {\n\t\tthrow new Error(\"Mistral response has no body\");\n\t}\n\n\treturn readMistralEvents(response.body, signal);\n}\n\nclass MistralHttpError extends Error {\n\tstatusCode: number;\n\tbody: string;\n\n\tconstructor(statusCode: number, body: string, statusText: string) {\n\t\tsuper(statusText || `Request failed with status ${statusCode}`);\n\t\tthis.name = \"MistralHttpError\";\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n}\n\nfunction buildMistralHeaders(model: Model<\"mistral-conversations\">, apiKey: string, options?: MistralOptions): Headers {\n\tconst headers = new Headers({\n\t\t\"User-Agent\": getPiUserAgent(),\n\t\taccept: \"text/event-stream\",\n\t\tauthorization: `Bearer ${apiKey}`,\n\t\t\"content-type\": \"application/json\",\n\t});\n\tapplyMistralHeaderOverrides(headers, model.headers);\n\tapplyMistralHeaderOverrides(headers, options?.headers);\n\n\tconst hasExplicitAffinity =\n\t\thasMistralHeaderOverride(model.headers, \"x-affinity\") || hasMistralHeaderOverride(options?.headers, \"x-affinity\");\n\tif (shouldUsePromptCaching(options) && !hasExplicitAffinity) {\n\t\theaders.set(\"x-affinity\", options.sessionId);\n\t}\n\n\treturn headers;\n}\n\nfunction applyMistralHeaderOverrides(headers: Headers, overrides?: Record<string, string | null>): void {\n\tif (!overrides) return;\n\tfor (const [name, value] of Object.entries(overrides)) {\n\t\tif (value === null) headers.delete(name);\n\t\telse headers.set(name, value);\n\t}\n}\n\nfunction hasMistralHeaderOverride(overrides: Record<string, string | null> | undefined, target: string): boolean {\n\treturn !!overrides && Object.keys(overrides).some((name) => name.toLowerCase() === target);\n}\n\nfunction toMistralWirePayload(payload: MistralChatPayload): Record<string, unknown> {\n\tconst wirePayload: Record<string, unknown> = { ...payload };\n\tfor (const [source, target] of [\n\t\t[\"topP\", \"top_p\"],\n\t\t[\"maxTokens\", \"max_tokens\"],\n\t\t[\"randomSeed\", \"random_seed\"],\n\t\t[\"responseFormat\", \"response_format\"],\n\t\t[\"toolChoice\", \"tool_choice\"],\n\t\t[\"presencePenalty\", \"presence_penalty\"],\n\t\t[\"frequencyPenalty\", \"frequency_penalty\"],\n\t\t[\"parallelToolCalls\", \"parallel_tool_calls\"],\n\t\t[\"reasoningEffort\", \"reasoning_effort\"],\n\t\t[\"promptMode\", \"prompt_mode\"],\n\t\t[\"promptCacheKey\", \"prompt_cache_key\"],\n\t\t[\"safePrompt\", \"safe_prompt\"],\n\t] as const) {\n\t\tremapMistralProperty(wirePayload, source, target);\n\t}\n\twirePayload.messages = payload.messages.map((message) => toMistralWireMessage(message));\n\n\tconst responseFormat = wirePayload.response_format;\n\tif (isMistralRecord(responseFormat)) {\n\t\tconst wireResponseFormat = { ...responseFormat };\n\t\tremapMistralProperty(wireResponseFormat, \"jsonSchema\", \"json_schema\");\n\t\tconst jsonSchema = wireResponseFormat.json_schema;\n\t\tif (isMistralRecord(jsonSchema)) {\n\t\t\tconst wireJsonSchema = { ...jsonSchema };\n\t\t\tremapMistralProperty(wireJsonSchema, \"schemaDefinition\", \"schema\");\n\t\t\twireResponseFormat.json_schema = wireJsonSchema;\n\t\t}\n\t\twirePayload.response_format = wireResponseFormat;\n\t}\n\n\treturn wirePayload;\n}\n\nfunction toMistralWireMessage(message: MistralChatMessage): Record<string, unknown> {\n\tconst wireMessage: Record<string, unknown> = { ...message };\n\tremapMistralProperty(wireMessage, \"toolCalls\", \"tool_calls\");\n\tremapMistralProperty(wireMessage, \"toolCallId\", \"tool_call_id\");\n\tif (Array.isArray(message.content)) {\n\t\twireMessage.content = message.content.map((chunk) => toMistralWireContentChunk(chunk));\n\t}\n\treturn wireMessage;\n}\n\nfunction toMistralWireContentChunk(chunk: MistralContentChunk): Record<string, unknown> {\n\tconst wireChunk: Record<string, unknown> = { ...chunk };\n\tfor (const [source, target] of [\n\t\t[\"imageUrl\", \"image_url\"],\n\t\t[\"documentUrl\", \"document_url\"],\n\t\t[\"documentName\", \"document_name\"],\n\t\t[\"fileId\", \"file_id\"],\n\t\t[\"referenceIds\", \"reference_ids\"],\n\t\t[\"inputAudio\", \"input_audio\"],\n\t] as const) {\n\t\tremapMistralProperty(wireChunk, source, target);\n\t}\n\treturn wireChunk;\n}\n\nfunction remapMistralProperty(record: Record<string, unknown>, source: string, target: string): void {\n\tif (!(source in record)) return;\n\trecord[target] = record[source];\n\tdelete record[source];\n}\n\nfunction isMistralRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst MISTRAL_STREAM_DONE = Symbol(\"mistral-stream-done\");\n\nasync function* readMistralEvents(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal: AbortSignal,\n): AsyncGenerator<MistralCompletionEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tbuffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n\n\t\t\tlet boundary = findMistralEventBoundary(buffer);\n\t\t\twhile (boundary) {\n\t\t\t\tconst event = parseMistralEvent(buffer.slice(0, boundary.index));\n\t\t\t\tbuffer = buffer.slice(boundary.index + boundary.length);\n\t\t\t\tif (event === MISTRAL_STREAM_DONE) return;\n\t\t\t\tif (event) yield event;\n\t\t\t\tboundary = findMistralEventBoundary(buffer);\n\t\t\t}\n\n\t\t\tif (done) break;\n\t\t}\n\n\t\tif (buffer.trim()) {\n\t\t\tconst event = parseMistralEvent(buffer);\n\t\t\tif (event !== MISTRAL_STREAM_DONE && event) yield event;\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {}\n\t}\n}\n\nfunction findMistralEventBoundary(buffer: string): { index: number; length: number } | undefined {\n\tconst match = /\\r\\n\\r\\n|\\r\\n\\r|\\r\\n\\n|\\r\\r\\n|\\n\\r\\n|\\r\\r|\\n\\r|\\n\\n/u.exec(buffer);\n\treturn match?.index === undefined ? undefined : { index: match.index, length: match[0].length };\n}\n\nfunction parseMistralEvent(raw: string): MistralCompletionEvent | typeof MISTRAL_STREAM_DONE | undefined {\n\tconst data = raw\n\t\t.split(/\\r\\n|\\r|\\n/u)\n\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t.map((line) => line.slice(5).trimStart())\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tif (!data) return undefined;\n\tif (data === \"[DONE]\") return MISTRAL_STREAM_DONE;\n\n\tconst parsed: unknown = JSON.parse(data);\n\tif (!isMistralRecord(parsed) || !Array.isArray(parsed.choices)) {\n\t\tthrow new Error(\"Invalid Mistral streaming event\");\n\t}\n\treturn { data: parsed as MistralCompletionEvent[\"data\"] };\n}\n\nfunction buildChatPayload(\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\tmessages: Message[],\n\toptions?: MistralOptions,\n): MistralChatPayload {\n\tconst payload: MistralChatPayload = {\n\t\tmodel: model.id,\n\t\tstream: true,\n\t\tmessages: toChatMessages(messages, model.input.includes(\"image\")),\n\t};\n\n\tif (context.tools?.length) payload.tools = toFunctionTools(context.tools);\n\tif (options?.temperature !== undefined) payload.temperature = options.temperature;\n\tif (options?.maxTokens !== undefined) payload.maxTokens = options.maxTokens;\n\tif (options?.toolChoice) payload.toolChoice = mapToolChoice(options.toolChoice);\n\tif (options?.promptMode) payload.promptMode = options.promptMode;\n\tif (options?.reasoningEffort) payload.reasoningEffort = options.reasoningEffort;\n\tif (shouldUsePromptCaching(options)) payload.promptCacheKey = options.sessionId;\n\n\tif (context.systemPrompt) {\n\t\tpayload.messages.unshift({\n\t\t\trole: \"system\",\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tapplyExtraBody(payload, options?.extraBody, MISTRAL_RESERVED_BODY_KEYS);\n\n\treturn payload;\n}\n\nfunction shouldUsePromptCaching(options?: MistralOptions): options is MistralOptions & { sessionId: string } {\n\treturn options?.cacheRetention !== \"none\" && !!options?.sessionId;\n}\n\nfunction getMistralCachedPromptTokens(usage: unknown, promptTokens: number): number {\n\tconst rawUsage = usage as {\n\t\tpromptTokensDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_tokens_details?: { cached_tokens?: unknown } | null;\n\t\tpromptTokenDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_token_details?: { cached_tokens?: unknown } | null;\n\t\tnumCachedTokens?: unknown;\n\t\tnum_cached_tokens?: unknown;\n\t};\n\tconst rawCachedTokens =\n\t\trawUsage.promptTokensDetails?.cachedTokens ??\n\t\trawUsage.prompt_tokens_details?.cached_tokens ??\n\t\trawUsage.promptTokenDetails?.cachedTokens ??\n\t\trawUsage.prompt_token_details?.cached_tokens ??\n\t\trawUsage.numCachedTokens ??\n\t\trawUsage.num_cached_tokens ??\n\t\t0;\n\tconst cachedTokens = typeof rawCachedTokens === \"number\" && Number.isFinite(rawCachedTokens) ? rawCachedTokens : 0;\n\treturn Math.min(promptTokens, Math.max(0, cachedTokens));\n}\n\nasync function consumeChatStream(\n\tmodel: Model<\"mistral-conversations\">,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmistralStream: AsyncIterable<MistralCompletionEvent>,\n): Promise<void> {\n\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\tconst toolBlocksByKey = new Map<string, number>();\n\n\tconst finishCurrentBlock = (block?: typeof currentBlock) => {\n\t\tif (!block) return;\n\t\tif (block.type === \"text\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (block.type === \"thinking\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t};\n\n\tfor await (const event of mistralStream) {\n\t\tconst chunk = event.data;\n\t\t// Mistral's streamed CompletionChunk carries an id field. Keep the first non-empty one,\n\t\t// mirroring how OpenAI-style streaming exposes a stable response identifier per stream.\n\t\toutput.responseId ||= chunk.id;\n\n\t\tif (chunk.usage) {\n\t\t\tconst promptTokens = chunk.usage.prompt_tokens || 0;\n\t\t\tconst cachedPromptTokens = getMistralCachedPromptTokens(chunk.usage, promptTokens);\n\n\t\t\toutput.usage.input = Math.max(0, promptTokens - cachedPromptTokens);\n\t\t\toutput.usage.output = chunk.usage.completion_tokens || 0;\n\t\t\toutput.usage.cacheRead = cachedPromptTokens;\n\t\t\toutput.usage.cacheWrite = 0;\n\t\t\toutput.usage.totalTokens =\n\t\t\t\tchunk.usage.total_tokens ||\n\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\tcalculateCost(model, output.usage);\n\t\t}\n\n\t\tconst choice = chunk.choices[0];\n\t\tif (!choice) continue;\n\n\t\tif (choice.finish_reason) {\n\t\t\toutput.rawStopReason = choice.finish_reason;\n\t\t\tconst stopReasonResult = mapChatStopReason(choice.finish_reason);\n\t\t\toutput.stopReason = stopReasonResult.stopReason;\n\t\t\tif (stopReasonResult.errorMessage) {\n\t\t\t\toutput.errorMessage = stopReasonResult.errorMessage;\n\t\t\t}\n\t\t}\n\n\t\tconst delta = choice.delta;\n\t\tif (delta.content !== null && delta.content !== undefined) {\n\t\t\tconst contentItems = typeof delta.content === \"string\" ? [delta.content] : delta.content;\n\t\t\tfor (const item of contentItems) {\n\t\t\t\tif (typeof item === \"string\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item);\n\t\t\t\t\tif (currentBlock?.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"thinking\") {\n\t\t\t\t\tconst deltaText = (item.thinking ?? [])\n\t\t\t\t\t\t.map((part) => part.text ?? \"\")\n\t\t\t\t\t\t.filter((text) => text.length > 0)\n\t\t\t\t\t\t.join(\"\");\n\t\t\t\t\tconst thinkingDelta = sanitizeSurrogates(deltaText);\n\t\t\t\t\tif (!thinkingDelta) continue;\n\t\t\t\t\tif (currentBlock?.type !== \"thinking\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.thinking += thinkingDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: thinkingDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item.text ?? \"\");\n\t\t\t\t\tif (currentBlock?.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst toolCalls = delta.tool_calls || [];\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tif (currentBlock) {\n\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\tcurrentBlock = null;\n\t\t\t}\n\t\t\tconst callId =\n\t\t\t\ttoolCall.id && toolCall.id !== \"null\"\n\t\t\t\t\t? toolCall.id\n\t\t\t\t\t: deriveMistralToolCallId(`toolcall:${toolCall.index ?? 0}`, 0);\n\t\t\tconst key = `${callId}:${toolCall.index || 0}`;\n\t\t\tconst existingIndex = toolBlocksByKey.get(key);\n\t\t\tlet block: (ToolCall & { partialArgs?: string }) | undefined;\n\n\t\t\tif (existingIndex !== undefined) {\n\t\t\t\tconst existing = output.content[existingIndex];\n\t\t\t\tif (existing?.type === \"toolCall\") {\n\t\t\t\t\tblock = existing as ToolCall & { partialArgs?: string };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!block) {\n\t\t\t\tblock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: callId,\n\t\t\t\t\tname: toolCall.function.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(block);\n\t\t\t\ttoolBlocksByKey.set(key, output.content.length - 1);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t}\n\n\t\t\tconst argsDelta =\n\t\t\t\ttypeof toolCall.function.arguments === \"string\"\n\t\t\t\t\t? toolCall.function.arguments\n\t\t\t\t\t: JSON.stringify(toolCall.function.arguments || {});\n\t\t\tblock.partialArgs = (block.partialArgs || \"\") + argsDelta;\n\t\t\tblock.arguments = parseStreamingJson<Record<string, unknown>>(block.partialArgs);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\tcontentIndex: toolBlocksByKey.get(key)!,\n\t\t\t\tdelta: argsDelta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t}\n\n\tfinishCurrentBlock(currentBlock);\n\tfor (const index of toolBlocksByKey.values()) {\n\t\tconst block = output.content[index];\n\t\tif (block.type !== \"toolCall\") continue;\n\t\tconst toolBlock = block as ToolCall & { partialArgs?: string };\n\t\ttoolBlock.arguments = parseStreamingJson<Record<string, unknown>>(toolBlock.partialArgs);\n\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t// carries parsed arguments.\n\t\tdelete toolBlock.partialArgs;\n\t\tstream.push({\n\t\t\ttype: \"toolcall_end\",\n\t\t\tcontentIndex: index,\n\t\t\ttoolCall: toolBlock,\n\t\t\tpartial: output,\n\t\t});\n\t}\n}\n\nfunction toFunctionTools(tools: Tool[]): MistralFunctionTool[] {\n\treturn tools.map((tool) => {\n\t\tconst strict = resolveJsonSchemaStrictSampling(tool, true);\n\t\treturn {\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: stripSymbolKeys(getJsonSchemaToolParameters(tool, strict)) as Record<string, unknown>,\n\t\t\t\tstrict: strict ?? false,\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction stripSymbolKeys(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) => stripSymbolKeys(item));\n\t}\n\n\tif (value && typeof value === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\tresult[key] = stripSymbolKeys(entry);\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn value;\n}\n\nfunction toChatMessages(messages: Message[], supportsImages: boolean): MistralChatMessage[] {\n\tconst result: MistralChatMessage[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tresult.push({ role: \"user\", content: sanitizeSurrogates(msg.content) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst hadImages = msg.content.some((item) => item.type === \"image\");\n\t\t\tconst content: MistralContentChunk[] = msg.content\n\t\t\t\t.filter((item) => item.type === \"text\" || supportsImages)\n\t\t\t\t.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") return { type: \"text\", text: sanitizeSurrogates(item.text) };\n\t\t\t\t\treturn { type: \"image_url\", imageUrl: `data:${item.mimeType};base64,${item.data}` };\n\t\t\t\t});\n\t\t\tif (content.length > 0) {\n\t\t\t\tresult.push({ role: \"user\", content });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (hadImages && !supportsImages) {\n\t\t\t\tresult.push({ role: \"user\", content: \"(image omitted: model does not support images)\" });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst contentParts: MistralContentChunk[] = [];\n\t\t\tconst toolCalls: MistralRequestToolCall[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (block.text.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({ type: \"text\", text: sanitizeSurrogates(block.text) });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinking.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: [{ type: \"text\", text: sanitizeSurrogates(block.thinking) }],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type !== \"toolCall\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttoolCalls.push({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments || {}) },\n\t\t\t\t\tindex: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst assistantMessage: MistralChatMessage = { role: \"assistant\", prefix: false };\n\t\t\tif (contentParts.length > 0) assistantMessage.content = contentParts;\n\t\t\tif (toolCalls.length > 0) assistantMessage.toolCalls = toolCalls;\n\t\t\tif (contentParts.length > 0 || toolCalls.length > 0) result.push(assistantMessage);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst toolContent: MistralContentChunk[] = [];\n\t\tconst textResult = msg.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => (part.type === \"text\" ? sanitizeSurrogates(part.text) : \"\"))\n\t\t\t.join(\"\\n\");\n\t\tconst hasImages = msg.content.some((part) => part.type === \"image\");\n\t\tconst toolText = buildToolResultText(textResult, hasImages, supportsImages, msg.isError);\n\t\ttoolContent.push({ type: \"text\", text: toolText });\n\t\tfor (const part of msg.content) {\n\t\t\tif (!supportsImages) continue;\n\t\t\tif (part.type !== \"image\") continue;\n\t\t\ttoolContent.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timageUrl: `data:${part.mimeType};base64,${part.data}`,\n\t\t\t});\n\t\t}\n\t\tresult.push({\n\t\t\trole: \"tool\",\n\t\t\ttoolCallId: msg.toolCallId,\n\t\t\tname: msg.toolName,\n\t\t\tcontent: toolContent,\n\t\t});\n\t}\n\n\treturn result;\n}\n\nfunction buildToolResultText(text: string, hasImages: boolean, supportsImages: boolean, isError: boolean): string {\n\tconst trimmed = text.trim();\n\tconst errorPrefix = isError ? \"[tool error] \" : \"\";\n\n\tif (trimmed.length > 0) {\n\t\tconst imageSuffix = hasImages && !supportsImages ? \"\\n[tool image omitted: model does not support images]\" : \"\";\n\t\treturn `${errorPrefix}${trimmed}${imageSuffix}`;\n\t}\n\n\tif (hasImages) {\n\t\tif (supportsImages) {\n\t\t\treturn isError ? \"[tool error] (see attached image)\" : \"(see attached image)\";\n\t\t}\n\t\treturn isError\n\t\t\t? \"[tool error] (image omitted: model does not support images)\"\n\t\t\t: \"(image omitted: model does not support images)\";\n\t}\n\n\treturn isError ? \"[tool error] (no tool output)\" : \"(no tool output)\";\n}\n\nfunction usesReasoningEffort(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.id === \"mistral-small-2603\" || model.id === \"mistral-small-latest\" || model.id === \"mistral-medium-3.5\";\n}\n\nfunction usesPromptModeReasoning(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.reasoning && !usesReasoningEffort(model);\n}\n\nfunction mapReasoningEffort(\n\tmodel: Model<\"mistral-conversations\">,\n\tlevel: Exclude<SimpleStreamOptions[\"reasoning\"], undefined>,\n): MistralReasoningEffort {\n\treturn (model.thinkingLevelMap?.[level] ?? \"high\") as MistralReasoningEffort;\n}\n\nfunction mapToolChoice(\n\tchoice: MistralOptions[\"toolChoice\"],\n): \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } } | undefined {\n\tif (!choice) return undefined;\n\tif (choice === \"auto\" || choice === \"none\" || choice === \"any\" || choice === \"required\") {\n\t\treturn choice;\n\t}\n\treturn {\n\t\ttype: \"function\",\n\t\tfunction: { name: choice.function.name },\n\t};\n}\n\nfunction mapChatStopReason(reason: string | null): { stopReason: StopReason; errorMessage?: string } {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\tcase \"model_length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider stopped with: error\" };\n\t\tdefault:\n\t\t\treturn { stopReason: \"error\", errorMessage: `Provider stopped with: ${reason}` };\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-completions.d.ts","sourceRoot":"","sources":["../../src/api/openai-completions.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,KAAK,EAOX,0BAA0B,EAI1B,MAAM,sCAAsC,CAAC;AAG9C,OAAO,KAAK,EAIX,OAAO,
|
|
1
|
+
{"version":3,"file":"openai-completions.d.ts","sourceRoot":"","sources":["../../src/api/openai-completions.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,KAAK,EAOX,0BAA0B,EAI1B,MAAM,sCAAsC,CAAC;AAG9C,OAAO,KAAK,EAIX,OAAO,EAIP,KAAK,EAIL,mBAAmB,EAEnB,cAAc,EACd,aAAa,EAEb,eAAe,EAMf,MAAM,aAAa,CAAC;AAOrB,OAAO,EAEN,KAAK,+BAA+B,EACpC,MAAM,8BAA8B,CAAC;AA+BtC,OAAO,EACN,0BAA0B,IAAI,SAAS,EACvC,KAAK,+BAA+B,GACpC,MAAM,8BAA8B,CAAC;AA8NtC,MAAM,WAAW,wBAAyB,SAAQ,aAAa;IAC9D,UAAU,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,8BAA8B,CAAC;IACpE,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;IAC1E,2KAA2K;IAC3K,eAAe,CAAC,EAAE,eAAe,CAAC;CAClC;AAED,MAAM,WAAW,iCAAiC;IACjD,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,0BAA0B,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACzD;AAsHD,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,oBAAoB,EAAE,wBAAwB,CAufjF,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,oBAAoB,EAAE,mBAAmB,CA6BlF,CAAC;AAsdF,wBAAgB,eAAe,CAC9B,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,EAClC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,+BAA+B,EACvC,OAAO,GAAE,iCAAsC,GAC7C,0BAA0B,EAAE,CAmS9B"}
|
|
@@ -5,7 +5,7 @@ import { AssistantMessageEventStream } from "../utils/event-stream.js";
|
|
|
5
5
|
import { shortHash } from "../utils/hash.js";
|
|
6
6
|
import { headersToRecord } from "../utils/headers.js";
|
|
7
7
|
import { parseStreamingJson } from "../utils/json-parse.js";
|
|
8
|
-
import {
|
|
8
|
+
import { getPiUserAgent } from "../utils/pi-user-agent.js";
|
|
9
9
|
import { getOpenAICompletionsCompat as getCompat, } from "../utils/prompt-cache-ttl.js";
|
|
10
10
|
import { getProviderEnvValue } from "../utils/provider-env.js";
|
|
11
11
|
import { retryProviderStreamRequest } from "../utils/provider-retry.js";
|
|
@@ -161,16 +161,77 @@ function getOpenRouterRawMetadata(error) {
|
|
|
161
161
|
function isForcedOpenAICompletionsToolChoice(toolChoice) {
|
|
162
162
|
return toolChoice !== undefined && toolChoice !== "auto" && toolChoice !== "none";
|
|
163
163
|
}
|
|
164
|
-
function
|
|
165
|
-
|
|
164
|
+
function isReasoningDetailObject(detail) {
|
|
165
|
+
return typeof detail === "object" && detail !== null && !Array.isArray(detail);
|
|
166
|
+
}
|
|
167
|
+
function hasValidCommonReasoningDetailFields(candidate) {
|
|
168
|
+
return ((candidate.id === undefined || candidate.id === null || typeof candidate.id === "string") &&
|
|
169
|
+
(candidate.format === undefined || typeof candidate.format === "string") &&
|
|
170
|
+
(candidate.index === undefined || typeof candidate.index === "number"));
|
|
171
|
+
}
|
|
172
|
+
function isOpenAIReasoningDetail(detail) {
|
|
173
|
+
if (!isReasoningDetailObject(detail) || !hasValidCommonReasoningDetailFields(detail)) {
|
|
166
174
|
return false;
|
|
167
175
|
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
176
|
+
switch (detail.type) {
|
|
177
|
+
case "reasoning.summary":
|
|
178
|
+
return typeof detail.summary === "string";
|
|
179
|
+
case "reasoning.encrypted":
|
|
180
|
+
return typeof detail.data === "string";
|
|
181
|
+
case "reasoning.text":
|
|
182
|
+
return (typeof detail.text === "string" &&
|
|
183
|
+
(detail.signature === undefined || detail.signature === null || typeof detail.signature === "string"));
|
|
184
|
+
default:
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function parseOpenAIReasoningDetails(signature) {
|
|
189
|
+
if (!signature)
|
|
190
|
+
return undefined;
|
|
191
|
+
try {
|
|
192
|
+
const parsed = JSON.parse(signature);
|
|
193
|
+
return Array.isArray(parsed) && parsed.length > 0 && parsed.every(isOpenAIReasoningDetail) ? parsed : undefined;
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function parseLegacyEncryptedReasoningDetail(signature) {
|
|
200
|
+
if (!signature)
|
|
201
|
+
return undefined;
|
|
202
|
+
try {
|
|
203
|
+
const parsed = JSON.parse(signature);
|
|
204
|
+
return isOpenAIReasoningDetail(parsed) &&
|
|
205
|
+
parsed.type === "reasoning.encrypted" &&
|
|
206
|
+
typeof parsed.id === "string" &&
|
|
207
|
+
parsed.id.length > 0 &&
|
|
208
|
+
parsed.data.length > 0
|
|
209
|
+
? parsed
|
|
210
|
+
: undefined;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function fillMissingCommonReasoningDetailFields(target, source) {
|
|
217
|
+
target.id ??= source.id;
|
|
218
|
+
target.format ||= source.format;
|
|
219
|
+
target.index ??= source.index;
|
|
220
|
+
}
|
|
221
|
+
function appendOpenAIReasoningDetail(details, detail) {
|
|
222
|
+
const lastDetail = details[details.length - 1];
|
|
223
|
+
if (detail.type === "reasoning.text" && lastDetail?.type === "reasoning.text") {
|
|
224
|
+
lastDetail.text += detail.text;
|
|
225
|
+
lastDetail.signature ||= detail.signature;
|
|
226
|
+
fillMissingCommonReasoningDetailFields(lastDetail, detail);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (detail.type === "reasoning.summary" && lastDetail?.type === "reasoning.summary") {
|
|
230
|
+
lastDetail.summary += detail.summary;
|
|
231
|
+
fillMissingCommonReasoningDetailFields(lastDetail, detail);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
details.push({ ...detail });
|
|
174
235
|
}
|
|
175
236
|
function resolveCacheRetention(cacheRetention, env) {
|
|
176
237
|
if (cacheRetention) {
|
|
@@ -249,7 +310,6 @@ export const stream = (model, context, options) => {
|
|
|
249
310
|
const deferredToolCallDeltas = new Map();
|
|
250
311
|
const toolCallBlocksByIndex = new Map();
|
|
251
312
|
const toolCallBlocksById = new Map();
|
|
252
|
-
const pendingReasoningDetailsByToolCallId = new Map();
|
|
253
313
|
const blocks = output.content;
|
|
254
314
|
const getContentIndex = (block) => blocks.indexOf(block);
|
|
255
315
|
const getCustomToolCallInput = (block) => {
|
|
@@ -360,16 +420,6 @@ export const stream = (model, context, options) => {
|
|
|
360
420
|
}
|
|
361
421
|
return thinkingBlock;
|
|
362
422
|
};
|
|
363
|
-
const applyPendingReasoningDetail = (block) => {
|
|
364
|
-
if (!block.id) {
|
|
365
|
-
return;
|
|
366
|
-
}
|
|
367
|
-
const pendingReasoningDetail = pendingReasoningDetailsByToolCallId.get(block.id);
|
|
368
|
-
if (pendingReasoningDetail) {
|
|
369
|
-
block.thoughtSignature = pendingReasoningDetail;
|
|
370
|
-
pendingReasoningDetailsByToolCallId.delete(block.id);
|
|
371
|
-
}
|
|
372
|
-
};
|
|
373
423
|
const ensureToolCallBlock = (toolCall) => {
|
|
374
424
|
const streamIndex = typeof toolCall.index === "number" ? toolCall.index : undefined;
|
|
375
425
|
const name = toolCall.function?.name ?? toolCall.custom?.name ?? "";
|
|
@@ -433,7 +483,6 @@ export const stream = (model, context, options) => {
|
|
|
433
483
|
};
|
|
434
484
|
delete block.partialArgs;
|
|
435
485
|
}
|
|
436
|
-
applyPendingReasoningDetail(block);
|
|
437
486
|
return block;
|
|
438
487
|
};
|
|
439
488
|
const flushDeferredBlocks = () => {
|
|
@@ -586,16 +635,14 @@ export const stream = (model, context, options) => {
|
|
|
586
635
|
const reasoningDetails = choice.delta.reasoning_details;
|
|
587
636
|
if (Array.isArray(reasoningDetails)) {
|
|
588
637
|
for (const detail of reasoningDetails) {
|
|
589
|
-
if (
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
}
|
|
598
|
-
}
|
|
638
|
+
if (!isOpenAIReasoningDetail(detail))
|
|
639
|
+
continue;
|
|
640
|
+
const block = ensureThinkingBlock("");
|
|
641
|
+
const preservedDetails = parseOpenAIReasoningDetails(block.thinkingSignature) ?? [];
|
|
642
|
+
appendOpenAIReasoningDetail(preservedDetails, detail);
|
|
643
|
+
// Keep provider replay data in the existing signature slot. OpenRouter
|
|
644
|
+
// requires the complete reasoning_details sequence in its original order.
|
|
645
|
+
block.thinkingSignature = JSON.stringify(preservedDetails);
|
|
599
646
|
}
|
|
600
647
|
}
|
|
601
648
|
}
|
|
@@ -670,7 +717,7 @@ export const streamSimple = (model, context, options) => {
|
|
|
670
717
|
});
|
|
671
718
|
};
|
|
672
719
|
function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId, compat = getCompat(model)) {
|
|
673
|
-
const headers = { ...model.headers };
|
|
720
|
+
const headers = { "User-Agent": getPiUserAgent(), ...model.headers };
|
|
674
721
|
if (model.provider === "github-copilot") {
|
|
675
722
|
const hasImages = hasCopilotVisionInput(context.messages);
|
|
676
723
|
const copilotHeaders = buildCopilotDynamicHeaders({
|
|
@@ -695,9 +742,6 @@ function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId,
|
|
|
695
742
|
if (optionsHeaders) {
|
|
696
743
|
Object.assign(headers, optionsHeaders);
|
|
697
744
|
}
|
|
698
|
-
if (model.provider === "xai") {
|
|
699
|
-
forcePiUserAgent(headers);
|
|
700
|
-
}
|
|
701
745
|
return new OpenAI({
|
|
702
746
|
apiKey,
|
|
703
747
|
baseURL: model.baseUrl,
|
|
@@ -759,7 +803,7 @@ function buildParams(model, context, options, compat = getCompat(model), cacheRe
|
|
|
759
803
|
if (cacheControl) {
|
|
760
804
|
applyAnthropicCacheControl(messages, params.tools, cacheControl);
|
|
761
805
|
}
|
|
762
|
-
if (options?.toolChoice) {
|
|
806
|
+
if (options?.toolChoice && params.tools?.length) {
|
|
763
807
|
params.tool_choice = options.toolChoice;
|
|
764
808
|
}
|
|
765
809
|
const thinkingTokenBudgetField = resolveThinkingTokenBudgetField(compat);
|
|
@@ -1121,9 +1165,16 @@ export function convertMessages(model, context, compat, options = {}) {
|
|
|
1121
1165
|
text: sanitizeSurrogates(block.text),
|
|
1122
1166
|
}));
|
|
1123
1167
|
const assistantText = assistantTextParts.map((part) => part.text).join("");
|
|
1124
|
-
const
|
|
1125
|
-
|
|
1126
|
-
|
|
1168
|
+
const thinkingBlocks = msg.content.filter(isThinkingContentBlock);
|
|
1169
|
+
const toolCalls = msg.content.filter(isToolCallBlock);
|
|
1170
|
+
const signedReasoningDetails = thinkingBlocks
|
|
1171
|
+
.map((block) => parseOpenAIReasoningDetails(block.thinkingSignature))
|
|
1172
|
+
.find((details) => details !== undefined);
|
|
1173
|
+
const legacyReasoningDetails = toolCalls
|
|
1174
|
+
.map((toolCall) => parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature))
|
|
1175
|
+
.filter((detail) => detail !== undefined);
|
|
1176
|
+
const preservedReasoningDetails = signedReasoningDetails ?? (legacyReasoningDetails.length > 0 ? legacyReasoningDetails : undefined);
|
|
1177
|
+
const nonEmptyThinkingBlocks = thinkingBlocks.filter((block) => block.thinking.trim().length > 0);
|
|
1127
1178
|
if (nonEmptyThinkingBlocks.length > 0) {
|
|
1128
1179
|
if (compat.requiresThinkingAsText) {
|
|
1129
1180
|
// Convert thinking blocks to plain text (no tags to avoid model mimicking them)
|
|
@@ -1161,7 +1212,6 @@ export function convertMessages(model, context, compat, options = {}) {
|
|
|
1161
1212
|
// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].
|
|
1162
1213
|
assistantMsg.content = assistantText;
|
|
1163
1214
|
}
|
|
1164
|
-
const toolCalls = msg.content.filter(isToolCallBlock);
|
|
1165
1215
|
if (toolCalls.length > 0) {
|
|
1166
1216
|
assistantMsg.tool_calls = toolCalls.map((tc) => {
|
|
1167
1217
|
const customInputProperty = options?.grammarToolInputProperties?.get(tc.name);
|
|
@@ -1184,20 +1234,9 @@ export function convertMessages(model, context, compat, options = {}) {
|
|
|
1184
1234
|
},
|
|
1185
1235
|
};
|
|
1186
1236
|
});
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
try {
|
|
1191
|
-
return JSON.parse(tc.thoughtSignature);
|
|
1192
|
-
}
|
|
1193
|
-
catch {
|
|
1194
|
-
return null;
|
|
1195
|
-
}
|
|
1196
|
-
})
|
|
1197
|
-
.filter(Boolean);
|
|
1198
|
-
if (reasoningDetails.length > 0) {
|
|
1199
|
-
Object.assign(assistantMsg, { reasoning_details: reasoningDetails });
|
|
1200
|
-
}
|
|
1237
|
+
}
|
|
1238
|
+
if (preservedReasoningDetails) {
|
|
1239
|
+
assistantMsg.reasoning_details = preservedReasoningDetails;
|
|
1201
1240
|
}
|
|
1202
1241
|
if (compat.requiresReasoningContentOnAssistantMessages &&
|
|
1203
1242
|
model.reasoning &&
|