@caupulican/pi-ai 0.81.15 → 0.81.16

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.
@@ -1,6 +1,7 @@
1
1
  import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.js";
2
2
  import type { Context, Model, OpenAICompletionsCompat, SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.ts";
3
3
  import { type ToolNameMap } from "../utils/tool-names.ts";
4
+ export declare function formatOpenAICompletionsProviderError(error: unknown, model: Model<"openai-completions">): string;
4
5
  export interface OpenAICompletionsOptions extends StreamOptions {
5
6
  toolChoice?: "auto" | "none" | "required" | {
6
7
  type: "function";
@@ -1 +1 @@
1
- {"version":3,"file":"openai-completions.d.ts","sourceRoot":"","sources":["../../src/providers/openai-completions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAOX,0BAA0B,EAG1B,MAAM,sCAAsC,CAAC;AAE9C,OAAO,KAAK,EAGX,OAAO,EAGP,KAAK,EACL,uBAAuB,EACvB,mBAAmB,EAEnB,cAAc,EACd,aAAa,EAMb,MAAM,aAAa,CAAC;AAMrB,OAAO,EAAqB,KAAK,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAoD7E,MAAM,WAAW,wBAAyB,SAAQ,aAAa;IAC9D,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,UAAU,GAAG;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,QAAQ,EAAE;YAAE,IAAI,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IAC7F,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;CAClE;AAOD,KAAK,+BAA+B,GAAG,IAAI,CAAC,QAAQ,CAAC,uBAAuB,CAAC,EAAE,oBAAoB,CAAC,GAAG;IACtG,kBAAkB,CAAC,EAAE,uBAAuB,CAAC,oBAAoB,CAAC,CAAC;CACnE,CAAC;AAsBF,eAAO,MAAM,uBAAuB,EAAE,cAAc,CAAC,oBAAoB,EAAE,wBAAwB,CAmWlG,CAAC;AAEF,eAAO,MAAM,6BAA6B,EAAE,cAAc,CAAC,oBAAoB,EAAE,mBAAmB,CAiBnG,CAAC;AA4SF,wBAAgB,eAAe,CAC9B,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,EAClC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,+BAA+B,EACvC,WAAW,GAAE,WAAoD,GAC/D,0BAA0B,EAAE,CAgP9B","sourcesContent":["import OpenAI from \"openai\";\nimport type {\n\tChatCompletionAssistantMessageParam,\n\tChatCompletionChunk,\n\tChatCompletionContentPart,\n\tChatCompletionContentPartImage,\n\tChatCompletionContentPartText,\n\tChatCompletionDeveloperMessageParam,\n\tChatCompletionMessageParam,\n\tChatCompletionSystemMessageParam,\n\tChatCompletionToolMessageParam,\n} from \"openai/resources/chat/completions.js\";\nimport { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tOpenAICompletionsCompat,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJsonState } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createToolNameMap, type ToolNameMap } from \"../utils/tool-names.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Check if conversation messages contain tool calls or tool results.\n * This is needed because Anthropic (via proxy) requires the tools param\n * to be present when messages include tool_calls or tool role messages.\n */\nfunction hasToolHistory(messages: Message[]): boolean {\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn true;\n\t\t}\n\t\tif (msg.role === \"assistant\") {\n\t\t\tif (msg.content.some((block) => block.type === \"toolCall\")) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction getOpenAICompletionsApiKey(model: Model<\"openai-completions\">, apiKey: string | undefined): string {\n\tif (apiKey) {\n\t\treturn apiKey;\n\t}\n\tif (model.provider === \"llama-cpp\") {\n\t\treturn \"sk-no-key\";\n\t}\n\tthrow new Error(`No API key for provider: ${model.provider}`);\n}\n\nfunction isTextContentBlock(block: { type: string }): block is TextContent {\n\treturn block.type === \"text\";\n}\n\nfunction isThinkingContentBlock(block: { type: string }): block is ThinkingContent {\n\treturn block.type === \"thinking\";\n}\n\nfunction isToolCallBlock(block: { type: string }): block is ToolCall {\n\treturn block.type === \"toolCall\";\n}\n\nfunction isImageContentBlock(block: { type: string }): block is ImageContent {\n\treturn block.type === \"image\";\n}\n\nexport interface OpenAICompletionsOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"required\" | { type: \"function\"; function: { name: string } };\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n}\n\ninterface OpenAICompatCacheControl {\n\ttype: \"ephemeral\";\n\tttl?: string;\n}\n\ntype ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, \"cacheControlFormat\"> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n};\n\ntype ChatCompletionInstructionMessageParam = ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam;\n\ntype ChatCompletionTextPartWithCacheControl = ChatCompletionContentPartText & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\ntype ChatCompletionToolWithCacheControl = OpenAI.Chat.Completions.ChatCompletionTool & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport const streamOpenAICompletions: StreamFunction<\"openai-completions\", OpenAICompletionsOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\t\t\tconst compat = getCompat(model);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);\n\t\t\tlet params = buildParams(model, context, options, compat, cacheRetention);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: options?.maxRetries ?? 0,\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await client.chat.completions\n\t\t\t\t.create(params, requestOptions)\n\t\t\t\t.withResponse();\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tinterface StreamingToolCallBlock extends ToolCall {\n\t\t\t\tpartialArgs?: string;\n\t\t\t\tpartialArgsComplete?: boolean;\n\t\t\t\tstreamIndex?: number;\n\t\t\t}\n\t\t\ttype StreamingBlock = TextContent | ThinkingContent | StreamingToolCallBlock;\n\t\t\ttype StreamingToolCallDelta = NonNullable<ChatCompletionChunk.Choice.Delta[\"tool_calls\"]>[number];\n\n\t\t\tlet textBlock: TextContent | null = null;\n\t\t\tlet thinkingBlock: ThinkingContent | null = null;\n\t\t\tlet hasFinishReason = false;\n\t\t\tconst toolCallBlocksByIndex = new Map<number, StreamingToolCallBlock>();\n\t\t\tconst toolCallBlocksById = new Map<string, StreamingToolCallBlock>();\n\t\t\tconst toolCallIdCounts = new Map<string, number>();\n\t\t\tconst usedToolCallIds = new Set<string>();\n\t\t\tlet syntheticToolCallOrdinal = 0;\n\t\t\tconst pendingReasoningDetailsById = new Map<string, string>();\n\t\t\tconst blocks = output.content as StreamingBlock[];\n\t\t\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\t\t\tconst getContentIndex = (block: StreamingBlock) => blocks.indexOf(block);\n\t\t\tconst finishBlock = (block: StreamingBlock) => {\n\t\t\t\tconst contentIndex = getContentIndex(block);\n\t\t\t\tif (contentIndex === -1) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t// Finalize in-place and strip the scratch buffers so replay only\n\t\t\t\t\t// carries parsed arguments.\n\t\t\t\t\tdelete block.partialArgs;\n\t\t\t\t\tdelete block.partialArgsComplete;\n\t\t\t\t\tdelete block.streamIndex;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\ttoolCall: block,\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\tconst ensureTextBlock = () => {\n\t\t\t\tif (!textBlock) {\n\t\t\t\t\ttextBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\tblocks.push(textBlock);\n\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: getContentIndex(textBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn textBlock;\n\t\t\t};\n\t\t\tconst ensureThinkingBlock = (thinkingSignature: string) => {\n\t\t\t\tif (!thinkingBlock) {\n\t\t\t\t\tthinkingBlock = {\n\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\tthinkingSignature,\n\t\t\t\t\t};\n\t\t\t\t\tblocks.push(thinkingBlock);\n\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: getContentIndex(thinkingBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn thinkingBlock;\n\t\t\t};\n\t\t\tconst attachPendingReasoningDetail = (block: StreamingToolCallBlock, id: string) => {\n\t\t\t\tconst pending = pendingReasoningDetailsById.get(id);\n\t\t\t\tif (pending !== undefined && !block.thoughtSignature) {\n\t\t\t\t\tblock.thoughtSignature = pending;\n\t\t\t\t\tpendingReasoningDetailsById.delete(id);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst allocateToolCallId = (rawId: string | undefined, streamIndex: number | undefined) => {\n\t\t\t\tconst fallbackOrdinal = streamIndex ?? syntheticToolCallOrdinal++;\n\t\t\t\tconst baseId = rawId && rawId.length > 0 ? rawId : `call_${fallbackOrdinal}`;\n\t\t\t\tlet count = toolCallIdCounts.get(baseId) ?? 0;\n\t\t\t\tlet candidate = count === 0 ? baseId : `${baseId}_${count + 1}`;\n\t\t\t\twhile (usedToolCallIds.has(candidate)) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tcandidate = `${baseId}_${count + 1}`;\n\t\t\t\t}\n\t\t\t\ttoolCallIdCounts.set(baseId, count + 1);\n\t\t\t\tusedToolCallIds.add(candidate);\n\t\t\t\treturn candidate;\n\t\t\t};\n\t\t\tconst ensureToolCallBlock = (toolCall: StreamingToolCallDelta) => {\n\t\t\t\tconst streamIndex = typeof toolCall.index === \"number\" ? toolCall.index : undefined;\n\t\t\t\tlet block = streamIndex !== undefined ? toolCallBlocksByIndex.get(streamIndex) : undefined;\n\t\t\t\tif (!block && streamIndex === undefined && toolCall.id) {\n\t\t\t\t\tblock = toolCallBlocksById.get(toolCall.id);\n\t\t\t\t}\n\t\t\t\tif (!block) {\n\t\t\t\t\tblock = {\n\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\tid: allocateToolCallId(toolCall.id, streamIndex),\n\t\t\t\t\t\tname: toolCall.function?.name ? toolNameMap.toOriginalName(toolCall.function.name) : \"\",\n\t\t\t\t\t\targuments: {},\n\t\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t\t\tpartialArgsComplete: true,\n\t\t\t\t\t\tstreamIndex,\n\t\t\t\t\t};\n\t\t\t\t\tif (streamIndex !== undefined) {\n\t\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t\t}\n\t\t\t\t\tif (toolCall.id && !toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_start\",\n\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (streamIndex !== undefined && block.streamIndex === undefined) {\n\t\t\t\t\tblock.streamIndex = streamIndex;\n\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t}\n\t\t\t\tif (toolCall.id) {\n\t\t\t\t\tif (!toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tattachPendingReasoningDetail(block, toolCall.id);\n\t\t\t\t}\n\t\t\t\treturn block;\n\t\t\t};\n\n\t\t\tfor await (const chunk of openaiStream) {\n\t\t\t\tif (!chunk || typeof chunk !== \"object\") continue;\n\n\t\t\t\t// OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,\n\t\t\t\t// and each chunk in a streamed completion carries the same id.\n\t\t\t\toutput.responseId ||= chunk.id;\n\t\t\t\tif (typeof chunk.model === \"string\" && chunk.model.length > 0 && chunk.model !== model.id) {\n\t\t\t\t\toutput.responseModel ||= chunk.model;\n\t\t\t\t}\n\t\t\t\tif (chunk.usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage(chunk.usage, model);\n\t\t\t\t}\n\n\t\t\t\tconst choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;\n\t\t\t\tif (!choice) continue;\n\n\t\t\t\t// Fallback: some providers (e.g., Moonshot) return usage\n\t\t\t\t// in choice.usage instead of the standard chunk.usage\n\t\t\t\tif (!chunk.usage && (choice as any).usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage((choice as any).usage, model);\n\t\t\t\t}\n\n\t\t\t\tif (choice.finish_reason) {\n\t\t\t\t\tconst finishReasonResult = mapStopReason(choice.finish_reason);\n\t\t\t\t\toutput.stopReason = finishReasonResult.stopReason;\n\t\t\t\t\tif (finishReasonResult.errorMessage) {\n\t\t\t\t\t\toutput.errorMessage = finishReasonResult.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\thasFinishReason = true;\n\t\t\t\t}\n\n\t\t\t\tif (choice.delta) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tchoice.delta.content !== null &&\n\t\t\t\t\t\tchoice.delta.content !== undefined &&\n\t\t\t\t\t\tchoice.delta.content.length > 0\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst block = ensureTextBlock();\n\t\t\t\t\t\tblock.text += choice.delta.content;\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\tdelta: choice.delta.content,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t// Some endpoints return reasoning in reasoning_content (llama.cpp),\n\t\t\t\t\t// or reasoning (other openai compatible endpoints)\n\t\t\t\t\t// Use the first non-empty reasoning field to avoid duplication\n\t\t\t\t\t// (e.g., chutes.ai returns both reasoning_content and reasoning with same content)\n\t\t\t\t\tconst reasoningFields = [\"reasoning_content\", \"reasoning\", \"reasoning_text\"];\n\t\t\t\t\tconst deltaFields = choice.delta as Record<string, unknown>;\n\t\t\t\t\tlet foundReasoningField: string | null = null;\n\t\t\t\t\tfor (const field of reasoningFields) {\n\t\t\t\t\t\tconst value = deltaFields[field];\n\t\t\t\t\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\t\t\t\t\tfoundReasoningField = field;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foundReasoningField) {\n\t\t\t\t\t\tconst delta = deltaFields[foundReasoningField];\n\t\t\t\t\t\tif (typeof delta === \"string\" && delta.length > 0) {\n\t\t\t\t\t\t\tconst thinkingSignature =\n\t\t\t\t\t\t\t\tmodel.provider === \"opencode-go\" && foundReasoningField === \"reasoning\"\n\t\t\t\t\t\t\t\t\t? \"reasoning_content\"\n\t\t\t\t\t\t\t\t\t: foundReasoningField;\n\t\t\t\t\t\t\tconst block = ensureThinkingBlock(thinkingSignature);\n\t\t\t\t\t\t\tblock.thinking += delta;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (choice?.delta?.tool_calls) {\n\t\t\t\t\t\tfor (const toolCall of choice.delta.tool_calls) {\n\t\t\t\t\t\t\tconst block = ensureToolCallBlock(toolCall);\n\t\t\t\t\t\t\tif (!block.name && toolCall.function?.name) {\n\t\t\t\t\t\t\t\tblock.name = toolNameMap.toOriginalName(toolCall.function.name);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlet delta = \"\";\n\t\t\t\t\t\t\tif (toolCall.function?.arguments) {\n\t\t\t\t\t\t\t\tdelta = toolCall.function.arguments;\n\t\t\t\t\t\t\t\tblock.partialArgs = (block.partialArgs ?? \"\") + toolCall.function.arguments;\n\t\t\t\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst reasoningDetails = (choice.delta as any).reasoning_details;\n\t\t\t\t\tif (reasoningDetails && Array.isArray(reasoningDetails)) {\n\t\t\t\t\t\tfor (const detail of reasoningDetails) {\n\t\t\t\t\t\t\tif (detail.type === \"reasoning.encrypted\" && detail.id && detail.data) {\n\t\t\t\t\t\t\t\tconst serialized = JSON.stringify(detail);\n\t\t\t\t\t\t\t\tconst matchingToolCall = toolCallBlocksById.get(detail.id);\n\t\t\t\t\t\t\t\tif (matchingToolCall) {\n\t\t\t\t\t\t\t\t\tmatchingToolCall.thoughtSignature = serialized;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tpendingReasoningDetailsById.set(detail.id, serialized);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (output.stopReason !== \"toolUse\") {\n\t\t\t\tfor (const block of blocks) {\n\t\t\t\t\tif (block.type === \"toolCall\" && block.partialArgs?.trim() && block.partialArgsComplete === false) {\n\t\t\t\t\t\tblock.errorMessage = `Tool call arguments were truncated before complete JSON was received (stop reason: ${output.stopReason}). Retry the tool call with complete JSON arguments.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const block of blocks) {\n\t\t\t\tfinishBlock(block);\n\t\t\t}\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 === \"aborted\") {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Provider returned an error stop reason\");\n\t\t\t}\n\t\t\tif (!hasFinishReason) {\n\t\t\t\tthrow new Error(\"Stream ended without finish_reason\");\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\tdelete (block as { index?: number }).index;\n\t\t\t\t// Streaming scratch buffers are only used during parsing; never persist them.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t\tdelete (block as { partialArgsComplete?: boolean }).partialArgsComplete;\n\t\t\t\tdelete (block as { streamIndex?: number }).streamIndex;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\t\t// Some providers via OpenRouter give additional information in this field.\n\t\t\tconst rawMetadata = (error as any)?.error?.metadata?.raw;\n\t\t\tif (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) {\n\t\t\t\toutput.errorMessage += `\\n${rawMetadata}`;\n\t\t\t}\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\nexport const streamSimpleOpenAICompletions: StreamFunction<\"openai-completions\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst toolChoice = (options as OpenAICompletionsOptions | undefined)?.toolChoice;\n\n\treturn streamOpenAICompletions(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t\ttoolChoice,\n\t} satisfies OpenAICompletionsOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n) {\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId && compat.sendSessionAffinityHeaders) {\n\t\theaders.session_id = sessionId;\n\t\theaders[\"x-client-request-id\"] = sessionId;\n\t\theaders[\"x-session-affinity\"] = sessionId;\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\tconst defaultHeaders =\n\t\tmodel.provider === \"cloudflare-ai-gateway\"\n\t\t\t? {\n\t\t\t\t\t...headers,\n\t\t\t\t\tAuthorization: headers.Authorization ?? null,\n\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t}\n\t\t\t: headers;\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n\tcacheRetention: CacheRetention = resolveCacheRetention(options?.cacheRetention),\n) {\n\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\tconst messages = convertMessages(model, context, compat, toolNameMap);\n\tconst cacheControl = getCompatCacheControl(compat, cacheRetention);\n\n\tconst params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages,\n\t\tstream: true,\n\t\tprompt_cache_key:\n\t\t\t(model.baseUrl.includes(\"api.openai.com\") && cacheRetention !== \"none\") ||\n\t\t\t(cacheRetention === \"long\" && compat.supportsLongCacheRetention)\n\t\t\t\t? clampOpenAIPromptCacheKey(options?.sessionId)\n\t\t\t\t: undefined,\n\t\tprompt_cache_retention: cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined,\n\t};\n\n\tif (compat.supportsUsageInStreaming !== false) {\n\t\t(params as any).stream_options = { include_usage: true };\n\t}\n\n\tif (compat.supportsStore) {\n\t\tparams.store = false;\n\t}\n\n\tif (options?.maxTokens) {\n\t\tif (compat.maxTokensField === \"max_tokens\") {\n\t\t\t(params as any).max_tokens = options.maxTokens;\n\t\t} else {\n\t\t\tparams.max_completion_tokens = options.maxTokens;\n\t\t}\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\tparams.tools = convertTools(context.tools, compat, toolNameMap);\n\t\tif (compat.zaiToolStream) {\n\t\t\t(params as any).tool_stream = true;\n\t\t}\n\t} else if (hasToolHistory(context.messages)) {\n\t\t// Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results\n\t\tparams.tools = [];\n\t}\n\n\tif (cacheControl) {\n\t\tapplyAnthropicCacheControl(messages, params.tools, cacheControl);\n\t}\n\n\tif (options?.toolChoice) {\n\t\tparams.tool_choice =\n\t\t\ttypeof options.toolChoice === \"object\"\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: { name: toolNameMap.toProviderName(options.toolChoice.function.name) },\n\t\t\t\t\t}\n\t\t\t\t: options.toolChoice;\n\t}\n\n\tif (compat.thinkingFormat === \"zai\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen-chat-template\" && model.reasoning) {\n\t\t(params as any).chat_template_kwargs = {\n\t\t\tenable_thinking: !!options?.reasoningEffort,\n\t\t\tpreserve_thinking: true,\n\t\t};\n\t} else if (compat.thinkingFormat === \"deepseek\" && model.reasoning) {\n\t\t(params as any).thinking = { type: options?.reasoningEffort ? \"enabled\" : \"disabled\" };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\t(params as any).reasoning_effort =\n\t\t\t\tmodel.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"openrouter\" && model.reasoning) {\n\t\t// OpenRouter normalizes reasoning across providers via a nested reasoning object.\n\t\tconst openRouterParams = params as typeof params & { reasoning?: { effort?: string } };\n\t\tif (options?.reasoningEffort) {\n\t\t\topenRouterParams.reasoning = {\n\t\t\t\teffort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort,\n\t\t\t};\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\topenRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? \"none\" };\n\t\t}\n\t} else if (compat.thinkingFormat === \"together\" && model.reasoning) {\n\t\tconst togetherParams = params as Omit<typeof params, \"reasoning_effort\"> & {\n\t\t\treasoning?: { enabled: boolean };\n\t\t\treasoning_effort?: string;\n\t\t};\n\t\ttogetherParams.reasoning = { enabled: !!options?.reasoningEffort };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\ttogetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"string-thinking\" && model.reasoning) {\n\t\tconst stringThinkingParams = params as typeof params & { thinking?: string };\n\t\tif (options?.reasoningEffort) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.off ?? \"none\";\n\t\t}\n\t} else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\t// OpenAI-style reasoning_effort\n\t\t(params as any).reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t} else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\tconst offValue = model.thinkingLevelMap?.off;\n\t\tif (typeof offValue === \"string\") {\n\t\t\t(params as any).reasoning_effort = offValue;\n\t\t}\n\t}\n\n\t// OpenRouter provider routing preferences\n\tif (model.compat?.openRouterRouting) {\n\t\t(params as any).provider = model.compat.openRouterRouting;\n\t}\n\n\t// Vercel AI Gateway provider routing preferences\n\tif (model.baseUrl.includes(\"ai-gateway.vercel.sh\") && model.compat?.vercelGatewayRouting) {\n\t\tconst routing = model.compat.vercelGatewayRouting;\n\t\tif (routing.only || routing.order) {\n\t\t\tconst gatewayOptions: Record<string, string[]> = {};\n\t\t\tif (routing.only) gatewayOptions.only = routing.only;\n\t\t\tif (routing.order) gatewayOptions.order = routing.order;\n\t\t\t(params as any).providerOptions = { gateway: gatewayOptions };\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction getCompatCacheControl(\n\tcompat: ResolvedOpenAICompletionsCompat,\n\tcacheRetention: CacheRetention,\n): OpenAICompatCacheControl | undefined {\n\tif (compat.cacheControlFormat !== \"anthropic\" || cacheRetention === \"none\") {\n\t\treturn undefined;\n\t}\n\n\tconst ttl = cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"1h\" : undefined;\n\treturn { type: \"ephemeral\", ...(ttl ? { ttl } : {}) };\n}\n\nfunction applyAnthropicCacheControl(\n\tmessages: ChatCompletionMessageParam[],\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\taddCacheControlToSystemPrompt(messages, cacheControl);\n\taddCacheControlToLastTool(tools, cacheControl);\n\taddCacheControlToLastConversationMessage(messages, cacheControl);\n}\n\nfunction addCacheControlToSystemPrompt(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (const message of messages) {\n\t\tif (message.role === \"system\" || message.role === \"developer\") {\n\t\t\taddCacheControlToInstructionMessage(message, cacheControl);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastConversationMessage(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\t\tif (addCacheControlToMessage(message, cacheControl)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastTool(\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tif (!tools || tools.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastTool = tools[tools.length - 1] as ChatCompletionToolWithCacheControl;\n\tlastTool.cache_control = cacheControl;\n}\n\nfunction addCacheControlToInstructionMessage(\n\tmessage: ChatCompletionInstructionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\treturn addCacheControlToTextContent(message, cacheControl);\n}\n\nfunction addCacheControlToMessage(\n\tmessage: ChatCompletionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\treturn addCacheControlToTextContent(message, cacheControl);\n\t}\n\treturn false;\n}\n\nfunction addCacheControlToTextContent(\n\tmessage:\n\t\t| ChatCompletionInstructionMessageParam\n\t\t| ChatCompletionAssistantMessageParam\n\t\t| Extract<ChatCompletionMessageParam, { role: \"user\" }>,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\tif (content.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tmessage.content = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: content,\n\t\t\t\tcache_control: cacheControl,\n\t\t\t},\n\t\t] as ChatCompletionTextPartWithCacheControl[];\n\t\treturn true;\n\t}\n\n\tif (!Array.isArray(content)) {\n\t\treturn false;\n\t}\n\n\tfor (let i = content.length - 1; i >= 0; i--) {\n\t\tconst part = content[i];\n\t\tif (part?.type === \"text\") {\n\t\t\tconst textPart = part as ChatCompletionTextPartWithCacheControl;\n\t\t\ttextPart.cache_control = cacheControl;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nexport function convertMessages(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(context.tools ?? []),\n): ChatCompletionMessageParam[] {\n\tconst params: ChatCompletionMessageParam[] = [];\n\n\tconst normalizeToolCallId = (id: string): string => {\n\t\t// Handle pipe-separated IDs from OpenAI Responses API\n\t\t// Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)\n\t\t// These come from providers like github-copilot, openai-codex, opencode\n\t\t// Extract just the call_id part and normalize it\n\t\tif (id.includes(\"|\")) {\n\t\t\tconst [callId] = id.split(\"|\");\n\t\t\t// Sanitize to allowed chars and truncate to 40 chars (OpenAI limit)\n\t\t\treturn callId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 40);\n\t\t}\n\n\t\tif (model.provider === \"openai\") return id.length > 40 ? id.slice(0, 40) : id;\n\t\treturn id;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId(id));\n\n\tif (context.systemPrompt) {\n\t\tconst useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n\t\tconst role = useDeveloperRole ? \"developer\" : \"system\";\n\t\tparams.push({ role: role, content: sanitizeSurrogates(context.systemPrompt) });\n\t}\n\n\tlet lastRole: string | null = null;\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\t\t// Some providers don't allow user messages directly after tool results\n\t\t// Insert a synthetic assistant message to bridge the gap\n\t\tif (compat.requiresAssistantAfterToolResult && lastRole === \"toolResult\" && msg.role === \"user\") {\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t});\n\t\t}\n\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: sanitizeSurrogates(msg.content),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ChatCompletionContentPart[] = msg.content.map((item): ChatCompletionContentPart => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartText;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\turl: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartImage;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\t// Some providers don't accept null content, use empty string instead\n\t\t\tconst assistantMsg: ChatCompletionAssistantMessageParam = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: compat.requiresAssistantAfterToolResult ? \"\" : null,\n\t\t\t};\n\n\t\t\tconst assistantTextParts = msg.content\n\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t.filter((block) => block.text.trim().length > 0)\n\t\t\t\t.map(\n\t\t\t\t\t(block) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t\t}) satisfies ChatCompletionContentPartText,\n\t\t\t\t);\n\t\t\tconst assistantText = assistantTextParts.map((part) => part.text).join(\"\");\n\n\t\t\tconst nonEmptyThinkingBlocks = msg.content\n\t\t\t\t.filter(isThinkingContentBlock)\n\t\t\t\t.filter((block) => block.thinking.trim().length > 0);\n\t\t\tif (nonEmptyThinkingBlocks.length > 0) {\n\t\t\t\tif (compat.requiresThinkingAsText) {\n\t\t\t\t\t// Convert thinking blocks to plain text (no tags to avoid model mimicking them)\n\t\t\t\t\tconst thinkingText = nonEmptyThinkingBlocks\n\t\t\t\t\t\t.map((block) => sanitizeSurrogates(block.thinking))\n\t\t\t\t\t\t.join(\"\\n\\n\");\n\t\t\t\t\tassistantMsg.content = [{ type: \"text\", text: thinkingText }, ...assistantTextParts];\n\t\t\t\t} else {\n\t\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\t\tif (assistantText.length > 0) {\n\t\t\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss)\n\t\t\t\t\tlet signature = nonEmptyThinkingBlocks[0].thinkingSignature;\n\t\t\t\t\tif (model.provider === \"opencode-go\" && signature === \"reasoning\") {\n\t\t\t\t\t\tsignature = \"reasoning_content\";\n\t\t\t\t\t}\n\t\t\t\t\tif (signature && signature.length > 0) {\n\t\t\t\t\t\t(assistantMsg as any)[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (assistantText.length > 0) {\n\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t}\n\n\t\t\tconst toolCalls = msg.content.filter(isToolCallBlock);\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tassistantMsg.tool_calls = toolCalls.map((tc) => ({\n\t\t\t\t\tid: tc.id,\n\t\t\t\t\ttype: \"function\" as const,\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: toolNameMap.toProviderName(tc.name),\n\t\t\t\t\t\targuments: JSON.stringify(tc.arguments),\n\t\t\t\t\t},\n\t\t\t\t}));\n\t\t\t\tconst reasoningDetails = toolCalls\n\t\t\t\t\t.filter((tc) => tc.thoughtSignature)\n\t\t\t\t\t.map((tc) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn JSON.parse(tc.thoughtSignature!);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.filter(Boolean);\n\t\t\t\tif (reasoningDetails.length > 0) {\n\t\t\t\t\t(assistantMsg as any).reasoning_details = reasoningDetails;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcompat.requiresReasoningContentOnAssistantMessages &&\n\t\t\t\tmodel.reasoning &&\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content === undefined\n\t\t\t) {\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content = \"\";\n\t\t\t}\n\t\t\t// Skip assistant messages that have no content and no tool calls.\n\t\t\t// Some providers require \"either content or tool_calls, but not none\".\n\t\t\t// Other providers also don't accept empty assistant messages.\n\t\t\t// This handles aborted assistant responses that got no content.\n\t\t\tconst content = assistantMsg.content;\n\t\t\tconst hasContent =\n\t\t\t\tcontent !== null &&\n\t\t\t\tcontent !== undefined &&\n\t\t\t\t(typeof content === \"string\" ? content.length > 0 : content.length > 0);\n\t\t\tif (!hasContent && !assistantMsg.tool_calls) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparams.push(assistantMsg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst imageBlocks: Array<{ type: \"image_url\"; image_url: { url: string } }> = [];\n\t\t\tlet j = i;\n\n\t\t\tfor (; j < transformedMessages.length && transformedMessages[j].role === \"toolResult\"; j++) {\n\t\t\t\tconst toolMsg = transformedMessages[j] as ToolResultMessage;\n\n\t\t\t\t// Extract text and image content\n\t\t\t\tconst textResult = toolMsg.content\n\t\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t\t.map((block) => block.text)\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tconst hasImages = toolMsg.content.some((c) => c.type === \"image\");\n\n\t\t\t\t// Always send tool result with text (or placeholder if only images)\n\t\t\t\tconst hasText = textResult.length > 0;\n\t\t\t\t// Some providers require the 'name' field in tool results\n\t\t\t\tconst toolResultMsg: ChatCompletionToolMessageParam = {\n\t\t\t\t\trole: \"tool\",\n\t\t\t\t\tcontent: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n\t\t\t\t\ttool_call_id: toolMsg.toolCallId,\n\t\t\t\t};\n\t\t\t\tif (compat.requiresToolResultName && toolMsg.toolName) {\n\t\t\t\t\t(toolResultMsg as any).name = toolMsg.toolName;\n\t\t\t\t}\n\t\t\t\tparams.push(toolResultMsg);\n\n\t\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\t\tfor (const block of toolMsg.content) {\n\t\t\t\t\t\tif (isImageContentBlock(block)) {\n\t\t\t\t\t\t\timageBlocks.push({\n\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\t\turl: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ti = j - 1;\n\n\t\t\tif (imageBlocks.length > 0) {\n\t\t\t\tif (compat.requiresAssistantAfterToolResult) {\n\t\t\t\t\tparams.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Attached image(s) from tool result:\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...imageBlocks,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tlastRole = \"user\";\n\t\t\t} else {\n\t\t\t\tlastRole = \"toolResult\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tlastRole = msg.role;\n\t}\n\n\treturn params;\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(tools),\n): OpenAI.Chat.Completions.ChatCompletionTool[] {\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: toolNameMap.toProviderName(tool.name),\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\t\t// Only include strict if provider supports it. Some reject unknown fields.\n\t\t\t...(compat.supportsStrictMode !== false && { strict: false }),\n\t\t},\n\t}));\n}\n\nfunction parseChunkUsage(\n\trawUsage: {\n\t\tprompt_tokens?: number;\n\t\tcompletion_tokens?: number;\n\t\tprompt_cache_hit_tokens?: number;\n\t\tprompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\t\tcost?: number;\n\t},\n\tmodel: Model<\"openai-completions\">,\n): AssistantMessage[\"usage\"] {\n\tconst promptTokens = rawUsage.prompt_tokens || 0;\n\tconst cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;\n\tconst cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n\n\t// Follow documented OpenAI/OpenRouter semantics: cached_tokens is cache-read\n\t// tokens (hits). OpenAI does not document or emit cache_write_tokens, but\n\t// OpenRouter-compatible providers can include it as a separate write count.\n\t// OpenRouter's own provider/tests affirm the separate mapping:\n\t// https://github.com/OpenRouterTeam/ai-sdk-provider/pull/409\n\t// Do not subtract writes from cached_tokens, otherwise spec-compliant\n\t// providers are under-reported. DS4 mirrors this contract too:\n\t// https://github.com/antirez/ds4/pull/29\n\tconst input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n\t// OpenAI completion_tokens already includes reasoning_tokens.\n\tconst outputTokens = rawUsage.completion_tokens || 0;\n\tconst usage: AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput: outputTokens,\n\t\tcacheRead: cacheReadTokens,\n\t\tcacheWrite: cacheWriteTokens,\n\t\ttotalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: rawUsage.cost || 0 },\n\t};\n\tcalculateCost(model, usage, { providerSuppliedTotal: Boolean(rawUsage.cost) });\n\treturn usage;\n}\n\nfunction mapStopReason(reason: ChatCompletionChunk.Choice[\"finish_reason\"] | string): {\n\tstopReason: StopReason;\n\terrorMessage?: string;\n} {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\tcase \"end\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"function_call\":\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"content_filter\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: content_filter\" };\n\t\tcase \"network_error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: network_error\" };\n\t\tdefault:\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: `Provider finish_reason: ${reason}`,\n\t\t\t};\n\t}\n}\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai = provider === \"zai\" || baseUrl.includes(\"api.z.ai\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\n\tconst isNonStandard =\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tbaseUrl.includes(\"deepseek.com\") ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway;\n\n\tconst useMaxTokens = baseUrl.includes(\"chutes.ai\") || isMoonshot || isCloudflareAiGateway || isTogether;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n\tconst cacheControlFormat = provider === \"openrouter\" && model.id.startsWith(\"anthropic/\") ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: !isNonStandard && !isOpenRouter,\n\t\tsupportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tsupportsUsageInStreaming: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: false,\n\t\tsupportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Uses explicit model.compat if provided, otherwise auto-detects from provider/URL.\n */\nfunction getCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? {},\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n"]}
1
+ {"version":3,"file":"openai-completions.d.ts","sourceRoot":"","sources":["../../src/providers/openai-completions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAOX,0BAA0B,EAG1B,MAAM,sCAAsC,CAAC;AAE9C,OAAO,KAAK,EAGX,OAAO,EAGP,KAAK,EACL,uBAAuB,EACvB,mBAAmB,EAEnB,cAAc,EACd,aAAa,EAMb,MAAM,aAAa,CAAC;AAMrB,OAAO,EAAqB,KAAK,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAsE7E,wBAAgB,oCAAoC,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,GAAG,MAAM,CAU/G;AAED,MAAM,WAAW,wBAAyB,SAAQ,aAAa;IAC9D,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,UAAU,GAAG;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,QAAQ,EAAE;YAAE,IAAI,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IAC7F,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;CAClE;AAOD,KAAK,+BAA+B,GAAG,IAAI,CAAC,QAAQ,CAAC,uBAAuB,CAAC,EAAE,oBAAoB,CAAC,GAAG;IACtG,kBAAkB,CAAC,EAAE,uBAAuB,CAAC,oBAAoB,CAAC,CAAC;CACnE,CAAC;AAsBF,eAAO,MAAM,uBAAuB,EAAE,cAAc,CAAC,oBAAoB,EAAE,wBAAwB,CAmWlG,CAAC;AAEF,eAAO,MAAM,6BAA6B,EAAE,cAAc,CAAC,oBAAoB,EAAE,mBAAmB,CAiBnG,CAAC;AA4SF,wBAAgB,eAAe,CAC9B,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,EAClC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,+BAA+B,EACvC,WAAW,GAAE,WAAoD,GAC/D,0BAA0B,EAAE,CAgP9B","sourcesContent":["import OpenAI from \"openai\";\nimport type {\n\tChatCompletionAssistantMessageParam,\n\tChatCompletionChunk,\n\tChatCompletionContentPart,\n\tChatCompletionContentPartImage,\n\tChatCompletionContentPartText,\n\tChatCompletionDeveloperMessageParam,\n\tChatCompletionMessageParam,\n\tChatCompletionSystemMessageParam,\n\tChatCompletionToolMessageParam,\n} from \"openai/resources/chat/completions.js\";\nimport { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tOpenAICompletionsCompat,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJsonState } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createToolNameMap, type ToolNameMap } from \"../utils/tool-names.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Check if conversation messages contain tool calls or tool results.\n * This is needed because Anthropic (via proxy) requires the tools param\n * to be present when messages include tool_calls or tool role messages.\n */\nfunction hasToolHistory(messages: Message[]): boolean {\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn true;\n\t\t}\n\t\tif (msg.role === \"assistant\") {\n\t\t\tif (msg.content.some((block) => block.type === \"toolCall\")) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction getOpenAICompletionsApiKey(model: Model<\"openai-completions\">, apiKey: string | undefined): string {\n\tif (apiKey) {\n\t\treturn apiKey;\n\t}\n\tif (model.provider === \"llama-cpp\") {\n\t\treturn \"sk-no-key\";\n\t}\n\tthrow new Error(`No API key for provider: ${model.provider}`);\n}\n\nfunction isTextContentBlock(block: { type: string }): block is TextContent {\n\treturn block.type === \"text\";\n}\n\nfunction isThinkingContentBlock(block: { type: string }): block is ThinkingContent {\n\treturn block.type === \"thinking\";\n}\n\nfunction isToolCallBlock(block: { type: string }): block is ToolCall {\n\treturn block.type === \"toolCall\";\n}\n\nfunction isImageContentBlock(block: { type: string }): block is ImageContent {\n\treturn block.type === \"image\";\n}\n\nfunction isOllamaModel(model: Model<\"openai-completions\">): boolean {\n\treturn model.provider === \"ollama\" || model.baseUrl.includes(\":11434\");\n}\n\nfunction isOllamaContextSizeError(\n\tmodel: Model<\"openai-completions\">,\n\tnormalized: ReturnType<typeof normalizeProviderError>,\n\tformatted: string,\n): boolean {\n\tif (!isOllamaModel(model)) return false;\n\tconst text = `${normalized.message}\\n${normalized.body ?? \"\"}\\n${formatted}`.toLowerCase();\n\treturn (\n\t\ttext.includes(\"exceed_context_size_error\") ||\n\t\ttext.includes(\"prompt too long\") ||\n\t\t(text.includes(\"context\") && text.includes(\"exceed\"))\n\t);\n}\n\nexport function formatOpenAICompletionsProviderError(error: unknown, model: Model<\"openai-completions\">): string {\n\tconst normalized = normalizeProviderError(error);\n\tconst formatted = formatProviderError(normalized);\n\tif (!isOllamaContextSizeError(model, normalized, formatted)) return formatted;\n\treturn (\n\t\t`${formatted}\\n` +\n\t\t`Ollama context action for ${model.provider}/${model.id}: Ollama rejected this request because it exceeds the model's served context window. ` +\n\t\t`Raise the Ollama serving context with OLLAMA_CONTEXT_LENGTH or a per-model num_ctx value, then retry. ` +\n\t\t`Do not lower pi's models.json contextWindow to mask this backend limit.`\n\t);\n}\n\nexport interface OpenAICompletionsOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"required\" | { type: \"function\"; function: { name: string } };\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n}\n\ninterface OpenAICompatCacheControl {\n\ttype: \"ephemeral\";\n\tttl?: string;\n}\n\ntype ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, \"cacheControlFormat\"> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n};\n\ntype ChatCompletionInstructionMessageParam = ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam;\n\ntype ChatCompletionTextPartWithCacheControl = ChatCompletionContentPartText & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\ntype ChatCompletionToolWithCacheControl = OpenAI.Chat.Completions.ChatCompletionTool & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport const streamOpenAICompletions: StreamFunction<\"openai-completions\", OpenAICompletionsOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\t\t\tconst compat = getCompat(model);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);\n\t\t\tlet params = buildParams(model, context, options, compat, cacheRetention);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: options?.maxRetries ?? 0,\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await client.chat.completions\n\t\t\t\t.create(params, requestOptions)\n\t\t\t\t.withResponse();\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tinterface StreamingToolCallBlock extends ToolCall {\n\t\t\t\tpartialArgs?: string;\n\t\t\t\tpartialArgsComplete?: boolean;\n\t\t\t\tstreamIndex?: number;\n\t\t\t}\n\t\t\ttype StreamingBlock = TextContent | ThinkingContent | StreamingToolCallBlock;\n\t\t\ttype StreamingToolCallDelta = NonNullable<ChatCompletionChunk.Choice.Delta[\"tool_calls\"]>[number];\n\n\t\t\tlet textBlock: TextContent | null = null;\n\t\t\tlet thinkingBlock: ThinkingContent | null = null;\n\t\t\tlet hasFinishReason = false;\n\t\t\tconst toolCallBlocksByIndex = new Map<number, StreamingToolCallBlock>();\n\t\t\tconst toolCallBlocksById = new Map<string, StreamingToolCallBlock>();\n\t\t\tconst toolCallIdCounts = new Map<string, number>();\n\t\t\tconst usedToolCallIds = new Set<string>();\n\t\t\tlet syntheticToolCallOrdinal = 0;\n\t\t\tconst pendingReasoningDetailsById = new Map<string, string>();\n\t\t\tconst blocks = output.content as StreamingBlock[];\n\t\t\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\t\t\tconst getContentIndex = (block: StreamingBlock) => blocks.indexOf(block);\n\t\t\tconst finishBlock = (block: StreamingBlock) => {\n\t\t\t\tconst contentIndex = getContentIndex(block);\n\t\t\t\tif (contentIndex === -1) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t// Finalize in-place and strip the scratch buffers so replay only\n\t\t\t\t\t// carries parsed arguments.\n\t\t\t\t\tdelete block.partialArgs;\n\t\t\t\t\tdelete block.partialArgsComplete;\n\t\t\t\t\tdelete block.streamIndex;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\ttoolCall: block,\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\tconst ensureTextBlock = () => {\n\t\t\t\tif (!textBlock) {\n\t\t\t\t\ttextBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\tblocks.push(textBlock);\n\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: getContentIndex(textBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn textBlock;\n\t\t\t};\n\t\t\tconst ensureThinkingBlock = (thinkingSignature: string) => {\n\t\t\t\tif (!thinkingBlock) {\n\t\t\t\t\tthinkingBlock = {\n\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\tthinkingSignature,\n\t\t\t\t\t};\n\t\t\t\t\tblocks.push(thinkingBlock);\n\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: getContentIndex(thinkingBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn thinkingBlock;\n\t\t\t};\n\t\t\tconst attachPendingReasoningDetail = (block: StreamingToolCallBlock, id: string) => {\n\t\t\t\tconst pending = pendingReasoningDetailsById.get(id);\n\t\t\t\tif (pending !== undefined && !block.thoughtSignature) {\n\t\t\t\t\tblock.thoughtSignature = pending;\n\t\t\t\t\tpendingReasoningDetailsById.delete(id);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst allocateToolCallId = (rawId: string | undefined, streamIndex: number | undefined) => {\n\t\t\t\tconst fallbackOrdinal = streamIndex ?? syntheticToolCallOrdinal++;\n\t\t\t\tconst baseId = rawId && rawId.length > 0 ? rawId : `call_${fallbackOrdinal}`;\n\t\t\t\tlet count = toolCallIdCounts.get(baseId) ?? 0;\n\t\t\t\tlet candidate = count === 0 ? baseId : `${baseId}_${count + 1}`;\n\t\t\t\twhile (usedToolCallIds.has(candidate)) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tcandidate = `${baseId}_${count + 1}`;\n\t\t\t\t}\n\t\t\t\ttoolCallIdCounts.set(baseId, count + 1);\n\t\t\t\tusedToolCallIds.add(candidate);\n\t\t\t\treturn candidate;\n\t\t\t};\n\t\t\tconst ensureToolCallBlock = (toolCall: StreamingToolCallDelta) => {\n\t\t\t\tconst streamIndex = typeof toolCall.index === \"number\" ? toolCall.index : undefined;\n\t\t\t\tlet block = streamIndex !== undefined ? toolCallBlocksByIndex.get(streamIndex) : undefined;\n\t\t\t\tif (!block && streamIndex === undefined && toolCall.id) {\n\t\t\t\t\tblock = toolCallBlocksById.get(toolCall.id);\n\t\t\t\t}\n\t\t\t\tif (!block) {\n\t\t\t\t\tblock = {\n\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\tid: allocateToolCallId(toolCall.id, streamIndex),\n\t\t\t\t\t\tname: toolCall.function?.name ? toolNameMap.toOriginalName(toolCall.function.name) : \"\",\n\t\t\t\t\t\targuments: {},\n\t\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t\t\tpartialArgsComplete: true,\n\t\t\t\t\t\tstreamIndex,\n\t\t\t\t\t};\n\t\t\t\t\tif (streamIndex !== undefined) {\n\t\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t\t}\n\t\t\t\t\tif (toolCall.id && !toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_start\",\n\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (streamIndex !== undefined && block.streamIndex === undefined) {\n\t\t\t\t\tblock.streamIndex = streamIndex;\n\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t}\n\t\t\t\tif (toolCall.id) {\n\t\t\t\t\tif (!toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tattachPendingReasoningDetail(block, toolCall.id);\n\t\t\t\t}\n\t\t\t\treturn block;\n\t\t\t};\n\n\t\t\tfor await (const chunk of openaiStream) {\n\t\t\t\tif (!chunk || typeof chunk !== \"object\") continue;\n\n\t\t\t\t// OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,\n\t\t\t\t// and each chunk in a streamed completion carries the same id.\n\t\t\t\toutput.responseId ||= chunk.id;\n\t\t\t\tif (typeof chunk.model === \"string\" && chunk.model.length > 0 && chunk.model !== model.id) {\n\t\t\t\t\toutput.responseModel ||= chunk.model;\n\t\t\t\t}\n\t\t\t\tif (chunk.usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage(chunk.usage, model);\n\t\t\t\t}\n\n\t\t\t\tconst choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;\n\t\t\t\tif (!choice) continue;\n\n\t\t\t\t// Fallback: some providers (e.g., Moonshot) return usage\n\t\t\t\t// in choice.usage instead of the standard chunk.usage\n\t\t\t\tif (!chunk.usage && (choice as any).usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage((choice as any).usage, model);\n\t\t\t\t}\n\n\t\t\t\tif (choice.finish_reason) {\n\t\t\t\t\tconst finishReasonResult = mapStopReason(choice.finish_reason);\n\t\t\t\t\toutput.stopReason = finishReasonResult.stopReason;\n\t\t\t\t\tif (finishReasonResult.errorMessage) {\n\t\t\t\t\t\toutput.errorMessage = finishReasonResult.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\thasFinishReason = true;\n\t\t\t\t}\n\n\t\t\t\tif (choice.delta) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tchoice.delta.content !== null &&\n\t\t\t\t\t\tchoice.delta.content !== undefined &&\n\t\t\t\t\t\tchoice.delta.content.length > 0\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst block = ensureTextBlock();\n\t\t\t\t\t\tblock.text += choice.delta.content;\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\tdelta: choice.delta.content,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t// Some endpoints return reasoning in reasoning_content (llama.cpp),\n\t\t\t\t\t// or reasoning (other openai compatible endpoints)\n\t\t\t\t\t// Use the first non-empty reasoning field to avoid duplication\n\t\t\t\t\t// (e.g., chutes.ai returns both reasoning_content and reasoning with same content)\n\t\t\t\t\tconst reasoningFields = [\"reasoning_content\", \"reasoning\", \"reasoning_text\"];\n\t\t\t\t\tconst deltaFields = choice.delta as Record<string, unknown>;\n\t\t\t\t\tlet foundReasoningField: string | null = null;\n\t\t\t\t\tfor (const field of reasoningFields) {\n\t\t\t\t\t\tconst value = deltaFields[field];\n\t\t\t\t\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\t\t\t\t\tfoundReasoningField = field;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foundReasoningField) {\n\t\t\t\t\t\tconst delta = deltaFields[foundReasoningField];\n\t\t\t\t\t\tif (typeof delta === \"string\" && delta.length > 0) {\n\t\t\t\t\t\t\tconst thinkingSignature =\n\t\t\t\t\t\t\t\tmodel.provider === \"opencode-go\" && foundReasoningField === \"reasoning\"\n\t\t\t\t\t\t\t\t\t? \"reasoning_content\"\n\t\t\t\t\t\t\t\t\t: foundReasoningField;\n\t\t\t\t\t\t\tconst block = ensureThinkingBlock(thinkingSignature);\n\t\t\t\t\t\t\tblock.thinking += delta;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (choice?.delta?.tool_calls) {\n\t\t\t\t\t\tfor (const toolCall of choice.delta.tool_calls) {\n\t\t\t\t\t\t\tconst block = ensureToolCallBlock(toolCall);\n\t\t\t\t\t\t\tif (!block.name && toolCall.function?.name) {\n\t\t\t\t\t\t\t\tblock.name = toolNameMap.toOriginalName(toolCall.function.name);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlet delta = \"\";\n\t\t\t\t\t\t\tif (toolCall.function?.arguments) {\n\t\t\t\t\t\t\t\tdelta = toolCall.function.arguments;\n\t\t\t\t\t\t\t\tblock.partialArgs = (block.partialArgs ?? \"\") + toolCall.function.arguments;\n\t\t\t\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst reasoningDetails = (choice.delta as any).reasoning_details;\n\t\t\t\t\tif (reasoningDetails && Array.isArray(reasoningDetails)) {\n\t\t\t\t\t\tfor (const detail of reasoningDetails) {\n\t\t\t\t\t\t\tif (detail.type === \"reasoning.encrypted\" && detail.id && detail.data) {\n\t\t\t\t\t\t\t\tconst serialized = JSON.stringify(detail);\n\t\t\t\t\t\t\t\tconst matchingToolCall = toolCallBlocksById.get(detail.id);\n\t\t\t\t\t\t\t\tif (matchingToolCall) {\n\t\t\t\t\t\t\t\t\tmatchingToolCall.thoughtSignature = serialized;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tpendingReasoningDetailsById.set(detail.id, serialized);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (output.stopReason !== \"toolUse\") {\n\t\t\t\tfor (const block of blocks) {\n\t\t\t\t\tif (block.type === \"toolCall\" && block.partialArgs?.trim() && block.partialArgsComplete === false) {\n\t\t\t\t\t\tblock.errorMessage = `Tool call arguments were truncated before complete JSON was received (stop reason: ${output.stopReason}). Retry the tool call with complete JSON arguments.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const block of blocks) {\n\t\t\t\tfinishBlock(block);\n\t\t\t}\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 === \"aborted\") {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Provider returned an error stop reason\");\n\t\t\t}\n\t\t\tif (!hasFinishReason) {\n\t\t\t\tthrow new Error(\"Stream ended without finish_reason\");\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\tdelete (block as { index?: number }).index;\n\t\t\t\t// Streaming scratch buffers are only used during parsing; never persist them.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t\tdelete (block as { partialArgsComplete?: boolean }).partialArgsComplete;\n\t\t\t\tdelete (block as { streamIndex?: number }).streamIndex;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatOpenAICompletionsProviderError(error, model);\n\t\t\t// Some providers via OpenRouter give additional information in this field.\n\t\t\tconst rawMetadata = (error as any)?.error?.metadata?.raw;\n\t\t\tif (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) {\n\t\t\t\toutput.errorMessage += `\\n${rawMetadata}`;\n\t\t\t}\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\nexport const streamSimpleOpenAICompletions: StreamFunction<\"openai-completions\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst toolChoice = (options as OpenAICompletionsOptions | undefined)?.toolChoice;\n\n\treturn streamOpenAICompletions(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t\ttoolChoice,\n\t} satisfies OpenAICompletionsOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n) {\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId && compat.sendSessionAffinityHeaders) {\n\t\theaders.session_id = sessionId;\n\t\theaders[\"x-client-request-id\"] = sessionId;\n\t\theaders[\"x-session-affinity\"] = sessionId;\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\tconst defaultHeaders =\n\t\tmodel.provider === \"cloudflare-ai-gateway\"\n\t\t\t? {\n\t\t\t\t\t...headers,\n\t\t\t\t\tAuthorization: headers.Authorization ?? null,\n\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t}\n\t\t\t: headers;\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n\tcacheRetention: CacheRetention = resolveCacheRetention(options?.cacheRetention),\n) {\n\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\tconst messages = convertMessages(model, context, compat, toolNameMap);\n\tconst cacheControl = getCompatCacheControl(compat, cacheRetention);\n\n\tconst params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages,\n\t\tstream: true,\n\t\tprompt_cache_key:\n\t\t\t(model.baseUrl.includes(\"api.openai.com\") && cacheRetention !== \"none\") ||\n\t\t\t(cacheRetention === \"long\" && compat.supportsLongCacheRetention)\n\t\t\t\t? clampOpenAIPromptCacheKey(options?.sessionId)\n\t\t\t\t: undefined,\n\t\tprompt_cache_retention: cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined,\n\t};\n\n\tif (compat.supportsUsageInStreaming !== false) {\n\t\t(params as any).stream_options = { include_usage: true };\n\t}\n\n\tif (compat.supportsStore) {\n\t\tparams.store = false;\n\t}\n\n\tif (options?.maxTokens) {\n\t\tif (compat.maxTokensField === \"max_tokens\") {\n\t\t\t(params as any).max_tokens = options.maxTokens;\n\t\t} else {\n\t\t\tparams.max_completion_tokens = options.maxTokens;\n\t\t}\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\tparams.tools = convertTools(context.tools, compat, toolNameMap);\n\t\tif (compat.zaiToolStream) {\n\t\t\t(params as any).tool_stream = true;\n\t\t}\n\t} else if (hasToolHistory(context.messages)) {\n\t\t// Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results\n\t\tparams.tools = [];\n\t}\n\n\tif (cacheControl) {\n\t\tapplyAnthropicCacheControl(messages, params.tools, cacheControl);\n\t}\n\n\tif (options?.toolChoice) {\n\t\tparams.tool_choice =\n\t\t\ttypeof options.toolChoice === \"object\"\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: { name: toolNameMap.toProviderName(options.toolChoice.function.name) },\n\t\t\t\t\t}\n\t\t\t\t: options.toolChoice;\n\t}\n\n\tif (compat.thinkingFormat === \"zai\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen-chat-template\" && model.reasoning) {\n\t\t(params as any).chat_template_kwargs = {\n\t\t\tenable_thinking: !!options?.reasoningEffort,\n\t\t\tpreserve_thinking: true,\n\t\t};\n\t} else if (compat.thinkingFormat === \"deepseek\" && model.reasoning) {\n\t\t(params as any).thinking = { type: options?.reasoningEffort ? \"enabled\" : \"disabled\" };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\t(params as any).reasoning_effort =\n\t\t\t\tmodel.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"openrouter\" && model.reasoning) {\n\t\t// OpenRouter normalizes reasoning across providers via a nested reasoning object.\n\t\tconst openRouterParams = params as typeof params & { reasoning?: { effort?: string } };\n\t\tif (options?.reasoningEffort) {\n\t\t\topenRouterParams.reasoning = {\n\t\t\t\teffort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort,\n\t\t\t};\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\topenRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? \"none\" };\n\t\t}\n\t} else if (compat.thinkingFormat === \"together\" && model.reasoning) {\n\t\tconst togetherParams = params as Omit<typeof params, \"reasoning_effort\"> & {\n\t\t\treasoning?: { enabled: boolean };\n\t\t\treasoning_effort?: string;\n\t\t};\n\t\ttogetherParams.reasoning = { enabled: !!options?.reasoningEffort };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\ttogetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"string-thinking\" && model.reasoning) {\n\t\tconst stringThinkingParams = params as typeof params & { thinking?: string };\n\t\tif (options?.reasoningEffort) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.off ?? \"none\";\n\t\t}\n\t} else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\t// OpenAI-style reasoning_effort\n\t\t(params as any).reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t} else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\tconst offValue = model.thinkingLevelMap?.off;\n\t\tif (typeof offValue === \"string\") {\n\t\t\t(params as any).reasoning_effort = offValue;\n\t\t}\n\t}\n\n\t// OpenRouter provider routing preferences\n\tif (model.compat?.openRouterRouting) {\n\t\t(params as any).provider = model.compat.openRouterRouting;\n\t}\n\n\t// Vercel AI Gateway provider routing preferences\n\tif (model.baseUrl.includes(\"ai-gateway.vercel.sh\") && model.compat?.vercelGatewayRouting) {\n\t\tconst routing = model.compat.vercelGatewayRouting;\n\t\tif (routing.only || routing.order) {\n\t\t\tconst gatewayOptions: Record<string, string[]> = {};\n\t\t\tif (routing.only) gatewayOptions.only = routing.only;\n\t\t\tif (routing.order) gatewayOptions.order = routing.order;\n\t\t\t(params as any).providerOptions = { gateway: gatewayOptions };\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction getCompatCacheControl(\n\tcompat: ResolvedOpenAICompletionsCompat,\n\tcacheRetention: CacheRetention,\n): OpenAICompatCacheControl | undefined {\n\tif (compat.cacheControlFormat !== \"anthropic\" || cacheRetention === \"none\") {\n\t\treturn undefined;\n\t}\n\n\tconst ttl = cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"1h\" : undefined;\n\treturn { type: \"ephemeral\", ...(ttl ? { ttl } : {}) };\n}\n\nfunction applyAnthropicCacheControl(\n\tmessages: ChatCompletionMessageParam[],\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\taddCacheControlToSystemPrompt(messages, cacheControl);\n\taddCacheControlToLastTool(tools, cacheControl);\n\taddCacheControlToLastConversationMessage(messages, cacheControl);\n}\n\nfunction addCacheControlToSystemPrompt(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (const message of messages) {\n\t\tif (message.role === \"system\" || message.role === \"developer\") {\n\t\t\taddCacheControlToInstructionMessage(message, cacheControl);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastConversationMessage(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\t\tif (addCacheControlToMessage(message, cacheControl)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastTool(\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tif (!tools || tools.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastTool = tools[tools.length - 1] as ChatCompletionToolWithCacheControl;\n\tlastTool.cache_control = cacheControl;\n}\n\nfunction addCacheControlToInstructionMessage(\n\tmessage: ChatCompletionInstructionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\treturn addCacheControlToTextContent(message, cacheControl);\n}\n\nfunction addCacheControlToMessage(\n\tmessage: ChatCompletionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\treturn addCacheControlToTextContent(message, cacheControl);\n\t}\n\treturn false;\n}\n\nfunction addCacheControlToTextContent(\n\tmessage:\n\t\t| ChatCompletionInstructionMessageParam\n\t\t| ChatCompletionAssistantMessageParam\n\t\t| Extract<ChatCompletionMessageParam, { role: \"user\" }>,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\tif (content.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tmessage.content = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: content,\n\t\t\t\tcache_control: cacheControl,\n\t\t\t},\n\t\t] as ChatCompletionTextPartWithCacheControl[];\n\t\treturn true;\n\t}\n\n\tif (!Array.isArray(content)) {\n\t\treturn false;\n\t}\n\n\tfor (let i = content.length - 1; i >= 0; i--) {\n\t\tconst part = content[i];\n\t\tif (part?.type === \"text\") {\n\t\t\tconst textPart = part as ChatCompletionTextPartWithCacheControl;\n\t\t\ttextPart.cache_control = cacheControl;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nexport function convertMessages(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(context.tools ?? []),\n): ChatCompletionMessageParam[] {\n\tconst params: ChatCompletionMessageParam[] = [];\n\n\tconst normalizeToolCallId = (id: string): string => {\n\t\t// Handle pipe-separated IDs from OpenAI Responses API\n\t\t// Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)\n\t\t// These come from providers like github-copilot, openai-codex, opencode\n\t\t// Extract just the call_id part and normalize it\n\t\tif (id.includes(\"|\")) {\n\t\t\tconst [callId] = id.split(\"|\");\n\t\t\t// Sanitize to allowed chars and truncate to 40 chars (OpenAI limit)\n\t\t\treturn callId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 40);\n\t\t}\n\n\t\tif (model.provider === \"openai\") return id.length > 40 ? id.slice(0, 40) : id;\n\t\treturn id;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId(id));\n\n\tif (context.systemPrompt) {\n\t\tconst useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n\t\tconst role = useDeveloperRole ? \"developer\" : \"system\";\n\t\tparams.push({ role: role, content: sanitizeSurrogates(context.systemPrompt) });\n\t}\n\n\tlet lastRole: string | null = null;\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\t\t// Some providers don't allow user messages directly after tool results\n\t\t// Insert a synthetic assistant message to bridge the gap\n\t\tif (compat.requiresAssistantAfterToolResult && lastRole === \"toolResult\" && msg.role === \"user\") {\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t});\n\t\t}\n\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: sanitizeSurrogates(msg.content),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ChatCompletionContentPart[] = msg.content.map((item): ChatCompletionContentPart => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartText;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\turl: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartImage;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\t// Some providers don't accept null content, use empty string instead\n\t\t\tconst assistantMsg: ChatCompletionAssistantMessageParam = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: compat.requiresAssistantAfterToolResult ? \"\" : null,\n\t\t\t};\n\n\t\t\tconst assistantTextParts = msg.content\n\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t.filter((block) => block.text.trim().length > 0)\n\t\t\t\t.map(\n\t\t\t\t\t(block) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t\t}) satisfies ChatCompletionContentPartText,\n\t\t\t\t);\n\t\t\tconst assistantText = assistantTextParts.map((part) => part.text).join(\"\");\n\n\t\t\tconst nonEmptyThinkingBlocks = msg.content\n\t\t\t\t.filter(isThinkingContentBlock)\n\t\t\t\t.filter((block) => block.thinking.trim().length > 0);\n\t\t\tif (nonEmptyThinkingBlocks.length > 0) {\n\t\t\t\tif (compat.requiresThinkingAsText) {\n\t\t\t\t\t// Convert thinking blocks to plain text (no tags to avoid model mimicking them)\n\t\t\t\t\tconst thinkingText = nonEmptyThinkingBlocks\n\t\t\t\t\t\t.map((block) => sanitizeSurrogates(block.thinking))\n\t\t\t\t\t\t.join(\"\\n\\n\");\n\t\t\t\t\tassistantMsg.content = [{ type: \"text\", text: thinkingText }, ...assistantTextParts];\n\t\t\t\t} else {\n\t\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\t\tif (assistantText.length > 0) {\n\t\t\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss)\n\t\t\t\t\tlet signature = nonEmptyThinkingBlocks[0].thinkingSignature;\n\t\t\t\t\tif (model.provider === \"opencode-go\" && signature === \"reasoning\") {\n\t\t\t\t\t\tsignature = \"reasoning_content\";\n\t\t\t\t\t}\n\t\t\t\t\tif (signature && signature.length > 0) {\n\t\t\t\t\t\t(assistantMsg as any)[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (assistantText.length > 0) {\n\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t}\n\n\t\t\tconst toolCalls = msg.content.filter(isToolCallBlock);\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tassistantMsg.tool_calls = toolCalls.map((tc) => ({\n\t\t\t\t\tid: tc.id,\n\t\t\t\t\ttype: \"function\" as const,\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: toolNameMap.toProviderName(tc.name),\n\t\t\t\t\t\targuments: JSON.stringify(tc.arguments),\n\t\t\t\t\t},\n\t\t\t\t}));\n\t\t\t\tconst reasoningDetails = toolCalls\n\t\t\t\t\t.filter((tc) => tc.thoughtSignature)\n\t\t\t\t\t.map((tc) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn JSON.parse(tc.thoughtSignature!);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.filter(Boolean);\n\t\t\t\tif (reasoningDetails.length > 0) {\n\t\t\t\t\t(assistantMsg as any).reasoning_details = reasoningDetails;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcompat.requiresReasoningContentOnAssistantMessages &&\n\t\t\t\tmodel.reasoning &&\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content === undefined\n\t\t\t) {\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content = \"\";\n\t\t\t}\n\t\t\t// Skip assistant messages that have no content and no tool calls.\n\t\t\t// Some providers require \"either content or tool_calls, but not none\".\n\t\t\t// Other providers also don't accept empty assistant messages.\n\t\t\t// This handles aborted assistant responses that got no content.\n\t\t\tconst content = assistantMsg.content;\n\t\t\tconst hasContent =\n\t\t\t\tcontent !== null &&\n\t\t\t\tcontent !== undefined &&\n\t\t\t\t(typeof content === \"string\" ? content.length > 0 : content.length > 0);\n\t\t\tif (!hasContent && !assistantMsg.tool_calls) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparams.push(assistantMsg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst imageBlocks: Array<{ type: \"image_url\"; image_url: { url: string } }> = [];\n\t\t\tlet j = i;\n\n\t\t\tfor (; j < transformedMessages.length && transformedMessages[j].role === \"toolResult\"; j++) {\n\t\t\t\tconst toolMsg = transformedMessages[j] as ToolResultMessage;\n\n\t\t\t\t// Extract text and image content\n\t\t\t\tconst textResult = toolMsg.content\n\t\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t\t.map((block) => block.text)\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tconst hasImages = toolMsg.content.some((c) => c.type === \"image\");\n\n\t\t\t\t// Always send tool result with text (or placeholder if only images)\n\t\t\t\tconst hasText = textResult.length > 0;\n\t\t\t\t// Some providers require the 'name' field in tool results\n\t\t\t\tconst toolResultMsg: ChatCompletionToolMessageParam = {\n\t\t\t\t\trole: \"tool\",\n\t\t\t\t\tcontent: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n\t\t\t\t\ttool_call_id: toolMsg.toolCallId,\n\t\t\t\t};\n\t\t\t\tif (compat.requiresToolResultName && toolMsg.toolName) {\n\t\t\t\t\t(toolResultMsg as any).name = toolMsg.toolName;\n\t\t\t\t}\n\t\t\t\tparams.push(toolResultMsg);\n\n\t\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\t\tfor (const block of toolMsg.content) {\n\t\t\t\t\t\tif (isImageContentBlock(block)) {\n\t\t\t\t\t\t\timageBlocks.push({\n\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\t\turl: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ti = j - 1;\n\n\t\t\tif (imageBlocks.length > 0) {\n\t\t\t\tif (compat.requiresAssistantAfterToolResult) {\n\t\t\t\t\tparams.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Attached image(s) from tool result:\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...imageBlocks,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tlastRole = \"user\";\n\t\t\t} else {\n\t\t\t\tlastRole = \"toolResult\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tlastRole = msg.role;\n\t}\n\n\treturn params;\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(tools),\n): OpenAI.Chat.Completions.ChatCompletionTool[] {\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: toolNameMap.toProviderName(tool.name),\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\t\t// Only include strict if provider supports it. Some reject unknown fields.\n\t\t\t...(compat.supportsStrictMode !== false && { strict: false }),\n\t\t},\n\t}));\n}\n\nfunction parseChunkUsage(\n\trawUsage: {\n\t\tprompt_tokens?: number;\n\t\tcompletion_tokens?: number;\n\t\tprompt_cache_hit_tokens?: number;\n\t\tprompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\t\tcost?: number;\n\t},\n\tmodel: Model<\"openai-completions\">,\n): AssistantMessage[\"usage\"] {\n\tconst promptTokens = rawUsage.prompt_tokens || 0;\n\tconst cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;\n\tconst cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n\n\t// Follow documented OpenAI/OpenRouter semantics: cached_tokens is cache-read\n\t// tokens (hits). OpenAI does not document or emit cache_write_tokens, but\n\t// OpenRouter-compatible providers can include it as a separate write count.\n\t// OpenRouter's own provider/tests affirm the separate mapping:\n\t// https://github.com/OpenRouterTeam/ai-sdk-provider/pull/409\n\t// Do not subtract writes from cached_tokens, otherwise spec-compliant\n\t// providers are under-reported. DS4 mirrors this contract too:\n\t// https://github.com/antirez/ds4/pull/29\n\tconst input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n\t// OpenAI completion_tokens already includes reasoning_tokens.\n\tconst outputTokens = rawUsage.completion_tokens || 0;\n\tconst usage: AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput: outputTokens,\n\t\tcacheRead: cacheReadTokens,\n\t\tcacheWrite: cacheWriteTokens,\n\t\ttotalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: rawUsage.cost || 0 },\n\t};\n\tcalculateCost(model, usage, { providerSuppliedTotal: Boolean(rawUsage.cost) });\n\treturn usage;\n}\n\nfunction mapStopReason(reason: ChatCompletionChunk.Choice[\"finish_reason\"] | string): {\n\tstopReason: StopReason;\n\terrorMessage?: string;\n} {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\tcase \"end\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"function_call\":\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"content_filter\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: content_filter\" };\n\t\tcase \"network_error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: network_error\" };\n\t\tdefault:\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: `Provider finish_reason: ${reason}`,\n\t\t\t};\n\t}\n}\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai = provider === \"zai\" || baseUrl.includes(\"api.z.ai\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\n\tconst isNonStandard =\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tbaseUrl.includes(\"deepseek.com\") ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway;\n\n\tconst useMaxTokens = baseUrl.includes(\"chutes.ai\") || isMoonshot || isCloudflareAiGateway || isTogether;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n\tconst cacheControlFormat = provider === \"openrouter\" && model.id.startsWith(\"anthropic/\") ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: !isNonStandard && !isOpenRouter,\n\t\tsupportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tsupportsUsageInStreaming: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: false,\n\t\tsupportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Uses explicit model.compat if provided, otherwise auto-detects from provider/URL.\n */\nfunction getCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? {},\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n"]}
@@ -50,6 +50,27 @@ function isToolCallBlock(block) {
50
50
  function isImageContentBlock(block) {
51
51
  return block.type === "image";
52
52
  }
53
+ function isOllamaModel(model) {
54
+ return model.provider === "ollama" || model.baseUrl.includes(":11434");
55
+ }
56
+ function isOllamaContextSizeError(model, normalized, formatted) {
57
+ if (!isOllamaModel(model))
58
+ return false;
59
+ const text = `${normalized.message}\n${normalized.body ?? ""}\n${formatted}`.toLowerCase();
60
+ return (text.includes("exceed_context_size_error") ||
61
+ text.includes("prompt too long") ||
62
+ (text.includes("context") && text.includes("exceed")));
63
+ }
64
+ export function formatOpenAICompletionsProviderError(error, model) {
65
+ const normalized = normalizeProviderError(error);
66
+ const formatted = formatProviderError(normalized);
67
+ if (!isOllamaContextSizeError(model, normalized, formatted))
68
+ return formatted;
69
+ return (`${formatted}\n` +
70
+ `Ollama context action for ${model.provider}/${model.id}: Ollama rejected this request because it exceeds the model's served context window. ` +
71
+ `Raise the Ollama serving context with OLLAMA_CONTEXT_LENGTH or a per-model num_ctx value, then retry. ` +
72
+ `Do not lower pi's models.json contextWindow to mask this backend limit.`);
73
+ }
53
74
  function resolveCacheRetention(cacheRetention) {
54
75
  if (cacheRetention) {
55
76
  return cacheRetention;
@@ -375,7 +396,7 @@ export const streamOpenAICompletions = (model, context, options) => {
375
396
  delete block.streamIndex;
376
397
  }
377
398
  output.stopReason = options?.signal?.aborted ? "aborted" : "error";
378
- output.errorMessage = formatProviderError(normalizeProviderError(error));
399
+ output.errorMessage = formatOpenAICompletionsProviderError(error, model);
379
400
  // Some providers via OpenRouter give additional information in this field.
380
401
  const rawMetadata = error?.error?.metadata?.raw;
381
402
  if (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) {
@@ -1 +1 @@
1
- {"version":3,"file":"openai-completions.js","sourceRoot":"","sources":["../../src/providers/openai-completions.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAY5B,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAmBjE,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAoB,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AACjF,OAAO,EAAE,0BAA0B,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAChG,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAA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AK,CAAC,MAAM,CAAC,oBAAoB,IAAI,QAAQ,CAAC,oBAAoB;QACxF,aAAa,EAAE,KAAK,CAAC,MAAM,CAAC,aAAa,IAAI,QAAQ,CAAC,aAAa;QACnE,kBAAkB,EAAE,KAAK,CAAC,MAAM,CAAC,kBAAkB,IAAI,QAAQ,CAAC,kBAAkB;QAClF,kBAAkB,EAAE,KAAK,CAAC,MAAM,CAAC,kBAAkB,IAAI,QAAQ,CAAC,kBAAkB;QAClF,0BAA0B,EAAE,KAAK,CAAC,MAAM,CAAC,0BAA0B,IAAI,QAAQ,CAAC,0BAA0B;QAC1G,0BAA0B,EAAE,KAAK,CAAC,MAAM,CAAC,0BAA0B,IAAI,QAAQ,CAAC,0BAA0B;KAC1G,CAAC;AAAA,CACF","sourcesContent":["import OpenAI from \"openai\";\nimport type {\n\tChatCompletionAssistantMessageParam,\n\tChatCompletionChunk,\n\tChatCompletionContentPart,\n\tChatCompletionContentPartImage,\n\tChatCompletionContentPartText,\n\tChatCompletionDeveloperMessageParam,\n\tChatCompletionMessageParam,\n\tChatCompletionSystemMessageParam,\n\tChatCompletionToolMessageParam,\n} from \"openai/resources/chat/completions.js\";\nimport { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tOpenAICompletionsCompat,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJsonState } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createToolNameMap, type ToolNameMap } from \"../utils/tool-names.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Check if conversation messages contain tool calls or tool results.\n * This is needed because Anthropic (via proxy) requires the tools param\n * to be present when messages include tool_calls or tool role messages.\n */\nfunction hasToolHistory(messages: Message[]): boolean {\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn true;\n\t\t}\n\t\tif (msg.role === \"assistant\") {\n\t\t\tif (msg.content.some((block) => block.type === \"toolCall\")) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction getOpenAICompletionsApiKey(model: Model<\"openai-completions\">, apiKey: string | undefined): string {\n\tif (apiKey) {\n\t\treturn apiKey;\n\t}\n\tif (model.provider === \"llama-cpp\") {\n\t\treturn \"sk-no-key\";\n\t}\n\tthrow new Error(`No API key for provider: ${model.provider}`);\n}\n\nfunction isTextContentBlock(block: { type: string }): block is TextContent {\n\treturn block.type === \"text\";\n}\n\nfunction isThinkingContentBlock(block: { type: string }): block is ThinkingContent {\n\treturn block.type === \"thinking\";\n}\n\nfunction isToolCallBlock(block: { type: string }): block is ToolCall {\n\treturn block.type === \"toolCall\";\n}\n\nfunction isImageContentBlock(block: { type: string }): block is ImageContent {\n\treturn block.type === \"image\";\n}\n\nexport interface OpenAICompletionsOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"required\" | { type: \"function\"; function: { name: string } };\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n}\n\ninterface OpenAICompatCacheControl {\n\ttype: \"ephemeral\";\n\tttl?: string;\n}\n\ntype ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, \"cacheControlFormat\"> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n};\n\ntype ChatCompletionInstructionMessageParam = ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam;\n\ntype ChatCompletionTextPartWithCacheControl = ChatCompletionContentPartText & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\ntype ChatCompletionToolWithCacheControl = OpenAI.Chat.Completions.ChatCompletionTool & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport const streamOpenAICompletions: StreamFunction<\"openai-completions\", OpenAICompletionsOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\t\t\tconst compat = getCompat(model);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);\n\t\t\tlet params = buildParams(model, context, options, compat, cacheRetention);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: options?.maxRetries ?? 0,\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await client.chat.completions\n\t\t\t\t.create(params, requestOptions)\n\t\t\t\t.withResponse();\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tinterface StreamingToolCallBlock extends ToolCall {\n\t\t\t\tpartialArgs?: string;\n\t\t\t\tpartialArgsComplete?: boolean;\n\t\t\t\tstreamIndex?: number;\n\t\t\t}\n\t\t\ttype StreamingBlock = TextContent | ThinkingContent | StreamingToolCallBlock;\n\t\t\ttype StreamingToolCallDelta = NonNullable<ChatCompletionChunk.Choice.Delta[\"tool_calls\"]>[number];\n\n\t\t\tlet textBlock: TextContent | null = null;\n\t\t\tlet thinkingBlock: ThinkingContent | null = null;\n\t\t\tlet hasFinishReason = false;\n\t\t\tconst toolCallBlocksByIndex = new Map<number, StreamingToolCallBlock>();\n\t\t\tconst toolCallBlocksById = new Map<string, StreamingToolCallBlock>();\n\t\t\tconst toolCallIdCounts = new Map<string, number>();\n\t\t\tconst usedToolCallIds = new Set<string>();\n\t\t\tlet syntheticToolCallOrdinal = 0;\n\t\t\tconst pendingReasoningDetailsById = new Map<string, string>();\n\t\t\tconst blocks = output.content as StreamingBlock[];\n\t\t\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\t\t\tconst getContentIndex = (block: StreamingBlock) => blocks.indexOf(block);\n\t\t\tconst finishBlock = (block: StreamingBlock) => {\n\t\t\t\tconst contentIndex = getContentIndex(block);\n\t\t\t\tif (contentIndex === -1) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t// Finalize in-place and strip the scratch buffers so replay only\n\t\t\t\t\t// carries parsed arguments.\n\t\t\t\t\tdelete block.partialArgs;\n\t\t\t\t\tdelete block.partialArgsComplete;\n\t\t\t\t\tdelete block.streamIndex;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\ttoolCall: block,\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\tconst ensureTextBlock = () => {\n\t\t\t\tif (!textBlock) {\n\t\t\t\t\ttextBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\tblocks.push(textBlock);\n\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: getContentIndex(textBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn textBlock;\n\t\t\t};\n\t\t\tconst ensureThinkingBlock = (thinkingSignature: string) => {\n\t\t\t\tif (!thinkingBlock) {\n\t\t\t\t\tthinkingBlock = {\n\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\tthinkingSignature,\n\t\t\t\t\t};\n\t\t\t\t\tblocks.push(thinkingBlock);\n\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: getContentIndex(thinkingBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn thinkingBlock;\n\t\t\t};\n\t\t\tconst attachPendingReasoningDetail = (block: StreamingToolCallBlock, id: string) => {\n\t\t\t\tconst pending = pendingReasoningDetailsById.get(id);\n\t\t\t\tif (pending !== undefined && !block.thoughtSignature) {\n\t\t\t\t\tblock.thoughtSignature = pending;\n\t\t\t\t\tpendingReasoningDetailsById.delete(id);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst allocateToolCallId = (rawId: string | undefined, streamIndex: number | undefined) => {\n\t\t\t\tconst fallbackOrdinal = streamIndex ?? syntheticToolCallOrdinal++;\n\t\t\t\tconst baseId = rawId && rawId.length > 0 ? rawId : `call_${fallbackOrdinal}`;\n\t\t\t\tlet count = toolCallIdCounts.get(baseId) ?? 0;\n\t\t\t\tlet candidate = count === 0 ? baseId : `${baseId}_${count + 1}`;\n\t\t\t\twhile (usedToolCallIds.has(candidate)) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tcandidate = `${baseId}_${count + 1}`;\n\t\t\t\t}\n\t\t\t\ttoolCallIdCounts.set(baseId, count + 1);\n\t\t\t\tusedToolCallIds.add(candidate);\n\t\t\t\treturn candidate;\n\t\t\t};\n\t\t\tconst ensureToolCallBlock = (toolCall: StreamingToolCallDelta) => {\n\t\t\t\tconst streamIndex = typeof toolCall.index === \"number\" ? toolCall.index : undefined;\n\t\t\t\tlet block = streamIndex !== undefined ? toolCallBlocksByIndex.get(streamIndex) : undefined;\n\t\t\t\tif (!block && streamIndex === undefined && toolCall.id) {\n\t\t\t\t\tblock = toolCallBlocksById.get(toolCall.id);\n\t\t\t\t}\n\t\t\t\tif (!block) {\n\t\t\t\t\tblock = {\n\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\tid: allocateToolCallId(toolCall.id, streamIndex),\n\t\t\t\t\t\tname: toolCall.function?.name ? toolNameMap.toOriginalName(toolCall.function.name) : \"\",\n\t\t\t\t\t\targuments: {},\n\t\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t\t\tpartialArgsComplete: true,\n\t\t\t\t\t\tstreamIndex,\n\t\t\t\t\t};\n\t\t\t\t\tif (streamIndex !== undefined) {\n\t\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t\t}\n\t\t\t\t\tif (toolCall.id && !toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_start\",\n\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (streamIndex !== undefined && block.streamIndex === undefined) {\n\t\t\t\t\tblock.streamIndex = streamIndex;\n\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t}\n\t\t\t\tif (toolCall.id) {\n\t\t\t\t\tif (!toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tattachPendingReasoningDetail(block, toolCall.id);\n\t\t\t\t}\n\t\t\t\treturn block;\n\t\t\t};\n\n\t\t\tfor await (const chunk of openaiStream) {\n\t\t\t\tif (!chunk || typeof chunk !== \"object\") continue;\n\n\t\t\t\t// OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,\n\t\t\t\t// and each chunk in a streamed completion carries the same id.\n\t\t\t\toutput.responseId ||= chunk.id;\n\t\t\t\tif (typeof chunk.model === \"string\" && chunk.model.length > 0 && chunk.model !== model.id) {\n\t\t\t\t\toutput.responseModel ||= chunk.model;\n\t\t\t\t}\n\t\t\t\tif (chunk.usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage(chunk.usage, model);\n\t\t\t\t}\n\n\t\t\t\tconst choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;\n\t\t\t\tif (!choice) continue;\n\n\t\t\t\t// Fallback: some providers (e.g., Moonshot) return usage\n\t\t\t\t// in choice.usage instead of the standard chunk.usage\n\t\t\t\tif (!chunk.usage && (choice as any).usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage((choice as any).usage, model);\n\t\t\t\t}\n\n\t\t\t\tif (choice.finish_reason) {\n\t\t\t\t\tconst finishReasonResult = mapStopReason(choice.finish_reason);\n\t\t\t\t\toutput.stopReason = finishReasonResult.stopReason;\n\t\t\t\t\tif (finishReasonResult.errorMessage) {\n\t\t\t\t\t\toutput.errorMessage = finishReasonResult.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\thasFinishReason = true;\n\t\t\t\t}\n\n\t\t\t\tif (choice.delta) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tchoice.delta.content !== null &&\n\t\t\t\t\t\tchoice.delta.content !== undefined &&\n\t\t\t\t\t\tchoice.delta.content.length > 0\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst block = ensureTextBlock();\n\t\t\t\t\t\tblock.text += choice.delta.content;\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\tdelta: choice.delta.content,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t// Some endpoints return reasoning in reasoning_content (llama.cpp),\n\t\t\t\t\t// or reasoning (other openai compatible endpoints)\n\t\t\t\t\t// Use the first non-empty reasoning field to avoid duplication\n\t\t\t\t\t// (e.g., chutes.ai returns both reasoning_content and reasoning with same content)\n\t\t\t\t\tconst reasoningFields = [\"reasoning_content\", \"reasoning\", \"reasoning_text\"];\n\t\t\t\t\tconst deltaFields = choice.delta as Record<string, unknown>;\n\t\t\t\t\tlet foundReasoningField: string | null = null;\n\t\t\t\t\tfor (const field of reasoningFields) {\n\t\t\t\t\t\tconst value = deltaFields[field];\n\t\t\t\t\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\t\t\t\t\tfoundReasoningField = field;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foundReasoningField) {\n\t\t\t\t\t\tconst delta = deltaFields[foundReasoningField];\n\t\t\t\t\t\tif (typeof delta === \"string\" && delta.length > 0) {\n\t\t\t\t\t\t\tconst thinkingSignature =\n\t\t\t\t\t\t\t\tmodel.provider === \"opencode-go\" && foundReasoningField === \"reasoning\"\n\t\t\t\t\t\t\t\t\t? \"reasoning_content\"\n\t\t\t\t\t\t\t\t\t: foundReasoningField;\n\t\t\t\t\t\t\tconst block = ensureThinkingBlock(thinkingSignature);\n\t\t\t\t\t\t\tblock.thinking += delta;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (choice?.delta?.tool_calls) {\n\t\t\t\t\t\tfor (const toolCall of choice.delta.tool_calls) {\n\t\t\t\t\t\t\tconst block = ensureToolCallBlock(toolCall);\n\t\t\t\t\t\t\tif (!block.name && toolCall.function?.name) {\n\t\t\t\t\t\t\t\tblock.name = toolNameMap.toOriginalName(toolCall.function.name);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlet delta = \"\";\n\t\t\t\t\t\t\tif (toolCall.function?.arguments) {\n\t\t\t\t\t\t\t\tdelta = toolCall.function.arguments;\n\t\t\t\t\t\t\t\tblock.partialArgs = (block.partialArgs ?? \"\") + toolCall.function.arguments;\n\t\t\t\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst reasoningDetails = (choice.delta as any).reasoning_details;\n\t\t\t\t\tif (reasoningDetails && Array.isArray(reasoningDetails)) {\n\t\t\t\t\t\tfor (const detail of reasoningDetails) {\n\t\t\t\t\t\t\tif (detail.type === \"reasoning.encrypted\" && detail.id && detail.data) {\n\t\t\t\t\t\t\t\tconst serialized = JSON.stringify(detail);\n\t\t\t\t\t\t\t\tconst matchingToolCall = toolCallBlocksById.get(detail.id);\n\t\t\t\t\t\t\t\tif (matchingToolCall) {\n\t\t\t\t\t\t\t\t\tmatchingToolCall.thoughtSignature = serialized;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tpendingReasoningDetailsById.set(detail.id, serialized);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (output.stopReason !== \"toolUse\") {\n\t\t\t\tfor (const block of blocks) {\n\t\t\t\t\tif (block.type === \"toolCall\" && block.partialArgs?.trim() && block.partialArgsComplete === false) {\n\t\t\t\t\t\tblock.errorMessage = `Tool call arguments were truncated before complete JSON was received (stop reason: ${output.stopReason}). Retry the tool call with complete JSON arguments.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const block of blocks) {\n\t\t\t\tfinishBlock(block);\n\t\t\t}\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 === \"aborted\") {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Provider returned an error stop reason\");\n\t\t\t}\n\t\t\tif (!hasFinishReason) {\n\t\t\t\tthrow new Error(\"Stream ended without finish_reason\");\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\tdelete (block as { index?: number }).index;\n\t\t\t\t// Streaming scratch buffers are only used during parsing; never persist them.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t\tdelete (block as { partialArgsComplete?: boolean }).partialArgsComplete;\n\t\t\t\tdelete (block as { streamIndex?: number }).streamIndex;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\t\t// Some providers via OpenRouter give additional information in this field.\n\t\t\tconst rawMetadata = (error as any)?.error?.metadata?.raw;\n\t\t\tif (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) {\n\t\t\t\toutput.errorMessage += `\\n${rawMetadata}`;\n\t\t\t}\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\nexport const streamSimpleOpenAICompletions: StreamFunction<\"openai-completions\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst toolChoice = (options as OpenAICompletionsOptions | undefined)?.toolChoice;\n\n\treturn streamOpenAICompletions(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t\ttoolChoice,\n\t} satisfies OpenAICompletionsOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n) {\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId && compat.sendSessionAffinityHeaders) {\n\t\theaders.session_id = sessionId;\n\t\theaders[\"x-client-request-id\"] = sessionId;\n\t\theaders[\"x-session-affinity\"] = sessionId;\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\tconst defaultHeaders =\n\t\tmodel.provider === \"cloudflare-ai-gateway\"\n\t\t\t? {\n\t\t\t\t\t...headers,\n\t\t\t\t\tAuthorization: headers.Authorization ?? null,\n\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t}\n\t\t\t: headers;\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n\tcacheRetention: CacheRetention = resolveCacheRetention(options?.cacheRetention),\n) {\n\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\tconst messages = convertMessages(model, context, compat, toolNameMap);\n\tconst cacheControl = getCompatCacheControl(compat, cacheRetention);\n\n\tconst params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages,\n\t\tstream: true,\n\t\tprompt_cache_key:\n\t\t\t(model.baseUrl.includes(\"api.openai.com\") && cacheRetention !== \"none\") ||\n\t\t\t(cacheRetention === \"long\" && compat.supportsLongCacheRetention)\n\t\t\t\t? clampOpenAIPromptCacheKey(options?.sessionId)\n\t\t\t\t: undefined,\n\t\tprompt_cache_retention: cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined,\n\t};\n\n\tif (compat.supportsUsageInStreaming !== false) {\n\t\t(params as any).stream_options = { include_usage: true };\n\t}\n\n\tif (compat.supportsStore) {\n\t\tparams.store = false;\n\t}\n\n\tif (options?.maxTokens) {\n\t\tif (compat.maxTokensField === \"max_tokens\") {\n\t\t\t(params as any).max_tokens = options.maxTokens;\n\t\t} else {\n\t\t\tparams.max_completion_tokens = options.maxTokens;\n\t\t}\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\tparams.tools = convertTools(context.tools, compat, toolNameMap);\n\t\tif (compat.zaiToolStream) {\n\t\t\t(params as any).tool_stream = true;\n\t\t}\n\t} else if (hasToolHistory(context.messages)) {\n\t\t// Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results\n\t\tparams.tools = [];\n\t}\n\n\tif (cacheControl) {\n\t\tapplyAnthropicCacheControl(messages, params.tools, cacheControl);\n\t}\n\n\tif (options?.toolChoice) {\n\t\tparams.tool_choice =\n\t\t\ttypeof options.toolChoice === \"object\"\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: { name: toolNameMap.toProviderName(options.toolChoice.function.name) },\n\t\t\t\t\t}\n\t\t\t\t: options.toolChoice;\n\t}\n\n\tif (compat.thinkingFormat === \"zai\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen-chat-template\" && model.reasoning) {\n\t\t(params as any).chat_template_kwargs = {\n\t\t\tenable_thinking: !!options?.reasoningEffort,\n\t\t\tpreserve_thinking: true,\n\t\t};\n\t} else if (compat.thinkingFormat === \"deepseek\" && model.reasoning) {\n\t\t(params as any).thinking = { type: options?.reasoningEffort ? \"enabled\" : \"disabled\" };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\t(params as any).reasoning_effort =\n\t\t\t\tmodel.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"openrouter\" && model.reasoning) {\n\t\t// OpenRouter normalizes reasoning across providers via a nested reasoning object.\n\t\tconst openRouterParams = params as typeof params & { reasoning?: { effort?: string } };\n\t\tif (options?.reasoningEffort) {\n\t\t\topenRouterParams.reasoning = {\n\t\t\t\teffort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort,\n\t\t\t};\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\topenRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? \"none\" };\n\t\t}\n\t} else if (compat.thinkingFormat === \"together\" && model.reasoning) {\n\t\tconst togetherParams = params as Omit<typeof params, \"reasoning_effort\"> & {\n\t\t\treasoning?: { enabled: boolean };\n\t\t\treasoning_effort?: string;\n\t\t};\n\t\ttogetherParams.reasoning = { enabled: !!options?.reasoningEffort };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\ttogetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"string-thinking\" && model.reasoning) {\n\t\tconst stringThinkingParams = params as typeof params & { thinking?: string };\n\t\tif (options?.reasoningEffort) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.off ?? \"none\";\n\t\t}\n\t} else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\t// OpenAI-style reasoning_effort\n\t\t(params as any).reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t} else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\tconst offValue = model.thinkingLevelMap?.off;\n\t\tif (typeof offValue === \"string\") {\n\t\t\t(params as any).reasoning_effort = offValue;\n\t\t}\n\t}\n\n\t// OpenRouter provider routing preferences\n\tif (model.compat?.openRouterRouting) {\n\t\t(params as any).provider = model.compat.openRouterRouting;\n\t}\n\n\t// Vercel AI Gateway provider routing preferences\n\tif (model.baseUrl.includes(\"ai-gateway.vercel.sh\") && model.compat?.vercelGatewayRouting) {\n\t\tconst routing = model.compat.vercelGatewayRouting;\n\t\tif (routing.only || routing.order) {\n\t\t\tconst gatewayOptions: Record<string, string[]> = {};\n\t\t\tif (routing.only) gatewayOptions.only = routing.only;\n\t\t\tif (routing.order) gatewayOptions.order = routing.order;\n\t\t\t(params as any).providerOptions = { gateway: gatewayOptions };\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction getCompatCacheControl(\n\tcompat: ResolvedOpenAICompletionsCompat,\n\tcacheRetention: CacheRetention,\n): OpenAICompatCacheControl | undefined {\n\tif (compat.cacheControlFormat !== \"anthropic\" || cacheRetention === \"none\") {\n\t\treturn undefined;\n\t}\n\n\tconst ttl = cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"1h\" : undefined;\n\treturn { type: \"ephemeral\", ...(ttl ? { ttl } : {}) };\n}\n\nfunction applyAnthropicCacheControl(\n\tmessages: ChatCompletionMessageParam[],\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\taddCacheControlToSystemPrompt(messages, cacheControl);\n\taddCacheControlToLastTool(tools, cacheControl);\n\taddCacheControlToLastConversationMessage(messages, cacheControl);\n}\n\nfunction addCacheControlToSystemPrompt(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (const message of messages) {\n\t\tif (message.role === \"system\" || message.role === \"developer\") {\n\t\t\taddCacheControlToInstructionMessage(message, cacheControl);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastConversationMessage(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\t\tif (addCacheControlToMessage(message, cacheControl)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastTool(\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tif (!tools || tools.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastTool = tools[tools.length - 1] as ChatCompletionToolWithCacheControl;\n\tlastTool.cache_control = cacheControl;\n}\n\nfunction addCacheControlToInstructionMessage(\n\tmessage: ChatCompletionInstructionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\treturn addCacheControlToTextContent(message, cacheControl);\n}\n\nfunction addCacheControlToMessage(\n\tmessage: ChatCompletionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\treturn addCacheControlToTextContent(message, cacheControl);\n\t}\n\treturn false;\n}\n\nfunction addCacheControlToTextContent(\n\tmessage:\n\t\t| ChatCompletionInstructionMessageParam\n\t\t| ChatCompletionAssistantMessageParam\n\t\t| Extract<ChatCompletionMessageParam, { role: \"user\" }>,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\tif (content.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tmessage.content = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: content,\n\t\t\t\tcache_control: cacheControl,\n\t\t\t},\n\t\t] as ChatCompletionTextPartWithCacheControl[];\n\t\treturn true;\n\t}\n\n\tif (!Array.isArray(content)) {\n\t\treturn false;\n\t}\n\n\tfor (let i = content.length - 1; i >= 0; i--) {\n\t\tconst part = content[i];\n\t\tif (part?.type === \"text\") {\n\t\t\tconst textPart = part as ChatCompletionTextPartWithCacheControl;\n\t\t\ttextPart.cache_control = cacheControl;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nexport function convertMessages(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(context.tools ?? []),\n): ChatCompletionMessageParam[] {\n\tconst params: ChatCompletionMessageParam[] = [];\n\n\tconst normalizeToolCallId = (id: string): string => {\n\t\t// Handle pipe-separated IDs from OpenAI Responses API\n\t\t// Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)\n\t\t// These come from providers like github-copilot, openai-codex, opencode\n\t\t// Extract just the call_id part and normalize it\n\t\tif (id.includes(\"|\")) {\n\t\t\tconst [callId] = id.split(\"|\");\n\t\t\t// Sanitize to allowed chars and truncate to 40 chars (OpenAI limit)\n\t\t\treturn callId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 40);\n\t\t}\n\n\t\tif (model.provider === \"openai\") return id.length > 40 ? id.slice(0, 40) : id;\n\t\treturn id;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId(id));\n\n\tif (context.systemPrompt) {\n\t\tconst useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n\t\tconst role = useDeveloperRole ? \"developer\" : \"system\";\n\t\tparams.push({ role: role, content: sanitizeSurrogates(context.systemPrompt) });\n\t}\n\n\tlet lastRole: string | null = null;\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\t\t// Some providers don't allow user messages directly after tool results\n\t\t// Insert a synthetic assistant message to bridge the gap\n\t\tif (compat.requiresAssistantAfterToolResult && lastRole === \"toolResult\" && msg.role === \"user\") {\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t});\n\t\t}\n\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: sanitizeSurrogates(msg.content),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ChatCompletionContentPart[] = msg.content.map((item): ChatCompletionContentPart => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartText;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\turl: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartImage;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\t// Some providers don't accept null content, use empty string instead\n\t\t\tconst assistantMsg: ChatCompletionAssistantMessageParam = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: compat.requiresAssistantAfterToolResult ? \"\" : null,\n\t\t\t};\n\n\t\t\tconst assistantTextParts = msg.content\n\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t.filter((block) => block.text.trim().length > 0)\n\t\t\t\t.map(\n\t\t\t\t\t(block) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t\t}) satisfies ChatCompletionContentPartText,\n\t\t\t\t);\n\t\t\tconst assistantText = assistantTextParts.map((part) => part.text).join(\"\");\n\n\t\t\tconst nonEmptyThinkingBlocks = msg.content\n\t\t\t\t.filter(isThinkingContentBlock)\n\t\t\t\t.filter((block) => block.thinking.trim().length > 0);\n\t\t\tif (nonEmptyThinkingBlocks.length > 0) {\n\t\t\t\tif (compat.requiresThinkingAsText) {\n\t\t\t\t\t// Convert thinking blocks to plain text (no tags to avoid model mimicking them)\n\t\t\t\t\tconst thinkingText = nonEmptyThinkingBlocks\n\t\t\t\t\t\t.map((block) => sanitizeSurrogates(block.thinking))\n\t\t\t\t\t\t.join(\"\\n\\n\");\n\t\t\t\t\tassistantMsg.content = [{ type: \"text\", text: thinkingText }, ...assistantTextParts];\n\t\t\t\t} else {\n\t\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\t\tif (assistantText.length > 0) {\n\t\t\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss)\n\t\t\t\t\tlet signature = nonEmptyThinkingBlocks[0].thinkingSignature;\n\t\t\t\t\tif (model.provider === \"opencode-go\" && signature === \"reasoning\") {\n\t\t\t\t\t\tsignature = \"reasoning_content\";\n\t\t\t\t\t}\n\t\t\t\t\tif (signature && signature.length > 0) {\n\t\t\t\t\t\t(assistantMsg as any)[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (assistantText.length > 0) {\n\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t}\n\n\t\t\tconst toolCalls = msg.content.filter(isToolCallBlock);\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tassistantMsg.tool_calls = toolCalls.map((tc) => ({\n\t\t\t\t\tid: tc.id,\n\t\t\t\t\ttype: \"function\" as const,\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: toolNameMap.toProviderName(tc.name),\n\t\t\t\t\t\targuments: JSON.stringify(tc.arguments),\n\t\t\t\t\t},\n\t\t\t\t}));\n\t\t\t\tconst reasoningDetails = toolCalls\n\t\t\t\t\t.filter((tc) => tc.thoughtSignature)\n\t\t\t\t\t.map((tc) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn JSON.parse(tc.thoughtSignature!);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.filter(Boolean);\n\t\t\t\tif (reasoningDetails.length > 0) {\n\t\t\t\t\t(assistantMsg as any).reasoning_details = reasoningDetails;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcompat.requiresReasoningContentOnAssistantMessages &&\n\t\t\t\tmodel.reasoning &&\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content === undefined\n\t\t\t) {\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content = \"\";\n\t\t\t}\n\t\t\t// Skip assistant messages that have no content and no tool calls.\n\t\t\t// Some providers require \"either content or tool_calls, but not none\".\n\t\t\t// Other providers also don't accept empty assistant messages.\n\t\t\t// This handles aborted assistant responses that got no content.\n\t\t\tconst content = assistantMsg.content;\n\t\t\tconst hasContent =\n\t\t\t\tcontent !== null &&\n\t\t\t\tcontent !== undefined &&\n\t\t\t\t(typeof content === \"string\" ? content.length > 0 : content.length > 0);\n\t\t\tif (!hasContent && !assistantMsg.tool_calls) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparams.push(assistantMsg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst imageBlocks: Array<{ type: \"image_url\"; image_url: { url: string } }> = [];\n\t\t\tlet j = i;\n\n\t\t\tfor (; j < transformedMessages.length && transformedMessages[j].role === \"toolResult\"; j++) {\n\t\t\t\tconst toolMsg = transformedMessages[j] as ToolResultMessage;\n\n\t\t\t\t// Extract text and image content\n\t\t\t\tconst textResult = toolMsg.content\n\t\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t\t.map((block) => block.text)\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tconst hasImages = toolMsg.content.some((c) => c.type === \"image\");\n\n\t\t\t\t// Always send tool result with text (or placeholder if only images)\n\t\t\t\tconst hasText = textResult.length > 0;\n\t\t\t\t// Some providers require the 'name' field in tool results\n\t\t\t\tconst toolResultMsg: ChatCompletionToolMessageParam = {\n\t\t\t\t\trole: \"tool\",\n\t\t\t\t\tcontent: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n\t\t\t\t\ttool_call_id: toolMsg.toolCallId,\n\t\t\t\t};\n\t\t\t\tif (compat.requiresToolResultName && toolMsg.toolName) {\n\t\t\t\t\t(toolResultMsg as any).name = toolMsg.toolName;\n\t\t\t\t}\n\t\t\t\tparams.push(toolResultMsg);\n\n\t\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\t\tfor (const block of toolMsg.content) {\n\t\t\t\t\t\tif (isImageContentBlock(block)) {\n\t\t\t\t\t\t\timageBlocks.push({\n\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\t\turl: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ti = j - 1;\n\n\t\t\tif (imageBlocks.length > 0) {\n\t\t\t\tif (compat.requiresAssistantAfterToolResult) {\n\t\t\t\t\tparams.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Attached image(s) from tool result:\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...imageBlocks,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tlastRole = \"user\";\n\t\t\t} else {\n\t\t\t\tlastRole = \"toolResult\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tlastRole = msg.role;\n\t}\n\n\treturn params;\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(tools),\n): OpenAI.Chat.Completions.ChatCompletionTool[] {\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: toolNameMap.toProviderName(tool.name),\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\t\t// Only include strict if provider supports it. Some reject unknown fields.\n\t\t\t...(compat.supportsStrictMode !== false && { strict: false }),\n\t\t},\n\t}));\n}\n\nfunction parseChunkUsage(\n\trawUsage: {\n\t\tprompt_tokens?: number;\n\t\tcompletion_tokens?: number;\n\t\tprompt_cache_hit_tokens?: number;\n\t\tprompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\t\tcost?: number;\n\t},\n\tmodel: Model<\"openai-completions\">,\n): AssistantMessage[\"usage\"] {\n\tconst promptTokens = rawUsage.prompt_tokens || 0;\n\tconst cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;\n\tconst cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n\n\t// Follow documented OpenAI/OpenRouter semantics: cached_tokens is cache-read\n\t// tokens (hits). OpenAI does not document or emit cache_write_tokens, but\n\t// OpenRouter-compatible providers can include it as a separate write count.\n\t// OpenRouter's own provider/tests affirm the separate mapping:\n\t// https://github.com/OpenRouterTeam/ai-sdk-provider/pull/409\n\t// Do not subtract writes from cached_tokens, otherwise spec-compliant\n\t// providers are under-reported. DS4 mirrors this contract too:\n\t// https://github.com/antirez/ds4/pull/29\n\tconst input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n\t// OpenAI completion_tokens already includes reasoning_tokens.\n\tconst outputTokens = rawUsage.completion_tokens || 0;\n\tconst usage: AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput: outputTokens,\n\t\tcacheRead: cacheReadTokens,\n\t\tcacheWrite: cacheWriteTokens,\n\t\ttotalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: rawUsage.cost || 0 },\n\t};\n\tcalculateCost(model, usage, { providerSuppliedTotal: Boolean(rawUsage.cost) });\n\treturn usage;\n}\n\nfunction mapStopReason(reason: ChatCompletionChunk.Choice[\"finish_reason\"] | string): {\n\tstopReason: StopReason;\n\terrorMessage?: string;\n} {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\tcase \"end\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"function_call\":\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"content_filter\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: content_filter\" };\n\t\tcase \"network_error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: network_error\" };\n\t\tdefault:\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: `Provider finish_reason: ${reason}`,\n\t\t\t};\n\t}\n}\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai = provider === \"zai\" || baseUrl.includes(\"api.z.ai\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\n\tconst isNonStandard =\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tbaseUrl.includes(\"deepseek.com\") ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway;\n\n\tconst useMaxTokens = baseUrl.includes(\"chutes.ai\") || isMoonshot || isCloudflareAiGateway || isTogether;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n\tconst cacheControlFormat = provider === \"openrouter\" && model.id.startsWith(\"anthropic/\") ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: !isNonStandard && !isOpenRouter,\n\t\tsupportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tsupportsUsageInStreaming: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: false,\n\t\tsupportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Uses explicit model.compat if provided, otherwise auto-detects from provider/URL.\n */\nfunction getCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? {},\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n"]}
1
+ {"version":3,"file":"openai-completions.js","sourceRoot":"","sources":["../../src/providers/openai-completions.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAY5B,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAmBjE,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAoB,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AACjF,OAAO,EAAE,0BAA0B,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAChG,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D;;;;GAIG;AACH,SAAS,cAAc,CAAC,QAAmB,EAAW;IACrD,KAAK,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC5B,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YAC/B,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,MAAM,CAAC,0BAA0B,IAAI,QAAQ,CAAC,0BAA0B;KAC1G,CAAC;AAAA,CACF","sourcesContent":["import OpenAI from \"openai\";\nimport type {\n\tChatCompletionAssistantMessageParam,\n\tChatCompletionChunk,\n\tChatCompletionContentPart,\n\tChatCompletionContentPartImage,\n\tChatCompletionContentPartText,\n\tChatCompletionDeveloperMessageParam,\n\tChatCompletionMessageParam,\n\tChatCompletionSystemMessageParam,\n\tChatCompletionToolMessageParam,\n} from \"openai/resources/chat/completions.js\";\nimport { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tOpenAICompletionsCompat,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJsonState } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createToolNameMap, type ToolNameMap } from \"../utils/tool-names.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Check if conversation messages contain tool calls or tool results.\n * This is needed because Anthropic (via proxy) requires the tools param\n * to be present when messages include tool_calls or tool role messages.\n */\nfunction hasToolHistory(messages: Message[]): boolean {\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn true;\n\t\t}\n\t\tif (msg.role === \"assistant\") {\n\t\t\tif (msg.content.some((block) => block.type === \"toolCall\")) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction getOpenAICompletionsApiKey(model: Model<\"openai-completions\">, apiKey: string | undefined): string {\n\tif (apiKey) {\n\t\treturn apiKey;\n\t}\n\tif (model.provider === \"llama-cpp\") {\n\t\treturn \"sk-no-key\";\n\t}\n\tthrow new Error(`No API key for provider: ${model.provider}`);\n}\n\nfunction isTextContentBlock(block: { type: string }): block is TextContent {\n\treturn block.type === \"text\";\n}\n\nfunction isThinkingContentBlock(block: { type: string }): block is ThinkingContent {\n\treturn block.type === \"thinking\";\n}\n\nfunction isToolCallBlock(block: { type: string }): block is ToolCall {\n\treturn block.type === \"toolCall\";\n}\n\nfunction isImageContentBlock(block: { type: string }): block is ImageContent {\n\treturn block.type === \"image\";\n}\n\nfunction isOllamaModel(model: Model<\"openai-completions\">): boolean {\n\treturn model.provider === \"ollama\" || model.baseUrl.includes(\":11434\");\n}\n\nfunction isOllamaContextSizeError(\n\tmodel: Model<\"openai-completions\">,\n\tnormalized: ReturnType<typeof normalizeProviderError>,\n\tformatted: string,\n): boolean {\n\tif (!isOllamaModel(model)) return false;\n\tconst text = `${normalized.message}\\n${normalized.body ?? \"\"}\\n${formatted}`.toLowerCase();\n\treturn (\n\t\ttext.includes(\"exceed_context_size_error\") ||\n\t\ttext.includes(\"prompt too long\") ||\n\t\t(text.includes(\"context\") && text.includes(\"exceed\"))\n\t);\n}\n\nexport function formatOpenAICompletionsProviderError(error: unknown, model: Model<\"openai-completions\">): string {\n\tconst normalized = normalizeProviderError(error);\n\tconst formatted = formatProviderError(normalized);\n\tif (!isOllamaContextSizeError(model, normalized, formatted)) return formatted;\n\treturn (\n\t\t`${formatted}\\n` +\n\t\t`Ollama context action for ${model.provider}/${model.id}: Ollama rejected this request because it exceeds the model's served context window. ` +\n\t\t`Raise the Ollama serving context with OLLAMA_CONTEXT_LENGTH or a per-model num_ctx value, then retry. ` +\n\t\t`Do not lower pi's models.json contextWindow to mask this backend limit.`\n\t);\n}\n\nexport interface OpenAICompletionsOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"required\" | { type: \"function\"; function: { name: string } };\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n}\n\ninterface OpenAICompatCacheControl {\n\ttype: \"ephemeral\";\n\tttl?: string;\n}\n\ntype ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, \"cacheControlFormat\"> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n};\n\ntype ChatCompletionInstructionMessageParam = ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam;\n\ntype ChatCompletionTextPartWithCacheControl = ChatCompletionContentPartText & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\ntype ChatCompletionToolWithCacheControl = OpenAI.Chat.Completions.ChatCompletionTool & {\n\tcache_control?: OpenAICompatCacheControl;\n};\n\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport const streamOpenAICompletions: StreamFunction<\"openai-completions\", OpenAICompletionsOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\t\t\tconst compat = getCompat(model);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);\n\t\t\tlet params = buildParams(model, context, options, compat, cacheRetention);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: options?.maxRetries ?? 0,\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await client.chat.completions\n\t\t\t\t.create(params, requestOptions)\n\t\t\t\t.withResponse();\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tinterface StreamingToolCallBlock extends ToolCall {\n\t\t\t\tpartialArgs?: string;\n\t\t\t\tpartialArgsComplete?: boolean;\n\t\t\t\tstreamIndex?: number;\n\t\t\t}\n\t\t\ttype StreamingBlock = TextContent | ThinkingContent | StreamingToolCallBlock;\n\t\t\ttype StreamingToolCallDelta = NonNullable<ChatCompletionChunk.Choice.Delta[\"tool_calls\"]>[number];\n\n\t\t\tlet textBlock: TextContent | null = null;\n\t\t\tlet thinkingBlock: ThinkingContent | null = null;\n\t\t\tlet hasFinishReason = false;\n\t\t\tconst toolCallBlocksByIndex = new Map<number, StreamingToolCallBlock>();\n\t\t\tconst toolCallBlocksById = new Map<string, StreamingToolCallBlock>();\n\t\t\tconst toolCallIdCounts = new Map<string, number>();\n\t\t\tconst usedToolCallIds = new Set<string>();\n\t\t\tlet syntheticToolCallOrdinal = 0;\n\t\t\tconst pendingReasoningDetailsById = new Map<string, string>();\n\t\t\tconst blocks = output.content as StreamingBlock[];\n\t\t\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\t\t\tconst getContentIndex = (block: StreamingBlock) => blocks.indexOf(block);\n\t\t\tconst finishBlock = (block: StreamingBlock) => {\n\t\t\t\tconst contentIndex = getContentIndex(block);\n\t\t\t\tif (contentIndex === -1) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t// Finalize in-place and strip the scratch buffers so replay only\n\t\t\t\t\t// carries parsed arguments.\n\t\t\t\t\tdelete block.partialArgs;\n\t\t\t\t\tdelete block.partialArgsComplete;\n\t\t\t\t\tdelete block.streamIndex;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\ttoolCall: block,\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\tconst ensureTextBlock = () => {\n\t\t\t\tif (!textBlock) {\n\t\t\t\t\ttextBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\tblocks.push(textBlock);\n\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: getContentIndex(textBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn textBlock;\n\t\t\t};\n\t\t\tconst ensureThinkingBlock = (thinkingSignature: string) => {\n\t\t\t\tif (!thinkingBlock) {\n\t\t\t\t\tthinkingBlock = {\n\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\tthinkingSignature,\n\t\t\t\t\t};\n\t\t\t\t\tblocks.push(thinkingBlock);\n\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: getContentIndex(thinkingBlock), partial: output });\n\t\t\t\t}\n\t\t\t\treturn thinkingBlock;\n\t\t\t};\n\t\t\tconst attachPendingReasoningDetail = (block: StreamingToolCallBlock, id: string) => {\n\t\t\t\tconst pending = pendingReasoningDetailsById.get(id);\n\t\t\t\tif (pending !== undefined && !block.thoughtSignature) {\n\t\t\t\t\tblock.thoughtSignature = pending;\n\t\t\t\t\tpendingReasoningDetailsById.delete(id);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst allocateToolCallId = (rawId: string | undefined, streamIndex: number | undefined) => {\n\t\t\t\tconst fallbackOrdinal = streamIndex ?? syntheticToolCallOrdinal++;\n\t\t\t\tconst baseId = rawId && rawId.length > 0 ? rawId : `call_${fallbackOrdinal}`;\n\t\t\t\tlet count = toolCallIdCounts.get(baseId) ?? 0;\n\t\t\t\tlet candidate = count === 0 ? baseId : `${baseId}_${count + 1}`;\n\t\t\t\twhile (usedToolCallIds.has(candidate)) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tcandidate = `${baseId}_${count + 1}`;\n\t\t\t\t}\n\t\t\t\ttoolCallIdCounts.set(baseId, count + 1);\n\t\t\t\tusedToolCallIds.add(candidate);\n\t\t\t\treturn candidate;\n\t\t\t};\n\t\t\tconst ensureToolCallBlock = (toolCall: StreamingToolCallDelta) => {\n\t\t\t\tconst streamIndex = typeof toolCall.index === \"number\" ? toolCall.index : undefined;\n\t\t\t\tlet block = streamIndex !== undefined ? toolCallBlocksByIndex.get(streamIndex) : undefined;\n\t\t\t\tif (!block && streamIndex === undefined && toolCall.id) {\n\t\t\t\t\tblock = toolCallBlocksById.get(toolCall.id);\n\t\t\t\t}\n\t\t\t\tif (!block) {\n\t\t\t\t\tblock = {\n\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\tid: allocateToolCallId(toolCall.id, streamIndex),\n\t\t\t\t\t\tname: toolCall.function?.name ? toolNameMap.toOriginalName(toolCall.function.name) : \"\",\n\t\t\t\t\t\targuments: {},\n\t\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t\t\tpartialArgsComplete: true,\n\t\t\t\t\t\tstreamIndex,\n\t\t\t\t\t};\n\t\t\t\t\tif (streamIndex !== undefined) {\n\t\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t\t}\n\t\t\t\t\tif (toolCall.id && !toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_start\",\n\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (streamIndex !== undefined && block.streamIndex === undefined) {\n\t\t\t\t\tblock.streamIndex = streamIndex;\n\t\t\t\t\ttoolCallBlocksByIndex.set(streamIndex, block);\n\t\t\t\t}\n\t\t\t\tif (toolCall.id) {\n\t\t\t\t\tif (!toolCallBlocksById.has(toolCall.id)) {\n\t\t\t\t\t\ttoolCallBlocksById.set(toolCall.id, block);\n\t\t\t\t\t}\n\t\t\t\t\tattachPendingReasoningDetail(block, toolCall.id);\n\t\t\t\t}\n\t\t\t\treturn block;\n\t\t\t};\n\n\t\t\tfor await (const chunk of openaiStream) {\n\t\t\t\tif (!chunk || typeof chunk !== \"object\") continue;\n\n\t\t\t\t// OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,\n\t\t\t\t// and each chunk in a streamed completion carries the same id.\n\t\t\t\toutput.responseId ||= chunk.id;\n\t\t\t\tif (typeof chunk.model === \"string\" && chunk.model.length > 0 && chunk.model !== model.id) {\n\t\t\t\t\toutput.responseModel ||= chunk.model;\n\t\t\t\t}\n\t\t\t\tif (chunk.usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage(chunk.usage, model);\n\t\t\t\t}\n\n\t\t\t\tconst choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;\n\t\t\t\tif (!choice) continue;\n\n\t\t\t\t// Fallback: some providers (e.g., Moonshot) return usage\n\t\t\t\t// in choice.usage instead of the standard chunk.usage\n\t\t\t\tif (!chunk.usage && (choice as any).usage) {\n\t\t\t\t\toutput.usage = parseChunkUsage((choice as any).usage, model);\n\t\t\t\t}\n\n\t\t\t\tif (choice.finish_reason) {\n\t\t\t\t\tconst finishReasonResult = mapStopReason(choice.finish_reason);\n\t\t\t\t\toutput.stopReason = finishReasonResult.stopReason;\n\t\t\t\t\tif (finishReasonResult.errorMessage) {\n\t\t\t\t\t\toutput.errorMessage = finishReasonResult.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\thasFinishReason = true;\n\t\t\t\t}\n\n\t\t\t\tif (choice.delta) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tchoice.delta.content !== null &&\n\t\t\t\t\t\tchoice.delta.content !== undefined &&\n\t\t\t\t\t\tchoice.delta.content.length > 0\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst block = ensureTextBlock();\n\t\t\t\t\t\tblock.text += choice.delta.content;\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\tdelta: choice.delta.content,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t// Some endpoints return reasoning in reasoning_content (llama.cpp),\n\t\t\t\t\t// or reasoning (other openai compatible endpoints)\n\t\t\t\t\t// Use the first non-empty reasoning field to avoid duplication\n\t\t\t\t\t// (e.g., chutes.ai returns both reasoning_content and reasoning with same content)\n\t\t\t\t\tconst reasoningFields = [\"reasoning_content\", \"reasoning\", \"reasoning_text\"];\n\t\t\t\t\tconst deltaFields = choice.delta as Record<string, unknown>;\n\t\t\t\t\tlet foundReasoningField: string | null = null;\n\t\t\t\t\tfor (const field of reasoningFields) {\n\t\t\t\t\t\tconst value = deltaFields[field];\n\t\t\t\t\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\t\t\t\t\tfoundReasoningField = field;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foundReasoningField) {\n\t\t\t\t\t\tconst delta = deltaFields[foundReasoningField];\n\t\t\t\t\t\tif (typeof delta === \"string\" && delta.length > 0) {\n\t\t\t\t\t\t\tconst thinkingSignature =\n\t\t\t\t\t\t\t\tmodel.provider === \"opencode-go\" && foundReasoningField === \"reasoning\"\n\t\t\t\t\t\t\t\t\t? \"reasoning_content\"\n\t\t\t\t\t\t\t\t\t: foundReasoningField;\n\t\t\t\t\t\t\tconst block = ensureThinkingBlock(thinkingSignature);\n\t\t\t\t\t\t\tblock.thinking += delta;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (choice?.delta?.tool_calls) {\n\t\t\t\t\t\tfor (const toolCall of choice.delta.tool_calls) {\n\t\t\t\t\t\t\tconst block = ensureToolCallBlock(toolCall);\n\t\t\t\t\t\t\tif (!block.name && toolCall.function?.name) {\n\t\t\t\t\t\t\t\tblock.name = toolNameMap.toOriginalName(toolCall.function.name);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlet delta = \"\";\n\t\t\t\t\t\t\tif (toolCall.function?.arguments) {\n\t\t\t\t\t\t\t\tdelta = toolCall.function.arguments;\n\t\t\t\t\t\t\t\tblock.partialArgs = (block.partialArgs ?? \"\") + toolCall.function.arguments;\n\t\t\t\t\t\t\t\tconst parseResult = parseStreamingJsonState(block.partialArgs);\n\t\t\t\t\t\t\t\tblock.arguments = parseResult.value;\n\t\t\t\t\t\t\t\tblock.partialArgsComplete = parseResult.complete;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: getContentIndex(block),\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst reasoningDetails = (choice.delta as any).reasoning_details;\n\t\t\t\t\tif (reasoningDetails && Array.isArray(reasoningDetails)) {\n\t\t\t\t\t\tfor (const detail of reasoningDetails) {\n\t\t\t\t\t\t\tif (detail.type === \"reasoning.encrypted\" && detail.id && detail.data) {\n\t\t\t\t\t\t\t\tconst serialized = JSON.stringify(detail);\n\t\t\t\t\t\t\t\tconst matchingToolCall = toolCallBlocksById.get(detail.id);\n\t\t\t\t\t\t\t\tif (matchingToolCall) {\n\t\t\t\t\t\t\t\t\tmatchingToolCall.thoughtSignature = serialized;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tpendingReasoningDetailsById.set(detail.id, serialized);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (output.stopReason !== \"toolUse\") {\n\t\t\t\tfor (const block of blocks) {\n\t\t\t\t\tif (block.type === \"toolCall\" && block.partialArgs?.trim() && block.partialArgsComplete === false) {\n\t\t\t\t\t\tblock.errorMessage = `Tool call arguments were truncated before complete JSON was received (stop reason: ${output.stopReason}). Retry the tool call with complete JSON arguments.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const block of blocks) {\n\t\t\t\tfinishBlock(block);\n\t\t\t}\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 === \"aborted\") {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Provider returned an error stop reason\");\n\t\t\t}\n\t\t\tif (!hasFinishReason) {\n\t\t\t\tthrow new Error(\"Stream ended without finish_reason\");\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\tdelete (block as { index?: number }).index;\n\t\t\t\t// Streaming scratch buffers are only used during parsing; never persist them.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t\tdelete (block as { partialArgsComplete?: boolean }).partialArgsComplete;\n\t\t\t\tdelete (block as { streamIndex?: number }).streamIndex;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatOpenAICompletionsProviderError(error, model);\n\t\t\t// Some providers via OpenRouter give additional information in this field.\n\t\t\tconst rawMetadata = (error as any)?.error?.metadata?.raw;\n\t\t\tif (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) {\n\t\t\t\toutput.errorMessage += `\\n${rawMetadata}`;\n\t\t\t}\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\nexport const streamSimpleOpenAICompletions: StreamFunction<\"openai-completions\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = getOpenAICompletionsApiKey(model, options?.apiKey);\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst toolChoice = (options as OpenAICompletionsOptions | undefined)?.toolChoice;\n\n\treturn streamOpenAICompletions(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t\ttoolChoice,\n\t} satisfies OpenAICompletionsOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n) {\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId && compat.sendSessionAffinityHeaders) {\n\t\theaders.session_id = sessionId;\n\t\theaders[\"x-client-request-id\"] = sessionId;\n\t\theaders[\"x-session-affinity\"] = sessionId;\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\tconst defaultHeaders =\n\t\tmodel.provider === \"cloudflare-ai-gateway\"\n\t\t\t? {\n\t\t\t\t\t...headers,\n\t\t\t\t\tAuthorization: headers.Authorization ?? null,\n\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t}\n\t\t\t: headers;\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\toptions?: OpenAICompletionsOptions,\n\tcompat: ResolvedOpenAICompletionsCompat = getCompat(model),\n\tcacheRetention: CacheRetention = resolveCacheRetention(options?.cacheRetention),\n) {\n\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\tconst messages = convertMessages(model, context, compat, toolNameMap);\n\tconst cacheControl = getCompatCacheControl(compat, cacheRetention);\n\n\tconst params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages,\n\t\tstream: true,\n\t\tprompt_cache_key:\n\t\t\t(model.baseUrl.includes(\"api.openai.com\") && cacheRetention !== \"none\") ||\n\t\t\t(cacheRetention === \"long\" && compat.supportsLongCacheRetention)\n\t\t\t\t? clampOpenAIPromptCacheKey(options?.sessionId)\n\t\t\t\t: undefined,\n\t\tprompt_cache_retention: cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined,\n\t};\n\n\tif (compat.supportsUsageInStreaming !== false) {\n\t\t(params as any).stream_options = { include_usage: true };\n\t}\n\n\tif (compat.supportsStore) {\n\t\tparams.store = false;\n\t}\n\n\tif (options?.maxTokens) {\n\t\tif (compat.maxTokensField === \"max_tokens\") {\n\t\t\t(params as any).max_tokens = options.maxTokens;\n\t\t} else {\n\t\t\tparams.max_completion_tokens = options.maxTokens;\n\t\t}\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\tparams.tools = convertTools(context.tools, compat, toolNameMap);\n\t\tif (compat.zaiToolStream) {\n\t\t\t(params as any).tool_stream = true;\n\t\t}\n\t} else if (hasToolHistory(context.messages)) {\n\t\t// Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results\n\t\tparams.tools = [];\n\t}\n\n\tif (cacheControl) {\n\t\tapplyAnthropicCacheControl(messages, params.tools, cacheControl);\n\t}\n\n\tif (options?.toolChoice) {\n\t\tparams.tool_choice =\n\t\t\ttypeof options.toolChoice === \"object\"\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: { name: toolNameMap.toProviderName(options.toolChoice.function.name) },\n\t\t\t\t\t}\n\t\t\t\t: options.toolChoice;\n\t}\n\n\tif (compat.thinkingFormat === \"zai\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen\" && model.reasoning) {\n\t\t(params as any).enable_thinking = !!options?.reasoningEffort;\n\t} else if (compat.thinkingFormat === \"qwen-chat-template\" && model.reasoning) {\n\t\t(params as any).chat_template_kwargs = {\n\t\t\tenable_thinking: !!options?.reasoningEffort,\n\t\t\tpreserve_thinking: true,\n\t\t};\n\t} else if (compat.thinkingFormat === \"deepseek\" && model.reasoning) {\n\t\t(params as any).thinking = { type: options?.reasoningEffort ? \"enabled\" : \"disabled\" };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\t(params as any).reasoning_effort =\n\t\t\t\tmodel.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"openrouter\" && model.reasoning) {\n\t\t// OpenRouter normalizes reasoning across providers via a nested reasoning object.\n\t\tconst openRouterParams = params as typeof params & { reasoning?: { effort?: string } };\n\t\tif (options?.reasoningEffort) {\n\t\t\topenRouterParams.reasoning = {\n\t\t\t\teffort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort,\n\t\t\t};\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\topenRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? \"none\" };\n\t\t}\n\t} else if (compat.thinkingFormat === \"together\" && model.reasoning) {\n\t\tconst togetherParams = params as Omit<typeof params, \"reasoning_effort\"> & {\n\t\t\treasoning?: { enabled: boolean };\n\t\t\treasoning_effort?: string;\n\t\t};\n\t\ttogetherParams.reasoning = { enabled: !!options?.reasoningEffort };\n\t\tif (options?.reasoningEffort && compat.supportsReasoningEffort) {\n\t\t\ttogetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t}\n\t} else if (compat.thinkingFormat === \"string-thinking\" && model.reasoning) {\n\t\tconst stringThinkingParams = params as typeof params & { thinking?: string };\n\t\tif (options?.reasoningEffort) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t\t} else if (model.thinkingLevelMap?.off !== null) {\n\t\t\tstringThinkingParams.thinking = model.thinkingLevelMap?.off ?? \"none\";\n\t\t}\n\t} else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\t// OpenAI-style reasoning_effort\n\t\t(params as any).reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n\t} else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n\t\tconst offValue = model.thinkingLevelMap?.off;\n\t\tif (typeof offValue === \"string\") {\n\t\t\t(params as any).reasoning_effort = offValue;\n\t\t}\n\t}\n\n\t// OpenRouter provider routing preferences\n\tif (model.compat?.openRouterRouting) {\n\t\t(params as any).provider = model.compat.openRouterRouting;\n\t}\n\n\t// Vercel AI Gateway provider routing preferences\n\tif (model.baseUrl.includes(\"ai-gateway.vercel.sh\") && model.compat?.vercelGatewayRouting) {\n\t\tconst routing = model.compat.vercelGatewayRouting;\n\t\tif (routing.only || routing.order) {\n\t\t\tconst gatewayOptions: Record<string, string[]> = {};\n\t\t\tif (routing.only) gatewayOptions.only = routing.only;\n\t\t\tif (routing.order) gatewayOptions.order = routing.order;\n\t\t\t(params as any).providerOptions = { gateway: gatewayOptions };\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction getCompatCacheControl(\n\tcompat: ResolvedOpenAICompletionsCompat,\n\tcacheRetention: CacheRetention,\n): OpenAICompatCacheControl | undefined {\n\tif (compat.cacheControlFormat !== \"anthropic\" || cacheRetention === \"none\") {\n\t\treturn undefined;\n\t}\n\n\tconst ttl = cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"1h\" : undefined;\n\treturn { type: \"ephemeral\", ...(ttl ? { ttl } : {}) };\n}\n\nfunction applyAnthropicCacheControl(\n\tmessages: ChatCompletionMessageParam[],\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\taddCacheControlToSystemPrompt(messages, cacheControl);\n\taddCacheControlToLastTool(tools, cacheControl);\n\taddCacheControlToLastConversationMessage(messages, cacheControl);\n}\n\nfunction addCacheControlToSystemPrompt(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (const message of messages) {\n\t\tif (message.role === \"system\" || message.role === \"developer\") {\n\t\t\taddCacheControlToInstructionMessage(message, cacheControl);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastConversationMessage(\n\tmessages: ChatCompletionMessageParam[],\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\t\tif (addCacheControlToMessage(message, cacheControl)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction addCacheControlToLastTool(\n\ttools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,\n\tcacheControl: OpenAICompatCacheControl,\n): void {\n\tif (!tools || tools.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastTool = tools[tools.length - 1] as ChatCompletionToolWithCacheControl;\n\tlastTool.cache_control = cacheControl;\n}\n\nfunction addCacheControlToInstructionMessage(\n\tmessage: ChatCompletionInstructionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\treturn addCacheControlToTextContent(message, cacheControl);\n}\n\nfunction addCacheControlToMessage(\n\tmessage: ChatCompletionMessageParam,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tif (message.role === \"user\" || message.role === \"assistant\") {\n\t\treturn addCacheControlToTextContent(message, cacheControl);\n\t}\n\treturn false;\n}\n\nfunction addCacheControlToTextContent(\n\tmessage:\n\t\t| ChatCompletionInstructionMessageParam\n\t\t| ChatCompletionAssistantMessageParam\n\t\t| Extract<ChatCompletionMessageParam, { role: \"user\" }>,\n\tcacheControl: OpenAICompatCacheControl,\n): boolean {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\tif (content.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tmessage.content = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: content,\n\t\t\t\tcache_control: cacheControl,\n\t\t\t},\n\t\t] as ChatCompletionTextPartWithCacheControl[];\n\t\treturn true;\n\t}\n\n\tif (!Array.isArray(content)) {\n\t\treturn false;\n\t}\n\n\tfor (let i = content.length - 1; i >= 0; i--) {\n\t\tconst part = content[i];\n\t\tif (part?.type === \"text\") {\n\t\t\tconst textPart = part as ChatCompletionTextPartWithCacheControl;\n\t\t\ttextPart.cache_control = cacheControl;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nexport function convertMessages(\n\tmodel: Model<\"openai-completions\">,\n\tcontext: Context,\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(context.tools ?? []),\n): ChatCompletionMessageParam[] {\n\tconst params: ChatCompletionMessageParam[] = [];\n\n\tconst normalizeToolCallId = (id: string): string => {\n\t\t// Handle pipe-separated IDs from OpenAI Responses API\n\t\t// Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)\n\t\t// These come from providers like github-copilot, openai-codex, opencode\n\t\t// Extract just the call_id part and normalize it\n\t\tif (id.includes(\"|\")) {\n\t\t\tconst [callId] = id.split(\"|\");\n\t\t\t// Sanitize to allowed chars and truncate to 40 chars (OpenAI limit)\n\t\t\treturn callId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 40);\n\t\t}\n\n\t\tif (model.provider === \"openai\") return id.length > 40 ? id.slice(0, 40) : id;\n\t\treturn id;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId(id));\n\n\tif (context.systemPrompt) {\n\t\tconst useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n\t\tconst role = useDeveloperRole ? \"developer\" : \"system\";\n\t\tparams.push({ role: role, content: sanitizeSurrogates(context.systemPrompt) });\n\t}\n\n\tlet lastRole: string | null = null;\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\t\t// Some providers don't allow user messages directly after tool results\n\t\t// Insert a synthetic assistant message to bridge the gap\n\t\tif (compat.requiresAssistantAfterToolResult && lastRole === \"toolResult\" && msg.role === \"user\") {\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t});\n\t\t}\n\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: sanitizeSurrogates(msg.content),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ChatCompletionContentPart[] = msg.content.map((item): ChatCompletionContentPart => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartText;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\turl: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies ChatCompletionContentPartImage;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\t// Some providers don't accept null content, use empty string instead\n\t\t\tconst assistantMsg: ChatCompletionAssistantMessageParam = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: compat.requiresAssistantAfterToolResult ? \"\" : null,\n\t\t\t};\n\n\t\t\tconst assistantTextParts = msg.content\n\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t.filter((block) => block.text.trim().length > 0)\n\t\t\t\t.map(\n\t\t\t\t\t(block) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t\t}) satisfies ChatCompletionContentPartText,\n\t\t\t\t);\n\t\t\tconst assistantText = assistantTextParts.map((part) => part.text).join(\"\");\n\n\t\t\tconst nonEmptyThinkingBlocks = msg.content\n\t\t\t\t.filter(isThinkingContentBlock)\n\t\t\t\t.filter((block) => block.thinking.trim().length > 0);\n\t\t\tif (nonEmptyThinkingBlocks.length > 0) {\n\t\t\t\tif (compat.requiresThinkingAsText) {\n\t\t\t\t\t// Convert thinking blocks to plain text (no tags to avoid model mimicking them)\n\t\t\t\t\tconst thinkingText = nonEmptyThinkingBlocks\n\t\t\t\t\t\t.map((block) => sanitizeSurrogates(block.thinking))\n\t\t\t\t\t\t.join(\"\\n\\n\");\n\t\t\t\t\tassistantMsg.content = [{ type: \"text\", text: thinkingText }, ...assistantTextParts];\n\t\t\t\t} else {\n\t\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\t\tif (assistantText.length > 0) {\n\t\t\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss)\n\t\t\t\t\tlet signature = nonEmptyThinkingBlocks[0].thinkingSignature;\n\t\t\t\t\tif (model.provider === \"opencode-go\" && signature === \"reasoning\") {\n\t\t\t\t\t\tsignature = \"reasoning_content\";\n\t\t\t\t\t}\n\t\t\t\t\tif (signature && signature.length > 0) {\n\t\t\t\t\t\t(assistantMsg as any)[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (assistantText.length > 0) {\n\t\t\t\t// Always send assistant content as a plain string (OpenAI Chat Completions\n\t\t\t\t// API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n\t\t\t\t// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n\t\t\t\t// NVIDIA NIM) to mirror the content-block structure literally in their\n\t\t\t\t// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n\t\t\t\tassistantMsg.content = assistantText;\n\t\t\t}\n\n\t\t\tconst toolCalls = msg.content.filter(isToolCallBlock);\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tassistantMsg.tool_calls = toolCalls.map((tc) => ({\n\t\t\t\t\tid: tc.id,\n\t\t\t\t\ttype: \"function\" as const,\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: toolNameMap.toProviderName(tc.name),\n\t\t\t\t\t\targuments: JSON.stringify(tc.arguments),\n\t\t\t\t\t},\n\t\t\t\t}));\n\t\t\t\tconst reasoningDetails = toolCalls\n\t\t\t\t\t.filter((tc) => tc.thoughtSignature)\n\t\t\t\t\t.map((tc) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn JSON.parse(tc.thoughtSignature!);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.filter(Boolean);\n\t\t\t\tif (reasoningDetails.length > 0) {\n\t\t\t\t\t(assistantMsg as any).reasoning_details = reasoningDetails;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcompat.requiresReasoningContentOnAssistantMessages &&\n\t\t\t\tmodel.reasoning &&\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content === undefined\n\t\t\t) {\n\t\t\t\t(assistantMsg as { reasoning_content?: string }).reasoning_content = \"\";\n\t\t\t}\n\t\t\t// Skip assistant messages that have no content and no tool calls.\n\t\t\t// Some providers require \"either content or tool_calls, but not none\".\n\t\t\t// Other providers also don't accept empty assistant messages.\n\t\t\t// This handles aborted assistant responses that got no content.\n\t\t\tconst content = assistantMsg.content;\n\t\t\tconst hasContent =\n\t\t\t\tcontent !== null &&\n\t\t\t\tcontent !== undefined &&\n\t\t\t\t(typeof content === \"string\" ? content.length > 0 : content.length > 0);\n\t\t\tif (!hasContent && !assistantMsg.tool_calls) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparams.push(assistantMsg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst imageBlocks: Array<{ type: \"image_url\"; image_url: { url: string } }> = [];\n\t\t\tlet j = i;\n\n\t\t\tfor (; j < transformedMessages.length && transformedMessages[j].role === \"toolResult\"; j++) {\n\t\t\t\tconst toolMsg = transformedMessages[j] as ToolResultMessage;\n\n\t\t\t\t// Extract text and image content\n\t\t\t\tconst textResult = toolMsg.content\n\t\t\t\t\t.filter(isTextContentBlock)\n\t\t\t\t\t.map((block) => block.text)\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tconst hasImages = toolMsg.content.some((c) => c.type === \"image\");\n\n\t\t\t\t// Always send tool result with text (or placeholder if only images)\n\t\t\t\tconst hasText = textResult.length > 0;\n\t\t\t\t// Some providers require the 'name' field in tool results\n\t\t\t\tconst toolResultMsg: ChatCompletionToolMessageParam = {\n\t\t\t\t\trole: \"tool\",\n\t\t\t\t\tcontent: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n\t\t\t\t\ttool_call_id: toolMsg.toolCallId,\n\t\t\t\t};\n\t\t\t\tif (compat.requiresToolResultName && toolMsg.toolName) {\n\t\t\t\t\t(toolResultMsg as any).name = toolMsg.toolName;\n\t\t\t\t}\n\t\t\t\tparams.push(toolResultMsg);\n\n\t\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\t\tfor (const block of toolMsg.content) {\n\t\t\t\t\t\tif (isImageContentBlock(block)) {\n\t\t\t\t\t\t\timageBlocks.push({\n\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\timage_url: {\n\t\t\t\t\t\t\t\t\turl: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ti = j - 1;\n\n\t\t\tif (imageBlocks.length > 0) {\n\t\t\t\tif (compat.requiresAssistantAfterToolResult) {\n\t\t\t\t\tparams.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: \"I have processed the tool results.\",\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Attached image(s) from tool result:\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...imageBlocks,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tlastRole = \"user\";\n\t\t\t} else {\n\t\t\t\tlastRole = \"toolResult\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tlastRole = msg.role;\n\t}\n\n\treturn params;\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tcompat: ResolvedOpenAICompletionsCompat,\n\ttoolNameMap: ToolNameMap = createToolNameMap(tools),\n): OpenAI.Chat.Completions.ChatCompletionTool[] {\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: toolNameMap.toProviderName(tool.name),\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\t\t// Only include strict if provider supports it. Some reject unknown fields.\n\t\t\t...(compat.supportsStrictMode !== false && { strict: false }),\n\t\t},\n\t}));\n}\n\nfunction parseChunkUsage(\n\trawUsage: {\n\t\tprompt_tokens?: number;\n\t\tcompletion_tokens?: number;\n\t\tprompt_cache_hit_tokens?: number;\n\t\tprompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\t\tcost?: number;\n\t},\n\tmodel: Model<\"openai-completions\">,\n): AssistantMessage[\"usage\"] {\n\tconst promptTokens = rawUsage.prompt_tokens || 0;\n\tconst cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;\n\tconst cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n\n\t// Follow documented OpenAI/OpenRouter semantics: cached_tokens is cache-read\n\t// tokens (hits). OpenAI does not document or emit cache_write_tokens, but\n\t// OpenRouter-compatible providers can include it as a separate write count.\n\t// OpenRouter's own provider/tests affirm the separate mapping:\n\t// https://github.com/OpenRouterTeam/ai-sdk-provider/pull/409\n\t// Do not subtract writes from cached_tokens, otherwise spec-compliant\n\t// providers are under-reported. DS4 mirrors this contract too:\n\t// https://github.com/antirez/ds4/pull/29\n\tconst input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n\t// OpenAI completion_tokens already includes reasoning_tokens.\n\tconst outputTokens = rawUsage.completion_tokens || 0;\n\tconst usage: AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput: outputTokens,\n\t\tcacheRead: cacheReadTokens,\n\t\tcacheWrite: cacheWriteTokens,\n\t\ttotalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: rawUsage.cost || 0 },\n\t};\n\tcalculateCost(model, usage, { providerSuppliedTotal: Boolean(rawUsage.cost) });\n\treturn usage;\n}\n\nfunction mapStopReason(reason: ChatCompletionChunk.Choice[\"finish_reason\"] | string): {\n\tstopReason: StopReason;\n\terrorMessage?: string;\n} {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\tcase \"end\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"function_call\":\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"content_filter\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: content_filter\" };\n\t\tcase \"network_error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider finish_reason: network_error\" };\n\t\tdefault:\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: `Provider finish_reason: ${reason}`,\n\t\t\t};\n\t}\n}\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai = provider === \"zai\" || baseUrl.includes(\"api.z.ai\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\n\tconst isNonStandard =\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tbaseUrl.includes(\"deepseek.com\") ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway;\n\n\tconst useMaxTokens = baseUrl.includes(\"chutes.ai\") || isMoonshot || isCloudflareAiGateway || isTogether;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n\tconst cacheControlFormat = provider === \"openrouter\" && model.id.startsWith(\"anthropic/\") ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: !isNonStandard && !isOpenRouter,\n\t\tsupportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tsupportsUsageInStreaming: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: false,\n\t\tsupportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Uses explicit model.compat if provided, otherwise auto-detects from provider/URL.\n */\nfunction getCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? {},\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n"]}
@@ -6,7 +6,7 @@ export interface ParsedTextToolCalls {
6
6
  attempted: boolean;
7
7
  failure?: TextToolProtocolParseFailure;
8
8
  }
9
- export type TextToolProtocolVariant = "tool-tag" | "tool-call" | "fenced-json";
9
+ export type TextToolProtocolVariant = "tool-tag" | "tool-call" | "fenced-json" | "function-xml";
10
10
  export interface TextToolProtocolOptions {
11
11
  variant?: TextToolProtocolVariant;
12
12
  }
@@ -1 +1 @@
1
- {"version":3,"file":"text-protocol.d.ts","sourceRoot":"","sources":["../../../src/utils/tool-repair/text-protocol.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAErD,MAAM,MAAM,4BAA4B,GACrC,SAAS,GACT,aAAa,GACb,cAAc,GACd,cAAc,GACd,mBAAmB,CAAC;AAEvB,MAAM,WAAW,mBAAmB;IACnC,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,4BAA4B,CAAC;CACvC;AAED,MAAM,MAAM,uBAAuB,GAAG,UAAU,GAAG,WAAW,GAAG,aAAa,CAAC;AAE/E,MAAM,WAAW,uBAAuB;IACvC,OAAO,CAAC,EAAE,uBAAuB,CAAC;CAClC;AA+QD,wBAAgB,gCAAgC,CAC/C,MAAM,EAAE,OAAO,GAAG,uBAAuB,GAAG,SAAS,GACnD,uBAAuB,GAAG,SAAS,CAIrC;AAuJD,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,MAAM,CAchH;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,IAAI,EAAE,GAAG,mBAAmB,CAajG","sourcesContent":["import type { Tool, ToolCall } from \"../../types.ts\";\n\nexport type TextToolProtocolParseFailure =\n\t| \"overlap\"\n\t| \"mixed-prose\"\n\t| \"unrecognized\"\n\t| \"unknown-tool\"\n\t| \"validation-failed\";\n\nexport interface ParsedTextToolCalls {\n\tcalls: ToolCall[];\n\ttext: string;\n\tattempted: boolean;\n\tfailure?: TextToolProtocolParseFailure;\n}\n\nexport type TextToolProtocolVariant = \"tool-tag\" | \"tool-call\" | \"fenced-json\";\n\nexport interface TextToolProtocolOptions {\n\tvariant?: TextToolProtocolVariant;\n}\n\ntype EnvelopeKind = \"pi_call\" | \"tool_call\" | \"fenced_json\";\n\ninterface EnvelopeMatch {\n\tkind: EnvelopeKind;\n\tstart: number;\n\tend: number;\n\tname?: string;\n\tbody: string;\n}\n\nconst DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT: TextToolProtocolVariant = \"tool-tag\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction escapeAttribute(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction knownToolNames(tools: readonly Tool[]): Set<string> {\n\treturn new Set(tools.map((tool) => tool.name));\n}\n\nfunction findJsonObjectEnd(text: string, start: number): number | undefined {\n\tlet index = start;\n\twhile (/\\s/.test(text[index] ?? \"\")) index++;\n\tif (text[index] !== \"{\") return undefined;\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (; index < text.length; index++) {\n\t\tconst char = text[index];\n\t\tif (inString) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"{\") depth++;\n\t\tif (char === \"}\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return index + 1;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isInsideMatch(index: number, matches: readonly EnvelopeMatch[]): boolean {\n\treturn matches.some((match) => index >= match.start && index < match.end);\n}\n\nfunction findToolEnvelopes(text: string): EnvelopeMatch[] {\n\tconst matches: EnvelopeMatch[] = [];\n\tconst piCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/pi:call\\s*>/g;\n\tfor (const match of text.matchAll(piCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\tconst openPiCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>/g;\n\tfor (const match of text.matchAll(openPiCallEnvelope)) {\n\t\tif (isInsideMatch(match.index, matches)) continue;\n\t\tconst bodyStart = match.index + match[0].length;\n\t\tconst bodyEnd = findJsonObjectEnd(text, bodyStart);\n\t\tif (bodyEnd === undefined) continue;\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: bodyEnd,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: text.slice(bodyStart, bodyEnd),\n\t\t});\n\t}\n\n\tconst toolCallEnvelope = /<tool_call>([\\s\\S]*?)<\\/tool_call>/g;\n\tfor (const match of text.matchAll(toolCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"tool_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst fence = /```(?:tool|tool_call|json)\\s*\\n([\\s\\S]*?)\\n?```/gi;\n\tfor (const match of text.matchAll(fence)) {\n\t\tmatches.push({\n\t\t\tkind: \"fenced_json\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\treturn matches.sort((a, b) => a.start - b.start);\n}\n\nfunction hasOverlap(matches: readonly EnvelopeMatch[]): boolean {\n\tlet previousEnd = -1;\n\tfor (const match of matches) {\n\t\tif (match.start < previousEnd) return true;\n\t\tpreviousEnd = match.end;\n\t}\n\treturn false;\n}\n\nfunction remainingText(text: string, matches: readonly EnvelopeMatch[]): string {\n\tlet cursor = 0;\n\tconst pieces: string[] = [];\n\tfor (const match of matches) {\n\t\tpieces.push(text.slice(cursor, match.start));\n\t\tcursor = match.end;\n\t}\n\tpieces.push(text.slice(cursor));\n\treturn pieces.join(\"\");\n}\n\nfunction coerceArguments(value: unknown): {\n\targuments: Record<string, unknown>;\n\trawArguments?: Record<string, unknown>;\n} {\n\tif (isRecord(value)) return { arguments: value };\n\treturn { arguments: value as Record<string, unknown>, rawArguments: { value } };\n}\n\nfunction normalizeSingleQuotedJson(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tif (!/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/.test(trimmed)) return undefined;\n\treturn trimmed.replace(/'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g, (_match, inner: string) => {\n\t\treturn JSON.stringify(inner.replace(/\\\\'/g, \"'\"));\n\t});\n}\n\nfunction normalizeBareJsonObject(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tlet changed = false;\n\tlet normalized = trimmed.replace(\n\t\t/([{,]\\s*)([A-Za-z_][A-Za-z0-9_-]*)(\\s*:)/g,\n\t\t(_match, prefix: string, key: string, suffix: string) => {\n\t\t\tchanged = true;\n\t\t\treturn `${prefix}${JSON.stringify(key)}${suffix}`;\n\t\t},\n\t);\n\tnormalized = normalized.replace(/:\\s*([A-Za-z_./-][A-Za-z0-9_./:-]*)(?=\\s*[,}])/g, (_match, value: string) => {\n\t\tif ([\"true\", \"false\", \"null\"].includes(value)) return `:${value}`;\n\t\tchanged = true;\n\t\treturn `:${JSON.stringify(value)}`;\n\t});\n\treturn changed ? normalized : undefined;\n}\n\nfunction normalizedJsonCandidates(raw: string): string[] {\n\tconst candidates: string[] = [];\n\tconst objectEnd = findJsonObjectEnd(raw, 0);\n\tif (objectEnd !== undefined && raw.slice(objectEnd).trim()) candidates.push(raw.slice(0, objectEnd));\n\tconst singleQuoted = normalizeSingleQuotedJson(raw);\n\tif (singleQuoted) candidates.push(singleQuoted);\n\tconst bare = normalizeBareJsonObject(raw);\n\tif (bare) candidates.push(bare);\n\tconst singleQuotedBare = singleQuoted ? normalizeBareJsonObject(singleQuoted) : undefined;\n\tif (singleQuotedBare) candidates.push(singleQuotedBare);\n\treturn candidates;\n}\n\nfunction parseJsonValue(raw: string): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: JSON.parse(raw) as unknown };\n\t} catch {\n\t\tfor (const normalized of normalizedJsonCandidates(raw)) {\n\t\t\ttry {\n\t\t\t\treturn { ok: true, value: JSON.parse(normalized) as unknown };\n\t\t\t} catch {\n\t\t\t\t// Try the next bounded normalization candidate.\n\t\t\t}\n\t\t}\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseJsonObject(raw: string): Record<string, unknown> | undefined {\n\tconst parsed = parseJsonValue(raw);\n\treturn parsed.ok && isRecord(parsed.value) ? parsed.value : undefined;\n}\n\nfunction textToolErrorMessage(name: string, names: readonly string[]): string | undefined {\n\tif (names.includes(name)) return undefined;\n\treturn `Unknown tool \"${name}\". Valid tools: ${names.join(\", \")}.`;\n}\n\nfunction extractNameFromMalformedJson(raw: string): string | undefined {\n\tconst match = /\"(?:name|tool)\"\\s*:\\s*\"([^\"]+)\"/.exec(raw);\n\treturn match?.[1];\n}\n\nfunction parsePiCallEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tconst parsed = parseJsonValue(match.body);\n\tconst args = parsed.ok ? coerceArguments(parsed.value) : coerceArguments(match.body.trim());\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: args.arguments,\n\t\trawArguments: parsed.ok ? args.rawArguments : { text: match.body.trim() },\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (match.kind === \"pi_call\") return parsePiCallEnvelope(match, names, index);\n\n\tconst parsed = parseJsonObject(match.body);\n\tif (!parsed) {\n\t\tconst name = extractNameFromMalformedJson(match.body);\n\t\tif (!name) return undefined;\n\t\treturn {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `text-tool-${index}`,\n\t\t\tname,\n\t\t\targuments: match.body.trim() as unknown as Record<string, unknown>,\n\t\t\trawArguments: { text: match.body.trim() },\n\t\t\tsource: \"text-protocol\",\n\t\t\terrorMessage: textToolErrorMessage(name, names),\n\t\t};\n\t}\n\n\tconst wrappedTool = isRecord(parsed.tool) ? parsed.tool : undefined;\n\tconst nameValue = parsed.name ?? (typeof parsed.tool === \"string\" ? parsed.tool : undefined) ?? wrappedTool?.name;\n\tif (typeof nameValue !== \"string\") return undefined;\n\tconst argsValue = parsed.arguments ?? parsed.args ?? wrappedTool?.arguments ?? wrappedTool?.args ?? {};\n\tconst args = coerceArguments(argsValue);\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: nameValue,\n\t\targuments: args.arguments,\n\t\trawArguments: args.rawArguments,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(nameValue, names),\n\t};\n}\n\nexport function normalizeTextToolProtocolOptions(\n\toption: boolean | TextToolProtocolOptions | undefined,\n): TextToolProtocolOptions | undefined {\n\tif (!option) return undefined;\n\tif (option === true) return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n\treturn { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n}\n\nfunction formatVariantEnvelope(variant: TextToolProtocolVariant, toolName: string, argsJson: string): string {\n\tif (variant === \"tool-call\") return `<tool_call>{\"name\":\"${toolName}\",\"arguments\":${argsJson}}</tool_call>`;\n\tif (variant === \"fenced-json\") return `\\`\\`\\`tool_call\\n{\"name\":\"${toolName}\",\"arguments\":${argsJson}}\\n\\`\\`\\``;\n\treturn `<pi:call name=\"${escapeAttribute(toolName)}\">${argsJson}</pi:call>`;\n}\n\nfunction schemaRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined;\n}\n\nfunction firstString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction schemaType(schema: Record<string, unknown>): string | undefined {\n\tconst type = schema.type;\n\tif (typeof type === \"string\") return type;\n\tif (!Array.isArray(type)) return undefined;\n\treturn type.filter(firstString).find((entry) => entry !== \"null\");\n}\n\nfunction stringExampleForProperty(propertyName: string | undefined): string {\n\tif (propertyName === \"path\") return \"src/index.ts\";\n\tif (propertyName === \"command\") return \"echo ok\";\n\tif (propertyName === \"oldText\") return \"foo\";\n\tif (propertyName === \"newText\") return \"bar\";\n\tif (propertyName === \"content\") return \"text\";\n\treturn \"value\";\n}\n\nfunction exampleValueForSchema(schemaValue: unknown, propertyName?: string): unknown {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return stringExampleForProperty(propertyName);\n\tconst constValue = schema.const;\n\tif (constValue !== undefined) return constValue;\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0) return enumValues[0];\n\tconst defaultValue = schema.default;\n\tif (defaultValue !== undefined) return defaultValue;\n\tconst type = schemaType(schema);\n\tif (type === \"number\" || type === \"integer\") return 1;\n\tif (type === \"boolean\") return true;\n\tif (type === \"array\") return [exampleValueForSchema(schema.items, propertyName)];\n\tif (type === \"object\") return exampleArgumentsForParameters(schema);\n\treturn stringExampleForProperty(propertyName);\n}\n\nfunction requiredPropertyNames(parameters: Record<string, unknown> | undefined): string[] {\n\treturn Array.isArray(parameters?.required) ? parameters.required.filter(firstString) : [];\n}\n\nfunction exampleArgumentsForParameters(parametersValue: unknown): Record<string, unknown> {\n\tconst parameters = schemaRecord(parametersValue);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return {};\n\tconst args: Record<string, unknown> = {};\n\tfor (const name of requiredPropertyNames(parameters)) {\n\t\targs[name] = exampleValueForSchema(properties[name], name);\n\t}\n\treturn args;\n}\n\nfunction typeLabel(schemaValue: unknown): string {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return \"string\";\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0 && enumValues.every((entry) => [\"string\", \"number\", \"boolean\"].includes(typeof entry))) {\n\t\treturn enumValues.map(String).join(\"|\");\n\t}\n\tconst type = schemaType(schema);\n\tif (type === \"integer\" || type === \"number\") return \"number\";\n\tif (type === \"boolean\") return \"bool\";\n\tif (type === \"array\") return `${typeLabel(schema.items)}[]`;\n\tif (type === \"object\") {\n\t\tconst properties = schemaRecord(schema.properties);\n\t\tif (!properties) return \"{}\";\n\t\tconst entries = Object.entries(properties)\n\t\t\t.slice(0, 4)\n\t\t\t.map(([name, value]) => `${name}:${typeLabel(value)}`);\n\t\tconst suffix = Object.keys(properties).length > entries.length ? \",...\" : \"\";\n\t\treturn `{${entries.join(\",\")}${suffix}}`;\n\t}\n\treturn \"string\";\n}\n\nfunction orderedPropertyNames(properties: Record<string, unknown>, required: readonly string[]): string[] {\n\tconst requiredSet = new Set(required);\n\treturn [\n\t\t...required.filter((name) => name in properties),\n\t\t...Object.keys(properties).filter((name) => !requiredSet.has(name)),\n\t];\n}\n\nfunction formatDefault(value: unknown): string {\n\tconst json = JSON.stringify(value);\n\treturn json ? `=${json}` : \"\";\n}\n\nfunction formatToolProjection(tool: Tool): string {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tconst required = requiredPropertyNames(parameters);\n\tconst requiredSet = new Set(required);\n\tconst args = properties\n\t\t? orderedPropertyNames(properties, required)\n\t\t\t\t.map((name) => {\n\t\t\t\t\tconst schema = schemaRecord(properties[name]);\n\t\t\t\t\tconst optional = requiredSet.has(name) ? \"\" : \"?\";\n\t\t\t\t\tconst defaultText = schema && \"default\" in schema ? formatDefault(schema.default) : \"\";\n\t\t\t\t\treturn `${name}:${typeLabel(schema)}${optional}${defaultText}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \")\n\t\t: \"\";\n\tconst description = tool.description.replace(/\\s+/g, \" \").trim();\n\treturn `${tool.name}(${args}) - ${description}`;\n}\n\nfunction toolHasArrayParameter(tool: Tool): boolean {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return false;\n\treturn Object.values(properties).some((schemaValue) => schemaType(schemaRecord(schemaValue) ?? {}) === \"array\");\n}\n\nfunction exampleTools(tools: readonly Tool[]): Tool[] {\n\tconst examples: Tool[] = [];\n\tconst readTool = tools.find((tool) => tool.name === \"read\");\n\tif (readTool) examples.push(readTool);\n\tif (examples.length === 0) examples.push(tools[0]);\n\tconst editTool = tools.find((tool) => tool.name === \"edit\" && !examples.includes(tool));\n\tconst arrayTool = editTool ?? tools.find((tool) => !examples.includes(tool) && toolHasArrayParameter(tool));\n\tif (arrayTool) examples.push(arrayTool);\n\treturn examples;\n}\n\nfunction protocolHeader(variant: TextToolProtocolVariant): string[] {\n\treturn [\n\t\t\"Text tool-call protocol is enabled.\",\n\t\t\"When calling tools, output only one or more envelopes and no prose:\",\n\t\tformatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}'),\n\t\t\"Arguments must be valid JSON objects. Use double quotes for JSON keys and string values. Arrays are JSON arrays [ ], never quoted strings. Omit optional args you do not need - do not send null.\",\n\t\t\"User requests about files, directories, searches, edits, writes, or shell commands require a tool envelope first; do not describe results yourself.\",\n\t\t'If the user asks to read /tmp/example.txt, output exactly: <pi:call name=\"read\">{\"path\":\"/tmp/example.txt\"}</pi:call>',\n\t\t'For any request to read a file path, call read with {\"path\":\"THE_PATH\"}; never output {\"file_path\":..., \"content\":...} or invented file contents.',\n\t\t\"Never write raw shell commands such as read -t PATH, cat PATH, or ls PATH; use a tool-call envelope instead.\",\n\t\t\"Never output markdown code blocks, raw shell commands, file paths, or invented tool results instead of a tool call; use the envelope and wait for the real result.\",\n\t];\n}\n\nexport function generateTextToolProtocolPrimer(tools: readonly Tool[], options?: TextToolProtocolOptions): string {\n\tif (tools.length === 0) return \"\";\n\tconst variant = options?.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT;\n\tconst lines = [...protocolHeader(variant), \"Examples:\"];\n\tfor (const tool of exampleTools(tools)) {\n\t\tlines.push(\n\t\t\tformatVariantEnvelope(variant, tool.name, JSON.stringify(exampleArgumentsForParameters(tool.parameters))),\n\t\t);\n\t}\n\tlines.push(\"Available tools:\");\n\tfor (const tool of tools) {\n\t\tlines.push(formatToolProjection(tool));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function parseTextToolCalls(text: string, knownTools: readonly Tool[]): ParsedTextToolCalls {\n\tif (knownTools.length === 0) return { calls: [], text, attempted: false };\n\tconst matches = findToolEnvelopes(text);\n\tif (matches.length === 0) return { calls: [], text, attempted: false };\n\tif (hasOverlap(matches)) return { calls: [], text, attempted: true, failure: \"overlap\" };\n\tconst remainder = remainingText(text, matches);\n\tconst names = [...knownToolNames(knownTools)];\n\tconst calls = matches\n\t\t.map((match, index) => parseEnvelope(match, names, index + 1))\n\t\t.filter((call): call is ToolCall => call !== undefined);\n\treturn calls.length > 0\n\t\t? { calls, text: remainder.trim(), attempted: true }\n\t\t: { calls: [], text, attempted: true, failure: \"unrecognized\" };\n}\n"]}
1
+ {"version":3,"file":"text-protocol.d.ts","sourceRoot":"","sources":["../../../src/utils/tool-repair/text-protocol.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAErD,MAAM,MAAM,4BAA4B,GACrC,SAAS,GACT,aAAa,GACb,cAAc,GACd,cAAc,GACd,mBAAmB,CAAC;AAEvB,MAAM,WAAW,mBAAmB;IACnC,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,4BAA4B,CAAC;CACvC;AAED,MAAM,MAAM,uBAAuB,GAAG,UAAU,GAAG,WAAW,GAAG,aAAa,GAAG,cAAc,CAAC;AAEhG,MAAM,WAAW,uBAAuB;IACvC,OAAO,CAAC,EAAE,uBAAuB,CAAC;CAClC;AAoUD,wBAAgB,gCAAgC,CAC/C,MAAM,EAAE,OAAO,GAAG,uBAAuB,GAAG,SAAS,GACnD,uBAAuB,GAAG,SAAS,CAIrC;AAyKD,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,MAAM,CAchH;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,IAAI,EAAE,GAAG,mBAAmB,CAajG","sourcesContent":["import type { Tool, ToolCall } from \"../../types.ts\";\n\nexport type TextToolProtocolParseFailure =\n\t| \"overlap\"\n\t| \"mixed-prose\"\n\t| \"unrecognized\"\n\t| \"unknown-tool\"\n\t| \"validation-failed\";\n\nexport interface ParsedTextToolCalls {\n\tcalls: ToolCall[];\n\ttext: string;\n\tattempted: boolean;\n\tfailure?: TextToolProtocolParseFailure;\n}\n\nexport type TextToolProtocolVariant = \"tool-tag\" | \"tool-call\" | \"fenced-json\" | \"function-xml\";\n\nexport interface TextToolProtocolOptions {\n\tvariant?: TextToolProtocolVariant;\n}\n\ntype EnvelopeKind = \"pi_call\" | \"tool_call\" | \"fenced_json\" | \"function_xml\";\n\ninterface EnvelopeMatch {\n\tkind: EnvelopeKind;\n\tstart: number;\n\tend: number;\n\tname?: string;\n\tbody: string;\n}\n\nconst DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT: TextToolProtocolVariant = \"tool-tag\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction escapeAttribute(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction escapeXmlText(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeXmlText(value: string): string {\n\treturn value\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction knownToolNames(tools: readonly Tool[]): Set<string> {\n\treturn new Set(tools.map((tool) => tool.name));\n}\n\nfunction findJsonObjectEnd(text: string, start: number): number | undefined {\n\tlet index = start;\n\twhile (/\\s/.test(text[index] ?? \"\")) index++;\n\tif (text[index] !== \"{\") return undefined;\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (; index < text.length; index++) {\n\t\tconst char = text[index];\n\t\tif (inString) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"{\") depth++;\n\t\tif (char === \"}\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return index + 1;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isInsideMatch(index: number, matches: readonly EnvelopeMatch[]): boolean {\n\treturn matches.some((match) => index >= match.start && index < match.end);\n}\n\nfunction findToolEnvelopes(text: string): EnvelopeMatch[] {\n\tconst matches: EnvelopeMatch[] = [];\n\tconst piCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/pi:call\\s*>/g;\n\tfor (const match of text.matchAll(piCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\tconst openPiCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>/g;\n\tfor (const match of text.matchAll(openPiCallEnvelope)) {\n\t\tif (isInsideMatch(match.index, matches)) continue;\n\t\tconst bodyStart = match.index + match[0].length;\n\t\tconst bodyEnd = findJsonObjectEnd(text, bodyStart);\n\t\tif (bodyEnd === undefined) continue;\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: bodyEnd,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: text.slice(bodyStart, bodyEnd),\n\t\t});\n\t}\n\n\tconst toolCallEnvelope = /<tool_call>([\\s\\S]*?)<\\/tool_call>/g;\n\tfor (const match of text.matchAll(toolCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"tool_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst fence = /```(?:tool|tool_call|json)\\s*\\n([\\s\\S]*?)\\n?```/gi;\n\tfor (const match of text.matchAll(fence)) {\n\t\tmatches.push({\n\t\t\tkind: \"fenced_json\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst functionEnvelope = /<function\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/function\\s*>/g;\n\tfor (const match of text.matchAll(functionEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"function_xml\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\treturn matches.sort((a, b) => a.start - b.start);\n}\n\nfunction hasOverlap(matches: readonly EnvelopeMatch[]): boolean {\n\tlet previousEnd = -1;\n\tfor (const match of matches) {\n\t\tif (match.start < previousEnd) return true;\n\t\tpreviousEnd = match.end;\n\t}\n\treturn false;\n}\n\nfunction remainingText(text: string, matches: readonly EnvelopeMatch[]): string {\n\tlet cursor = 0;\n\tconst pieces: string[] = [];\n\tfor (const match of matches) {\n\t\tpieces.push(text.slice(cursor, match.start));\n\t\tcursor = match.end;\n\t}\n\tpieces.push(text.slice(cursor));\n\treturn pieces.join(\"\");\n}\n\nfunction coerceArguments(value: unknown): {\n\targuments: Record<string, unknown>;\n\trawArguments?: Record<string, unknown>;\n} {\n\tif (isRecord(value)) return { arguments: value };\n\treturn { arguments: value as Record<string, unknown>, rawArguments: { value } };\n}\n\nfunction normalizeSingleQuotedJson(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tif (!/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/.test(trimmed)) return undefined;\n\treturn trimmed.replace(/'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g, (_match, inner: string) => {\n\t\treturn JSON.stringify(inner.replace(/\\\\'/g, \"'\"));\n\t});\n}\n\nfunction normalizeBareJsonObject(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tlet changed = false;\n\tlet normalized = trimmed.replace(\n\t\t/([{,]\\s*)([A-Za-z_][A-Za-z0-9_-]*)(\\s*:)/g,\n\t\t(_match, prefix: string, key: string, suffix: string) => {\n\t\t\tchanged = true;\n\t\t\treturn `${prefix}${JSON.stringify(key)}${suffix}`;\n\t\t},\n\t);\n\tnormalized = normalized.replace(/:\\s*([A-Za-z_./-][A-Za-z0-9_./:-]*)(?=\\s*[,}])/g, (_match, value: string) => {\n\t\tif ([\"true\", \"false\", \"null\"].includes(value)) return `:${value}`;\n\t\tchanged = true;\n\t\treturn `:${JSON.stringify(value)}`;\n\t});\n\treturn changed ? normalized : undefined;\n}\n\nfunction normalizedJsonCandidates(raw: string): string[] {\n\tconst candidates: string[] = [];\n\tconst objectEnd = findJsonObjectEnd(raw, 0);\n\tif (objectEnd !== undefined && raw.slice(objectEnd).trim()) candidates.push(raw.slice(0, objectEnd));\n\tconst singleQuoted = normalizeSingleQuotedJson(raw);\n\tif (singleQuoted) candidates.push(singleQuoted);\n\tconst bare = normalizeBareJsonObject(raw);\n\tif (bare) candidates.push(bare);\n\tconst singleQuotedBare = singleQuoted ? normalizeBareJsonObject(singleQuoted) : undefined;\n\tif (singleQuotedBare) candidates.push(singleQuotedBare);\n\treturn candidates;\n}\n\nfunction parseJsonValue(raw: string): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: JSON.parse(raw) as unknown };\n\t} catch {\n\t\tfor (const normalized of normalizedJsonCandidates(raw)) {\n\t\t\ttry {\n\t\t\t\treturn { ok: true, value: JSON.parse(normalized) as unknown };\n\t\t\t} catch {\n\t\t\t\t// Try the next bounded normalization candidate.\n\t\t\t}\n\t\t}\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseJsonObject(raw: string): Record<string, unknown> | undefined {\n\tconst parsed = parseJsonValue(raw);\n\treturn parsed.ok && isRecord(parsed.value) ? parsed.value : undefined;\n}\n\nfunction textToolErrorMessage(name: string, names: readonly string[]): string | undefined {\n\tif (names.includes(name)) return undefined;\n\treturn `Unknown tool \"${name}\". Valid tools: ${names.join(\", \")}.`;\n}\n\nfunction extractNameFromMalformedJson(raw: string): string | undefined {\n\tconst match = /\"(?:name|tool)\"\\s*:\\s*\"([^\"]+)\"/.exec(raw);\n\treturn match?.[1];\n}\n\nfunction parsePiCallEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tconst parsed = parseJsonValue(match.body);\n\tconst args = parsed.ok ? coerceArguments(parsed.value) : coerceArguments(match.body.trim());\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: args.arguments,\n\t\trawArguments: parsed.ok ? args.rawArguments : { text: match.body.trim() },\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseFunctionXmlEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tif (/<\\/?function\\b/i.test(match.body)) return undefined;\n\tconst params: Record<string, string> = {};\n\tlet cursor = 0;\n\tlet sawParam = false;\n\tconst paramPattern = /<param\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/param\\s*>/g;\n\tfor (const param of match.body.matchAll(paramPattern)) {\n\t\tif (match.body.slice(cursor, param.index).trim()) return undefined;\n\t\tconst name = unescapeAttribute(param[2] ?? \"\");\n\t\tif (!name || name in params) return undefined;\n\t\tparams[name] = unescapeXmlText((param[3] ?? \"\").trim());\n\t\tcursor = param.index + param[0].length;\n\t\tsawParam = true;\n\t}\n\tif (match.body.slice(cursor).trim()) return undefined;\n\tif (!sawParam) return undefined;\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: params,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (match.kind === \"pi_call\") return parsePiCallEnvelope(match, names, index);\n\tif (match.kind === \"function_xml\") return parseFunctionXmlEnvelope(match, names, index);\n\n\tconst parsed = parseJsonObject(match.body);\n\tif (!parsed) {\n\t\tconst name = extractNameFromMalformedJson(match.body);\n\t\tif (!name) return undefined;\n\t\treturn {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `text-tool-${index}`,\n\t\t\tname,\n\t\t\targuments: match.body.trim() as unknown as Record<string, unknown>,\n\t\t\trawArguments: { text: match.body.trim() },\n\t\t\tsource: \"text-protocol\",\n\t\t\terrorMessage: textToolErrorMessage(name, names),\n\t\t};\n\t}\n\n\tconst wrappedTool = isRecord(parsed.tool) ? parsed.tool : undefined;\n\tconst nameValue = parsed.name ?? (typeof parsed.tool === \"string\" ? parsed.tool : undefined) ?? wrappedTool?.name;\n\tif (typeof nameValue !== \"string\") return undefined;\n\tconst argsValue = parsed.arguments ?? parsed.args ?? wrappedTool?.arguments ?? wrappedTool?.args ?? {};\n\tconst args = coerceArguments(argsValue);\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: nameValue,\n\t\targuments: args.arguments,\n\t\trawArguments: args.rawArguments,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(nameValue, names),\n\t};\n}\n\nexport function normalizeTextToolProtocolOptions(\n\toption: boolean | TextToolProtocolOptions | undefined,\n): TextToolProtocolOptions | undefined {\n\tif (!option) return undefined;\n\tif (option === true) return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n\treturn { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n}\n\nfunction functionXmlParamValue(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\tconst json = JSON.stringify(value);\n\treturn json ?? String(value);\n}\n\nfunction formatFunctionXmlEnvelope(toolName: string, argsJson: string): string {\n\tconst args = parseJsonObject(argsJson) ?? {};\n\tconst params = Object.entries(args)\n\t\t.map(\n\t\t\t([name, value]) =>\n\t\t\t\t`<param name=\"${escapeAttribute(name)}\">${escapeXmlText(functionXmlParamValue(value))}</param>`,\n\t\t)\n\t\t.join(\"\");\n\treturn `<function name=\"${escapeAttribute(toolName)}\">${params}</function>`;\n}\n\nfunction formatVariantEnvelope(variant: TextToolProtocolVariant, toolName: string, argsJson: string): string {\n\tif (variant === \"tool-call\") return `<tool_call>{\"name\":\"${toolName}\",\"arguments\":${argsJson}}</tool_call>`;\n\tif (variant === \"fenced-json\") return `\\`\\`\\`tool_call\\n{\"name\":\"${toolName}\",\"arguments\":${argsJson}}\\n\\`\\`\\``;\n\tif (variant === \"function-xml\") return formatFunctionXmlEnvelope(toolName, argsJson);\n\treturn `<pi:call name=\"${escapeAttribute(toolName)}\">${argsJson}</pi:call>`;\n}\n\nfunction schemaRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined;\n}\n\nfunction firstString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction schemaType(schema: Record<string, unknown>): string | undefined {\n\tconst type = schema.type;\n\tif (typeof type === \"string\") return type;\n\tif (!Array.isArray(type)) return undefined;\n\treturn type.filter(firstString).find((entry) => entry !== \"null\");\n}\n\nfunction stringExampleForProperty(propertyName: string | undefined): string {\n\tif (propertyName === \"path\") return \"src/index.ts\";\n\tif (propertyName === \"command\") return \"echo ok\";\n\tif (propertyName === \"oldText\") return \"foo\";\n\tif (propertyName === \"newText\") return \"bar\";\n\tif (propertyName === \"content\") return \"text\";\n\treturn \"value\";\n}\n\nfunction exampleValueForSchema(schemaValue: unknown, propertyName?: string): unknown {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return stringExampleForProperty(propertyName);\n\tconst constValue = schema.const;\n\tif (constValue !== undefined) return constValue;\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0) return enumValues[0];\n\tconst defaultValue = schema.default;\n\tif (defaultValue !== undefined) return defaultValue;\n\tconst type = schemaType(schema);\n\tif (type === \"number\" || type === \"integer\") return 1;\n\tif (type === \"boolean\") return true;\n\tif (type === \"array\") return [exampleValueForSchema(schema.items, propertyName)];\n\tif (type === \"object\") return exampleArgumentsForParameters(schema);\n\treturn stringExampleForProperty(propertyName);\n}\n\nfunction requiredPropertyNames(parameters: Record<string, unknown> | undefined): string[] {\n\treturn Array.isArray(parameters?.required) ? parameters.required.filter(firstString) : [];\n}\n\nfunction exampleArgumentsForParameters(parametersValue: unknown): Record<string, unknown> {\n\tconst parameters = schemaRecord(parametersValue);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return {};\n\tconst args: Record<string, unknown> = {};\n\tfor (const name of requiredPropertyNames(parameters)) {\n\t\targs[name] = exampleValueForSchema(properties[name], name);\n\t}\n\treturn args;\n}\n\nfunction typeLabel(schemaValue: unknown): string {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return \"string\";\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0 && enumValues.every((entry) => [\"string\", \"number\", \"boolean\"].includes(typeof entry))) {\n\t\treturn enumValues.map(String).join(\"|\");\n\t}\n\tconst type = schemaType(schema);\n\tif (type === \"integer\" || type === \"number\") return \"number\";\n\tif (type === \"boolean\") return \"bool\";\n\tif (type === \"array\") return `${typeLabel(schema.items)}[]`;\n\tif (type === \"object\") {\n\t\tconst properties = schemaRecord(schema.properties);\n\t\tif (!properties) return \"{}\";\n\t\tconst entries = Object.entries(properties)\n\t\t\t.slice(0, 4)\n\t\t\t.map(([name, value]) => `${name}:${typeLabel(value)}`);\n\t\tconst suffix = Object.keys(properties).length > entries.length ? \",...\" : \"\";\n\t\treturn `{${entries.join(\",\")}${suffix}}`;\n\t}\n\treturn \"string\";\n}\n\nfunction orderedPropertyNames(properties: Record<string, unknown>, required: readonly string[]): string[] {\n\tconst requiredSet = new Set(required);\n\treturn [\n\t\t...required.filter((name) => name in properties),\n\t\t...Object.keys(properties).filter((name) => !requiredSet.has(name)),\n\t];\n}\n\nfunction formatDefault(value: unknown): string {\n\tconst json = JSON.stringify(value);\n\treturn json ? `=${json}` : \"\";\n}\n\nfunction formatToolProjection(tool: Tool): string {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tconst required = requiredPropertyNames(parameters);\n\tconst requiredSet = new Set(required);\n\tconst args = properties\n\t\t? orderedPropertyNames(properties, required)\n\t\t\t\t.map((name) => {\n\t\t\t\t\tconst schema = schemaRecord(properties[name]);\n\t\t\t\t\tconst optional = requiredSet.has(name) ? \"\" : \"?\";\n\t\t\t\t\tconst defaultText = schema && \"default\" in schema ? formatDefault(schema.default) : \"\";\n\t\t\t\t\treturn `${name}:${typeLabel(schema)}${optional}${defaultText}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \")\n\t\t: \"\";\n\tconst description = tool.description.replace(/\\s+/g, \" \").trim();\n\treturn `${tool.name}(${args}) - ${description}`;\n}\n\nfunction toolHasArrayParameter(tool: Tool): boolean {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return false;\n\treturn Object.values(properties).some((schemaValue) => schemaType(schemaRecord(schemaValue) ?? {}) === \"array\");\n}\n\nfunction exampleTools(tools: readonly Tool[]): Tool[] {\n\tconst examples: Tool[] = [];\n\tconst readTool = tools.find((tool) => tool.name === \"read\");\n\tif (readTool) examples.push(readTool);\n\tif (examples.length === 0) examples.push(tools[0]);\n\tconst editTool = tools.find((tool) => tool.name === \"edit\" && !examples.includes(tool));\n\tconst arrayTool = editTool ?? tools.find((tool) => !examples.includes(tool) && toolHasArrayParameter(tool));\n\tif (arrayTool) examples.push(arrayTool);\n\treturn examples;\n}\n\nfunction protocolHeader(variant: TextToolProtocolVariant): string[] {\n\treturn [\n\t\t\"Text tool-call protocol is enabled.\",\n\t\t\"When calling tools, output only one or more envelopes and no prose:\",\n\t\tformatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}'),\n\t\t\"Arguments must be valid JSON objects. Use double quotes for JSON keys and string values. Arrays are JSON arrays [ ], never quoted strings. Omit optional args you do not need - do not send null.\",\n\t\t\"User requests about files, directories, searches, edits, writes, or shell commands require a tool envelope first; do not describe results yourself.\",\n\t\t'If the user asks to read /tmp/example.txt, output exactly: <pi:call name=\"read\">{\"path\":\"/tmp/example.txt\"}</pi:call>',\n\t\t'For any request to read a file path, call read with {\"path\":\"THE_PATH\"}; never output {\"file_path\":..., \"content\":...} or invented file contents.',\n\t\t\"Never write raw shell commands such as read -t PATH, cat PATH, or ls PATH; use a tool-call envelope instead.\",\n\t\t\"Never output markdown code blocks, raw shell commands, file paths, or invented tool results instead of a tool call; use the envelope and wait for the real result.\",\n\t];\n}\n\nexport function generateTextToolProtocolPrimer(tools: readonly Tool[], options?: TextToolProtocolOptions): string {\n\tif (tools.length === 0) return \"\";\n\tconst variant = options?.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT;\n\tconst lines = [...protocolHeader(variant), \"Examples:\"];\n\tfor (const tool of exampleTools(tools)) {\n\t\tlines.push(\n\t\t\tformatVariantEnvelope(variant, tool.name, JSON.stringify(exampleArgumentsForParameters(tool.parameters))),\n\t\t);\n\t}\n\tlines.push(\"Available tools:\");\n\tfor (const tool of tools) {\n\t\tlines.push(formatToolProjection(tool));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function parseTextToolCalls(text: string, knownTools: readonly Tool[]): ParsedTextToolCalls {\n\tif (knownTools.length === 0) return { calls: [], text, attempted: false };\n\tconst matches = findToolEnvelopes(text);\n\tif (matches.length === 0) return { calls: [], text, attempted: false };\n\tif (hasOverlap(matches)) return { calls: [], text, attempted: true, failure: \"overlap\" };\n\tconst remainder = remainingText(text, matches);\n\tconst names = [...knownToolNames(knownTools)];\n\tconst calls = matches\n\t\t.map((match, index) => parseEnvelope(match, names, index + 1))\n\t\t.filter((call): call is ToolCall => call !== undefined);\n\treturn calls.length > 0\n\t\t? { calls, text: remainder.trim(), attempted: true }\n\t\t: { calls: [], text, attempted: true, failure: \"unrecognized\" };\n}\n"]}
@@ -8,10 +8,22 @@ function escapeAttribute(value) {
8
8
  function unescapeAttribute(value) {
9
9
  return value
10
10
  .replace(/&quot;/g, '"')
11
+ .replace(/&apos;/g, "'")
11
12
  .replace(/&lt;/g, "<")
12
13
  .replace(/&gt;/g, ">")
13
14
  .replace(/&amp;/g, "&");
14
15
  }
16
+ function escapeXmlText(value) {
17
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
18
+ }
19
+ function unescapeXmlText(value) {
20
+ return value
21
+ .replace(/&lt;/g, "<")
22
+ .replace(/&gt;/g, ">")
23
+ .replace(/&apos;/g, "'")
24
+ .replace(/&quot;/g, '"')
25
+ .replace(/&amp;/g, "&");
26
+ }
15
27
  function knownToolNames(tools) {
16
28
  return new Set(tools.map((tool) => tool.name));
17
29
  }
@@ -102,6 +114,16 @@ function findToolEnvelopes(text) {
102
114
  body: match[1] ?? "",
103
115
  });
104
116
  }
117
+ const functionEnvelope = /<function\s+name=(["'])(.*?)\1\s*>([\s\S]*?)<\/function\s*>/g;
118
+ for (const match of text.matchAll(functionEnvelope)) {
119
+ matches.push({
120
+ kind: "function_xml",
121
+ start: match.index,
122
+ end: match.index + match[0].length,
123
+ name: unescapeAttribute(match[2] ?? ""),
124
+ body: match[3] ?? "",
125
+ });
126
+ }
105
127
  return matches.sort((a, b) => a.start - b.start);
106
128
  }
107
129
  function hasOverlap(matches) {
@@ -215,9 +237,43 @@ function parsePiCallEnvelope(match, names, index) {
215
237
  errorMessage: textToolErrorMessage(match.name, names),
216
238
  };
217
239
  }
240
+ function parseFunctionXmlEnvelope(match, names, index) {
241
+ if (!match.name)
242
+ return undefined;
243
+ if (/<\/?function\b/i.test(match.body))
244
+ return undefined;
245
+ const params = {};
246
+ let cursor = 0;
247
+ let sawParam = false;
248
+ const paramPattern = /<param\s+name=(["'])(.*?)\1\s*>([\s\S]*?)<\/param\s*>/g;
249
+ for (const param of match.body.matchAll(paramPattern)) {
250
+ if (match.body.slice(cursor, param.index).trim())
251
+ return undefined;
252
+ const name = unescapeAttribute(param[2] ?? "");
253
+ if (!name || name in params)
254
+ return undefined;
255
+ params[name] = unescapeXmlText((param[3] ?? "").trim());
256
+ cursor = param.index + param[0].length;
257
+ sawParam = true;
258
+ }
259
+ if (match.body.slice(cursor).trim())
260
+ return undefined;
261
+ if (!sawParam)
262
+ return undefined;
263
+ return {
264
+ type: "toolCall",
265
+ id: `text-tool-${index}`,
266
+ name: match.name,
267
+ arguments: params,
268
+ source: "text-protocol",
269
+ errorMessage: textToolErrorMessage(match.name, names),
270
+ };
271
+ }
218
272
  function parseEnvelope(match, names, index) {
219
273
  if (match.kind === "pi_call")
220
274
  return parsePiCallEnvelope(match, names, index);
275
+ if (match.kind === "function_xml")
276
+ return parseFunctionXmlEnvelope(match, names, index);
221
277
  const parsed = parseJsonObject(match.body);
222
278
  if (!parsed) {
223
279
  const name = extractNameFromMalformedJson(match.body);
@@ -256,11 +312,26 @@ export function normalizeTextToolProtocolOptions(option) {
256
312
  return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };
257
313
  return { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };
258
314
  }
315
+ function functionXmlParamValue(value) {
316
+ if (typeof value === "string")
317
+ return value;
318
+ const json = JSON.stringify(value);
319
+ return json ?? String(value);
320
+ }
321
+ function formatFunctionXmlEnvelope(toolName, argsJson) {
322
+ const args = parseJsonObject(argsJson) ?? {};
323
+ const params = Object.entries(args)
324
+ .map(([name, value]) => `<param name="${escapeAttribute(name)}">${escapeXmlText(functionXmlParamValue(value))}</param>`)
325
+ .join("");
326
+ return `<function name="${escapeAttribute(toolName)}">${params}</function>`;
327
+ }
259
328
  function formatVariantEnvelope(variant, toolName, argsJson) {
260
329
  if (variant === "tool-call")
261
330
  return `<tool_call>{"name":"${toolName}","arguments":${argsJson}}</tool_call>`;
262
331
  if (variant === "fenced-json")
263
332
  return `\`\`\`tool_call\n{"name":"${toolName}","arguments":${argsJson}}\n\`\`\``;
333
+ if (variant === "function-xml")
334
+ return formatFunctionXmlEnvelope(toolName, argsJson);
264
335
  return `<pi:call name="${escapeAttribute(toolName)}">${argsJson}</pi:call>`;
265
336
  }
266
337
  function schemaRecord(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"text-protocol.js","sourceRoot":"","sources":["../../../src/utils/tool-repair/text-protocol.ts"],"names":[],"mappings":"AAgCA,MAAM,kCAAkC,GAA4B,UAAU,CAAC;AAE/E,SAAS,QAAQ,CAAC,KAAc,EAAoC;IACnE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,SAAS,eAAe,CAAC,KAAa,EAAU;IAC/C,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAAA,CACxG;AAED,SAAS,iBAAiB,CAAC,KAAa,EAAU;IACjD,OAAO,KAAK;SACV,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAAA,CACzB;AAED,SAAS,cAAc,CAAC,KAAsB,EAAe;IAC5D,OAAO,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAAA,CAC/C;AAED,SAAS,iBAAiB,CAAC,IAAY,EAAE,KAAa,EAAsB;IAC3E,IAAI,KAAK,GAAG,KAAK,CAAC;IAClB,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;QAAE,KAAK,EAAE,CAAC;IAC7C,I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,IAAI,EAAE,OAAO,EAAE,cAAc,EAAE,CAAC;AAAA,CACjE","sourcesContent":["import type { Tool, ToolCall } from \"../../types.ts\";\n\nexport type TextToolProtocolParseFailure =\n\t| \"overlap\"\n\t| \"mixed-prose\"\n\t| \"unrecognized\"\n\t| \"unknown-tool\"\n\t| \"validation-failed\";\n\nexport interface ParsedTextToolCalls {\n\tcalls: ToolCall[];\n\ttext: string;\n\tattempted: boolean;\n\tfailure?: TextToolProtocolParseFailure;\n}\n\nexport type TextToolProtocolVariant = \"tool-tag\" | \"tool-call\" | \"fenced-json\";\n\nexport interface TextToolProtocolOptions {\n\tvariant?: TextToolProtocolVariant;\n}\n\ntype EnvelopeKind = \"pi_call\" | \"tool_call\" | \"fenced_json\";\n\ninterface EnvelopeMatch {\n\tkind: EnvelopeKind;\n\tstart: number;\n\tend: number;\n\tname?: string;\n\tbody: string;\n}\n\nconst DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT: TextToolProtocolVariant = \"tool-tag\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction escapeAttribute(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction knownToolNames(tools: readonly Tool[]): Set<string> {\n\treturn new Set(tools.map((tool) => tool.name));\n}\n\nfunction findJsonObjectEnd(text: string, start: number): number | undefined {\n\tlet index = start;\n\twhile (/\\s/.test(text[index] ?? \"\")) index++;\n\tif (text[index] !== \"{\") return undefined;\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (; index < text.length; index++) {\n\t\tconst char = text[index];\n\t\tif (inString) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"{\") depth++;\n\t\tif (char === \"}\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return index + 1;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isInsideMatch(index: number, matches: readonly EnvelopeMatch[]): boolean {\n\treturn matches.some((match) => index >= match.start && index < match.end);\n}\n\nfunction findToolEnvelopes(text: string): EnvelopeMatch[] {\n\tconst matches: EnvelopeMatch[] = [];\n\tconst piCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/pi:call\\s*>/g;\n\tfor (const match of text.matchAll(piCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\tconst openPiCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>/g;\n\tfor (const match of text.matchAll(openPiCallEnvelope)) {\n\t\tif (isInsideMatch(match.index, matches)) continue;\n\t\tconst bodyStart = match.index + match[0].length;\n\t\tconst bodyEnd = findJsonObjectEnd(text, bodyStart);\n\t\tif (bodyEnd === undefined) continue;\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: bodyEnd,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: text.slice(bodyStart, bodyEnd),\n\t\t});\n\t}\n\n\tconst toolCallEnvelope = /<tool_call>([\\s\\S]*?)<\\/tool_call>/g;\n\tfor (const match of text.matchAll(toolCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"tool_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst fence = /```(?:tool|tool_call|json)\\s*\\n([\\s\\S]*?)\\n?```/gi;\n\tfor (const match of text.matchAll(fence)) {\n\t\tmatches.push({\n\t\t\tkind: \"fenced_json\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\treturn matches.sort((a, b) => a.start - b.start);\n}\n\nfunction hasOverlap(matches: readonly EnvelopeMatch[]): boolean {\n\tlet previousEnd = -1;\n\tfor (const match of matches) {\n\t\tif (match.start < previousEnd) return true;\n\t\tpreviousEnd = match.end;\n\t}\n\treturn false;\n}\n\nfunction remainingText(text: string, matches: readonly EnvelopeMatch[]): string {\n\tlet cursor = 0;\n\tconst pieces: string[] = [];\n\tfor (const match of matches) {\n\t\tpieces.push(text.slice(cursor, match.start));\n\t\tcursor = match.end;\n\t}\n\tpieces.push(text.slice(cursor));\n\treturn pieces.join(\"\");\n}\n\nfunction coerceArguments(value: unknown): {\n\targuments: Record<string, unknown>;\n\trawArguments?: Record<string, unknown>;\n} {\n\tif (isRecord(value)) return { arguments: value };\n\treturn { arguments: value as Record<string, unknown>, rawArguments: { value } };\n}\n\nfunction normalizeSingleQuotedJson(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tif (!/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/.test(trimmed)) return undefined;\n\treturn trimmed.replace(/'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g, (_match, inner: string) => {\n\t\treturn JSON.stringify(inner.replace(/\\\\'/g, \"'\"));\n\t});\n}\n\nfunction normalizeBareJsonObject(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tlet changed = false;\n\tlet normalized = trimmed.replace(\n\t\t/([{,]\\s*)([A-Za-z_][A-Za-z0-9_-]*)(\\s*:)/g,\n\t\t(_match, prefix: string, key: string, suffix: string) => {\n\t\t\tchanged = true;\n\t\t\treturn `${prefix}${JSON.stringify(key)}${suffix}`;\n\t\t},\n\t);\n\tnormalized = normalized.replace(/:\\s*([A-Za-z_./-][A-Za-z0-9_./:-]*)(?=\\s*[,}])/g, (_match, value: string) => {\n\t\tif ([\"true\", \"false\", \"null\"].includes(value)) return `:${value}`;\n\t\tchanged = true;\n\t\treturn `:${JSON.stringify(value)}`;\n\t});\n\treturn changed ? normalized : undefined;\n}\n\nfunction normalizedJsonCandidates(raw: string): string[] {\n\tconst candidates: string[] = [];\n\tconst objectEnd = findJsonObjectEnd(raw, 0);\n\tif (objectEnd !== undefined && raw.slice(objectEnd).trim()) candidates.push(raw.slice(0, objectEnd));\n\tconst singleQuoted = normalizeSingleQuotedJson(raw);\n\tif (singleQuoted) candidates.push(singleQuoted);\n\tconst bare = normalizeBareJsonObject(raw);\n\tif (bare) candidates.push(bare);\n\tconst singleQuotedBare = singleQuoted ? normalizeBareJsonObject(singleQuoted) : undefined;\n\tif (singleQuotedBare) candidates.push(singleQuotedBare);\n\treturn candidates;\n}\n\nfunction parseJsonValue(raw: string): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: JSON.parse(raw) as unknown };\n\t} catch {\n\t\tfor (const normalized of normalizedJsonCandidates(raw)) {\n\t\t\ttry {\n\t\t\t\treturn { ok: true, value: JSON.parse(normalized) as unknown };\n\t\t\t} catch {\n\t\t\t\t// Try the next bounded normalization candidate.\n\t\t\t}\n\t\t}\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseJsonObject(raw: string): Record<string, unknown> | undefined {\n\tconst parsed = parseJsonValue(raw);\n\treturn parsed.ok && isRecord(parsed.value) ? parsed.value : undefined;\n}\n\nfunction textToolErrorMessage(name: string, names: readonly string[]): string | undefined {\n\tif (names.includes(name)) return undefined;\n\treturn `Unknown tool \"${name}\". Valid tools: ${names.join(\", \")}.`;\n}\n\nfunction extractNameFromMalformedJson(raw: string): string | undefined {\n\tconst match = /\"(?:name|tool)\"\\s*:\\s*\"([^\"]+)\"/.exec(raw);\n\treturn match?.[1];\n}\n\nfunction parsePiCallEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tconst parsed = parseJsonValue(match.body);\n\tconst args = parsed.ok ? coerceArguments(parsed.value) : coerceArguments(match.body.trim());\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: args.arguments,\n\t\trawArguments: parsed.ok ? args.rawArguments : { text: match.body.trim() },\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (match.kind === \"pi_call\") return parsePiCallEnvelope(match, names, index);\n\n\tconst parsed = parseJsonObject(match.body);\n\tif (!parsed) {\n\t\tconst name = extractNameFromMalformedJson(match.body);\n\t\tif (!name) return undefined;\n\t\treturn {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `text-tool-${index}`,\n\t\t\tname,\n\t\t\targuments: match.body.trim() as unknown as Record<string, unknown>,\n\t\t\trawArguments: { text: match.body.trim() },\n\t\t\tsource: \"text-protocol\",\n\t\t\terrorMessage: textToolErrorMessage(name, names),\n\t\t};\n\t}\n\n\tconst wrappedTool = isRecord(parsed.tool) ? parsed.tool : undefined;\n\tconst nameValue = parsed.name ?? (typeof parsed.tool === \"string\" ? parsed.tool : undefined) ?? wrappedTool?.name;\n\tif (typeof nameValue !== \"string\") return undefined;\n\tconst argsValue = parsed.arguments ?? parsed.args ?? wrappedTool?.arguments ?? wrappedTool?.args ?? {};\n\tconst args = coerceArguments(argsValue);\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: nameValue,\n\t\targuments: args.arguments,\n\t\trawArguments: args.rawArguments,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(nameValue, names),\n\t};\n}\n\nexport function normalizeTextToolProtocolOptions(\n\toption: boolean | TextToolProtocolOptions | undefined,\n): TextToolProtocolOptions | undefined {\n\tif (!option) return undefined;\n\tif (option === true) return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n\treturn { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n}\n\nfunction formatVariantEnvelope(variant: TextToolProtocolVariant, toolName: string, argsJson: string): string {\n\tif (variant === \"tool-call\") return `<tool_call>{\"name\":\"${toolName}\",\"arguments\":${argsJson}}</tool_call>`;\n\tif (variant === \"fenced-json\") return `\\`\\`\\`tool_call\\n{\"name\":\"${toolName}\",\"arguments\":${argsJson}}\\n\\`\\`\\``;\n\treturn `<pi:call name=\"${escapeAttribute(toolName)}\">${argsJson}</pi:call>`;\n}\n\nfunction schemaRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined;\n}\n\nfunction firstString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction schemaType(schema: Record<string, unknown>): string | undefined {\n\tconst type = schema.type;\n\tif (typeof type === \"string\") return type;\n\tif (!Array.isArray(type)) return undefined;\n\treturn type.filter(firstString).find((entry) => entry !== \"null\");\n}\n\nfunction stringExampleForProperty(propertyName: string | undefined): string {\n\tif (propertyName === \"path\") return \"src/index.ts\";\n\tif (propertyName === \"command\") return \"echo ok\";\n\tif (propertyName === \"oldText\") return \"foo\";\n\tif (propertyName === \"newText\") return \"bar\";\n\tif (propertyName === \"content\") return \"text\";\n\treturn \"value\";\n}\n\nfunction exampleValueForSchema(schemaValue: unknown, propertyName?: string): unknown {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return stringExampleForProperty(propertyName);\n\tconst constValue = schema.const;\n\tif (constValue !== undefined) return constValue;\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0) return enumValues[0];\n\tconst defaultValue = schema.default;\n\tif (defaultValue !== undefined) return defaultValue;\n\tconst type = schemaType(schema);\n\tif (type === \"number\" || type === \"integer\") return 1;\n\tif (type === \"boolean\") return true;\n\tif (type === \"array\") return [exampleValueForSchema(schema.items, propertyName)];\n\tif (type === \"object\") return exampleArgumentsForParameters(schema);\n\treturn stringExampleForProperty(propertyName);\n}\n\nfunction requiredPropertyNames(parameters: Record<string, unknown> | undefined): string[] {\n\treturn Array.isArray(parameters?.required) ? parameters.required.filter(firstString) : [];\n}\n\nfunction exampleArgumentsForParameters(parametersValue: unknown): Record<string, unknown> {\n\tconst parameters = schemaRecord(parametersValue);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return {};\n\tconst args: Record<string, unknown> = {};\n\tfor (const name of requiredPropertyNames(parameters)) {\n\t\targs[name] = exampleValueForSchema(properties[name], name);\n\t}\n\treturn args;\n}\n\nfunction typeLabel(schemaValue: unknown): string {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return \"string\";\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0 && enumValues.every((entry) => [\"string\", \"number\", \"boolean\"].includes(typeof entry))) {\n\t\treturn enumValues.map(String).join(\"|\");\n\t}\n\tconst type = schemaType(schema);\n\tif (type === \"integer\" || type === \"number\") return \"number\";\n\tif (type === \"boolean\") return \"bool\";\n\tif (type === \"array\") return `${typeLabel(schema.items)}[]`;\n\tif (type === \"object\") {\n\t\tconst properties = schemaRecord(schema.properties);\n\t\tif (!properties) return \"{}\";\n\t\tconst entries = Object.entries(properties)\n\t\t\t.slice(0, 4)\n\t\t\t.map(([name, value]) => `${name}:${typeLabel(value)}`);\n\t\tconst suffix = Object.keys(properties).length > entries.length ? \",...\" : \"\";\n\t\treturn `{${entries.join(\",\")}${suffix}}`;\n\t}\n\treturn \"string\";\n}\n\nfunction orderedPropertyNames(properties: Record<string, unknown>, required: readonly string[]): string[] {\n\tconst requiredSet = new Set(required);\n\treturn [\n\t\t...required.filter((name) => name in properties),\n\t\t...Object.keys(properties).filter((name) => !requiredSet.has(name)),\n\t];\n}\n\nfunction formatDefault(value: unknown): string {\n\tconst json = JSON.stringify(value);\n\treturn json ? `=${json}` : \"\";\n}\n\nfunction formatToolProjection(tool: Tool): string {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tconst required = requiredPropertyNames(parameters);\n\tconst requiredSet = new Set(required);\n\tconst args = properties\n\t\t? orderedPropertyNames(properties, required)\n\t\t\t\t.map((name) => {\n\t\t\t\t\tconst schema = schemaRecord(properties[name]);\n\t\t\t\t\tconst optional = requiredSet.has(name) ? \"\" : \"?\";\n\t\t\t\t\tconst defaultText = schema && \"default\" in schema ? formatDefault(schema.default) : \"\";\n\t\t\t\t\treturn `${name}:${typeLabel(schema)}${optional}${defaultText}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \")\n\t\t: \"\";\n\tconst description = tool.description.replace(/\\s+/g, \" \").trim();\n\treturn `${tool.name}(${args}) - ${description}`;\n}\n\nfunction toolHasArrayParameter(tool: Tool): boolean {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return false;\n\treturn Object.values(properties).some((schemaValue) => schemaType(schemaRecord(schemaValue) ?? {}) === \"array\");\n}\n\nfunction exampleTools(tools: readonly Tool[]): Tool[] {\n\tconst examples: Tool[] = [];\n\tconst readTool = tools.find((tool) => tool.name === \"read\");\n\tif (readTool) examples.push(readTool);\n\tif (examples.length === 0) examples.push(tools[0]);\n\tconst editTool = tools.find((tool) => tool.name === \"edit\" && !examples.includes(tool));\n\tconst arrayTool = editTool ?? tools.find((tool) => !examples.includes(tool) && toolHasArrayParameter(tool));\n\tif (arrayTool) examples.push(arrayTool);\n\treturn examples;\n}\n\nfunction protocolHeader(variant: TextToolProtocolVariant): string[] {\n\treturn [\n\t\t\"Text tool-call protocol is enabled.\",\n\t\t\"When calling tools, output only one or more envelopes and no prose:\",\n\t\tformatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}'),\n\t\t\"Arguments must be valid JSON objects. Use double quotes for JSON keys and string values. Arrays are JSON arrays [ ], never quoted strings. Omit optional args you do not need - do not send null.\",\n\t\t\"User requests about files, directories, searches, edits, writes, or shell commands require a tool envelope first; do not describe results yourself.\",\n\t\t'If the user asks to read /tmp/example.txt, output exactly: <pi:call name=\"read\">{\"path\":\"/tmp/example.txt\"}</pi:call>',\n\t\t'For any request to read a file path, call read with {\"path\":\"THE_PATH\"}; never output {\"file_path\":..., \"content\":...} or invented file contents.',\n\t\t\"Never write raw shell commands such as read -t PATH, cat PATH, or ls PATH; use a tool-call envelope instead.\",\n\t\t\"Never output markdown code blocks, raw shell commands, file paths, or invented tool results instead of a tool call; use the envelope and wait for the real result.\",\n\t];\n}\n\nexport function generateTextToolProtocolPrimer(tools: readonly Tool[], options?: TextToolProtocolOptions): string {\n\tif (tools.length === 0) return \"\";\n\tconst variant = options?.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT;\n\tconst lines = [...protocolHeader(variant), \"Examples:\"];\n\tfor (const tool of exampleTools(tools)) {\n\t\tlines.push(\n\t\t\tformatVariantEnvelope(variant, tool.name, JSON.stringify(exampleArgumentsForParameters(tool.parameters))),\n\t\t);\n\t}\n\tlines.push(\"Available tools:\");\n\tfor (const tool of tools) {\n\t\tlines.push(formatToolProjection(tool));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function parseTextToolCalls(text: string, knownTools: readonly Tool[]): ParsedTextToolCalls {\n\tif (knownTools.length === 0) return { calls: [], text, attempted: false };\n\tconst matches = findToolEnvelopes(text);\n\tif (matches.length === 0) return { calls: [], text, attempted: false };\n\tif (hasOverlap(matches)) return { calls: [], text, attempted: true, failure: \"overlap\" };\n\tconst remainder = remainingText(text, matches);\n\tconst names = [...knownToolNames(knownTools)];\n\tconst calls = matches\n\t\t.map((match, index) => parseEnvelope(match, names, index + 1))\n\t\t.filter((call): call is ToolCall => call !== undefined);\n\treturn calls.length > 0\n\t\t? { calls, text: remainder.trim(), attempted: true }\n\t\t: { calls: [], text, attempted: true, failure: \"unrecognized\" };\n}\n"]}
1
+ {"version":3,"file":"text-protocol.js","sourceRoot":"","sources":["../../../src/utils/tool-repair/text-protocol.ts"],"names":[],"mappings":"AAgCA,MAAM,kCAAkC,GAA4B,UAAU,CAAC;AAE/E,SAAS,QAAQ,CAAC,KAAc,EAAoC;IACnE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,SAAS,eAAe,CAAC,KAAa,EAAU;IAC/C,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAAA,CACxG;AAED,SAAS,iBAAiB,CAAC,KAAa,EAAU;IACjD,OAAO,KAAK;SACV,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAAA,CACzB;AAED,SAAS,aAAa,CAAC,KAAa,EAAU;IAC7C,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,I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AC;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC1E,MAAM,OAAO,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACxC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IACvE,IAAI,UAAU,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;IACzF,MAAM,SAAS,GAAG,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC/C,MAAM,KAAK,GAAG,CAAC,GAAG,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC;IAC9C,MAAM,KAAK,GAAG,OAAO;SACnB,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;SAC7D,MAAM,CAAC,CAAC,IAAI,EAAoB,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACzD,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC;QACtB,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE;QACpD,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,cAAc,EAAE,CAAC;AAAA,CACjE","sourcesContent":["import type { Tool, ToolCall } from \"../../types.ts\";\n\nexport type TextToolProtocolParseFailure =\n\t| \"overlap\"\n\t| \"mixed-prose\"\n\t| \"unrecognized\"\n\t| \"unknown-tool\"\n\t| \"validation-failed\";\n\nexport interface ParsedTextToolCalls {\n\tcalls: ToolCall[];\n\ttext: string;\n\tattempted: boolean;\n\tfailure?: TextToolProtocolParseFailure;\n}\n\nexport type TextToolProtocolVariant = \"tool-tag\" | \"tool-call\" | \"fenced-json\" | \"function-xml\";\n\nexport interface TextToolProtocolOptions {\n\tvariant?: TextToolProtocolVariant;\n}\n\ntype EnvelopeKind = \"pi_call\" | \"tool_call\" | \"fenced_json\" | \"function_xml\";\n\ninterface EnvelopeMatch {\n\tkind: EnvelopeKind;\n\tstart: number;\n\tend: number;\n\tname?: string;\n\tbody: string;\n}\n\nconst DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT: TextToolProtocolVariant = \"tool-tag\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction escapeAttribute(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction escapeXmlText(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeXmlText(value: string): string {\n\treturn value\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction knownToolNames(tools: readonly Tool[]): Set<string> {\n\treturn new Set(tools.map((tool) => tool.name));\n}\n\nfunction findJsonObjectEnd(text: string, start: number): number | undefined {\n\tlet index = start;\n\twhile (/\\s/.test(text[index] ?? \"\")) index++;\n\tif (text[index] !== \"{\") return undefined;\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (; index < text.length; index++) {\n\t\tconst char = text[index];\n\t\tif (inString) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"{\") depth++;\n\t\tif (char === \"}\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return index + 1;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isInsideMatch(index: number, matches: readonly EnvelopeMatch[]): boolean {\n\treturn matches.some((match) => index >= match.start && index < match.end);\n}\n\nfunction findToolEnvelopes(text: string): EnvelopeMatch[] {\n\tconst matches: EnvelopeMatch[] = [];\n\tconst piCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/pi:call\\s*>/g;\n\tfor (const match of text.matchAll(piCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\tconst openPiCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>/g;\n\tfor (const match of text.matchAll(openPiCallEnvelope)) {\n\t\tif (isInsideMatch(match.index, matches)) continue;\n\t\tconst bodyStart = match.index + match[0].length;\n\t\tconst bodyEnd = findJsonObjectEnd(text, bodyStart);\n\t\tif (bodyEnd === undefined) continue;\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: bodyEnd,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: text.slice(bodyStart, bodyEnd),\n\t\t});\n\t}\n\n\tconst toolCallEnvelope = /<tool_call>([\\s\\S]*?)<\\/tool_call>/g;\n\tfor (const match of text.matchAll(toolCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"tool_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst fence = /```(?:tool|tool_call|json)\\s*\\n([\\s\\S]*?)\\n?```/gi;\n\tfor (const match of text.matchAll(fence)) {\n\t\tmatches.push({\n\t\t\tkind: \"fenced_json\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst functionEnvelope = /<function\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/function\\s*>/g;\n\tfor (const match of text.matchAll(functionEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"function_xml\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\treturn matches.sort((a, b) => a.start - b.start);\n}\n\nfunction hasOverlap(matches: readonly EnvelopeMatch[]): boolean {\n\tlet previousEnd = -1;\n\tfor (const match of matches) {\n\t\tif (match.start < previousEnd) return true;\n\t\tpreviousEnd = match.end;\n\t}\n\treturn false;\n}\n\nfunction remainingText(text: string, matches: readonly EnvelopeMatch[]): string {\n\tlet cursor = 0;\n\tconst pieces: string[] = [];\n\tfor (const match of matches) {\n\t\tpieces.push(text.slice(cursor, match.start));\n\t\tcursor = match.end;\n\t}\n\tpieces.push(text.slice(cursor));\n\treturn pieces.join(\"\");\n}\n\nfunction coerceArguments(value: unknown): {\n\targuments: Record<string, unknown>;\n\trawArguments?: Record<string, unknown>;\n} {\n\tif (isRecord(value)) return { arguments: value };\n\treturn { arguments: value as Record<string, unknown>, rawArguments: { value } };\n}\n\nfunction normalizeSingleQuotedJson(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tif (!/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/.test(trimmed)) return undefined;\n\treturn trimmed.replace(/'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g, (_match, inner: string) => {\n\t\treturn JSON.stringify(inner.replace(/\\\\'/g, \"'\"));\n\t});\n}\n\nfunction normalizeBareJsonObject(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tlet changed = false;\n\tlet normalized = trimmed.replace(\n\t\t/([{,]\\s*)([A-Za-z_][A-Za-z0-9_-]*)(\\s*:)/g,\n\t\t(_match, prefix: string, key: string, suffix: string) => {\n\t\t\tchanged = true;\n\t\t\treturn `${prefix}${JSON.stringify(key)}${suffix}`;\n\t\t},\n\t);\n\tnormalized = normalized.replace(/:\\s*([A-Za-z_./-][A-Za-z0-9_./:-]*)(?=\\s*[,}])/g, (_match, value: string) => {\n\t\tif ([\"true\", \"false\", \"null\"].includes(value)) return `:${value}`;\n\t\tchanged = true;\n\t\treturn `:${JSON.stringify(value)}`;\n\t});\n\treturn changed ? normalized : undefined;\n}\n\nfunction normalizedJsonCandidates(raw: string): string[] {\n\tconst candidates: string[] = [];\n\tconst objectEnd = findJsonObjectEnd(raw, 0);\n\tif (objectEnd !== undefined && raw.slice(objectEnd).trim()) candidates.push(raw.slice(0, objectEnd));\n\tconst singleQuoted = normalizeSingleQuotedJson(raw);\n\tif (singleQuoted) candidates.push(singleQuoted);\n\tconst bare = normalizeBareJsonObject(raw);\n\tif (bare) candidates.push(bare);\n\tconst singleQuotedBare = singleQuoted ? normalizeBareJsonObject(singleQuoted) : undefined;\n\tif (singleQuotedBare) candidates.push(singleQuotedBare);\n\treturn candidates;\n}\n\nfunction parseJsonValue(raw: string): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: JSON.parse(raw) as unknown };\n\t} catch {\n\t\tfor (const normalized of normalizedJsonCandidates(raw)) {\n\t\t\ttry {\n\t\t\t\treturn { ok: true, value: JSON.parse(normalized) as unknown };\n\t\t\t} catch {\n\t\t\t\t// Try the next bounded normalization candidate.\n\t\t\t}\n\t\t}\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseJsonObject(raw: string): Record<string, unknown> | undefined {\n\tconst parsed = parseJsonValue(raw);\n\treturn parsed.ok && isRecord(parsed.value) ? parsed.value : undefined;\n}\n\nfunction textToolErrorMessage(name: string, names: readonly string[]): string | undefined {\n\tif (names.includes(name)) return undefined;\n\treturn `Unknown tool \"${name}\". Valid tools: ${names.join(\", \")}.`;\n}\n\nfunction extractNameFromMalformedJson(raw: string): string | undefined {\n\tconst match = /\"(?:name|tool)\"\\s*:\\s*\"([^\"]+)\"/.exec(raw);\n\treturn match?.[1];\n}\n\nfunction parsePiCallEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tconst parsed = parseJsonValue(match.body);\n\tconst args = parsed.ok ? coerceArguments(parsed.value) : coerceArguments(match.body.trim());\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: args.arguments,\n\t\trawArguments: parsed.ok ? args.rawArguments : { text: match.body.trim() },\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseFunctionXmlEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tif (/<\\/?function\\b/i.test(match.body)) return undefined;\n\tconst params: Record<string, string> = {};\n\tlet cursor = 0;\n\tlet sawParam = false;\n\tconst paramPattern = /<param\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/param\\s*>/g;\n\tfor (const param of match.body.matchAll(paramPattern)) {\n\t\tif (match.body.slice(cursor, param.index).trim()) return undefined;\n\t\tconst name = unescapeAttribute(param[2] ?? \"\");\n\t\tif (!name || name in params) return undefined;\n\t\tparams[name] = unescapeXmlText((param[3] ?? \"\").trim());\n\t\tcursor = param.index + param[0].length;\n\t\tsawParam = true;\n\t}\n\tif (match.body.slice(cursor).trim()) return undefined;\n\tif (!sawParam) return undefined;\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: params,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (match.kind === \"pi_call\") return parsePiCallEnvelope(match, names, index);\n\tif (match.kind === \"function_xml\") return parseFunctionXmlEnvelope(match, names, index);\n\n\tconst parsed = parseJsonObject(match.body);\n\tif (!parsed) {\n\t\tconst name = extractNameFromMalformedJson(match.body);\n\t\tif (!name) return undefined;\n\t\treturn {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `text-tool-${index}`,\n\t\t\tname,\n\t\t\targuments: match.body.trim() as unknown as Record<string, unknown>,\n\t\t\trawArguments: { text: match.body.trim() },\n\t\t\tsource: \"text-protocol\",\n\t\t\terrorMessage: textToolErrorMessage(name, names),\n\t\t};\n\t}\n\n\tconst wrappedTool = isRecord(parsed.tool) ? parsed.tool : undefined;\n\tconst nameValue = parsed.name ?? (typeof parsed.tool === \"string\" ? parsed.tool : undefined) ?? wrappedTool?.name;\n\tif (typeof nameValue !== \"string\") return undefined;\n\tconst argsValue = parsed.arguments ?? parsed.args ?? wrappedTool?.arguments ?? wrappedTool?.args ?? {};\n\tconst args = coerceArguments(argsValue);\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: nameValue,\n\t\targuments: args.arguments,\n\t\trawArguments: args.rawArguments,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(nameValue, names),\n\t};\n}\n\nexport function normalizeTextToolProtocolOptions(\n\toption: boolean | TextToolProtocolOptions | undefined,\n): TextToolProtocolOptions | undefined {\n\tif (!option) return undefined;\n\tif (option === true) return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n\treturn { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n}\n\nfunction functionXmlParamValue(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\tconst json = JSON.stringify(value);\n\treturn json ?? String(value);\n}\n\nfunction formatFunctionXmlEnvelope(toolName: string, argsJson: string): string {\n\tconst args = parseJsonObject(argsJson) ?? {};\n\tconst params = Object.entries(args)\n\t\t.map(\n\t\t\t([name, value]) =>\n\t\t\t\t`<param name=\"${escapeAttribute(name)}\">${escapeXmlText(functionXmlParamValue(value))}</param>`,\n\t\t)\n\t\t.join(\"\");\n\treturn `<function name=\"${escapeAttribute(toolName)}\">${params}</function>`;\n}\n\nfunction formatVariantEnvelope(variant: TextToolProtocolVariant, toolName: string, argsJson: string): string {\n\tif (variant === \"tool-call\") return `<tool_call>{\"name\":\"${toolName}\",\"arguments\":${argsJson}}</tool_call>`;\n\tif (variant === \"fenced-json\") return `\\`\\`\\`tool_call\\n{\"name\":\"${toolName}\",\"arguments\":${argsJson}}\\n\\`\\`\\``;\n\tif (variant === \"function-xml\") return formatFunctionXmlEnvelope(toolName, argsJson);\n\treturn `<pi:call name=\"${escapeAttribute(toolName)}\">${argsJson}</pi:call>`;\n}\n\nfunction schemaRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined;\n}\n\nfunction firstString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction schemaType(schema: Record<string, unknown>): string | undefined {\n\tconst type = schema.type;\n\tif (typeof type === \"string\") return type;\n\tif (!Array.isArray(type)) return undefined;\n\treturn type.filter(firstString).find((entry) => entry !== \"null\");\n}\n\nfunction stringExampleForProperty(propertyName: string | undefined): string {\n\tif (propertyName === \"path\") return \"src/index.ts\";\n\tif (propertyName === \"command\") return \"echo ok\";\n\tif (propertyName === \"oldText\") return \"foo\";\n\tif (propertyName === \"newText\") return \"bar\";\n\tif (propertyName === \"content\") return \"text\";\n\treturn \"value\";\n}\n\nfunction exampleValueForSchema(schemaValue: unknown, propertyName?: string): unknown {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return stringExampleForProperty(propertyName);\n\tconst constValue = schema.const;\n\tif (constValue !== undefined) return constValue;\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0) return enumValues[0];\n\tconst defaultValue = schema.default;\n\tif (defaultValue !== undefined) return defaultValue;\n\tconst type = schemaType(schema);\n\tif (type === \"number\" || type === \"integer\") return 1;\n\tif (type === \"boolean\") return true;\n\tif (type === \"array\") return [exampleValueForSchema(schema.items, propertyName)];\n\tif (type === \"object\") return exampleArgumentsForParameters(schema);\n\treturn stringExampleForProperty(propertyName);\n}\n\nfunction requiredPropertyNames(parameters: Record<string, unknown> | undefined): string[] {\n\treturn Array.isArray(parameters?.required) ? parameters.required.filter(firstString) : [];\n}\n\nfunction exampleArgumentsForParameters(parametersValue: unknown): Record<string, unknown> {\n\tconst parameters = schemaRecord(parametersValue);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return {};\n\tconst args: Record<string, unknown> = {};\n\tfor (const name of requiredPropertyNames(parameters)) {\n\t\targs[name] = exampleValueForSchema(properties[name], name);\n\t}\n\treturn args;\n}\n\nfunction typeLabel(schemaValue: unknown): string {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return \"string\";\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0 && enumValues.every((entry) => [\"string\", \"number\", \"boolean\"].includes(typeof entry))) {\n\t\treturn enumValues.map(String).join(\"|\");\n\t}\n\tconst type = schemaType(schema);\n\tif (type === \"integer\" || type === \"number\") return \"number\";\n\tif (type === \"boolean\") return \"bool\";\n\tif (type === \"array\") return `${typeLabel(schema.items)}[]`;\n\tif (type === \"object\") {\n\t\tconst properties = schemaRecord(schema.properties);\n\t\tif (!properties) return \"{}\";\n\t\tconst entries = Object.entries(properties)\n\t\t\t.slice(0, 4)\n\t\t\t.map(([name, value]) => `${name}:${typeLabel(value)}`);\n\t\tconst suffix = Object.keys(properties).length > entries.length ? \",...\" : \"\";\n\t\treturn `{${entries.join(\",\")}${suffix}}`;\n\t}\n\treturn \"string\";\n}\n\nfunction orderedPropertyNames(properties: Record<string, unknown>, required: readonly string[]): string[] {\n\tconst requiredSet = new Set(required);\n\treturn [\n\t\t...required.filter((name) => name in properties),\n\t\t...Object.keys(properties).filter((name) => !requiredSet.has(name)),\n\t];\n}\n\nfunction formatDefault(value: unknown): string {\n\tconst json = JSON.stringify(value);\n\treturn json ? `=${json}` : \"\";\n}\n\nfunction formatToolProjection(tool: Tool): string {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tconst required = requiredPropertyNames(parameters);\n\tconst requiredSet = new Set(required);\n\tconst args = properties\n\t\t? orderedPropertyNames(properties, required)\n\t\t\t\t.map((name) => {\n\t\t\t\t\tconst schema = schemaRecord(properties[name]);\n\t\t\t\t\tconst optional = requiredSet.has(name) ? \"\" : \"?\";\n\t\t\t\t\tconst defaultText = schema && \"default\" in schema ? formatDefault(schema.default) : \"\";\n\t\t\t\t\treturn `${name}:${typeLabel(schema)}${optional}${defaultText}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \")\n\t\t: \"\";\n\tconst description = tool.description.replace(/\\s+/g, \" \").trim();\n\treturn `${tool.name}(${args}) - ${description}`;\n}\n\nfunction toolHasArrayParameter(tool: Tool): boolean {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return false;\n\treturn Object.values(properties).some((schemaValue) => schemaType(schemaRecord(schemaValue) ?? {}) === \"array\");\n}\n\nfunction exampleTools(tools: readonly Tool[]): Tool[] {\n\tconst examples: Tool[] = [];\n\tconst readTool = tools.find((tool) => tool.name === \"read\");\n\tif (readTool) examples.push(readTool);\n\tif (examples.length === 0) examples.push(tools[0]);\n\tconst editTool = tools.find((tool) => tool.name === \"edit\" && !examples.includes(tool));\n\tconst arrayTool = editTool ?? tools.find((tool) => !examples.includes(tool) && toolHasArrayParameter(tool));\n\tif (arrayTool) examples.push(arrayTool);\n\treturn examples;\n}\n\nfunction protocolHeader(variant: TextToolProtocolVariant): string[] {\n\treturn [\n\t\t\"Text tool-call protocol is enabled.\",\n\t\t\"When calling tools, output only one or more envelopes and no prose:\",\n\t\tformatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}'),\n\t\t\"Arguments must be valid JSON objects. Use double quotes for JSON keys and string values. Arrays are JSON arrays [ ], never quoted strings. Omit optional args you do not need - do not send null.\",\n\t\t\"User requests about files, directories, searches, edits, writes, or shell commands require a tool envelope first; do not describe results yourself.\",\n\t\t'If the user asks to read /tmp/example.txt, output exactly: <pi:call name=\"read\">{\"path\":\"/tmp/example.txt\"}</pi:call>',\n\t\t'For any request to read a file path, call read with {\"path\":\"THE_PATH\"}; never output {\"file_path\":..., \"content\":...} or invented file contents.',\n\t\t\"Never write raw shell commands such as read -t PATH, cat PATH, or ls PATH; use a tool-call envelope instead.\",\n\t\t\"Never output markdown code blocks, raw shell commands, file paths, or invented tool results instead of a tool call; use the envelope and wait for the real result.\",\n\t];\n}\n\nexport function generateTextToolProtocolPrimer(tools: readonly Tool[], options?: TextToolProtocolOptions): string {\n\tif (tools.length === 0) return \"\";\n\tconst variant = options?.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT;\n\tconst lines = [...protocolHeader(variant), \"Examples:\"];\n\tfor (const tool of exampleTools(tools)) {\n\t\tlines.push(\n\t\t\tformatVariantEnvelope(variant, tool.name, JSON.stringify(exampleArgumentsForParameters(tool.parameters))),\n\t\t);\n\t}\n\tlines.push(\"Available tools:\");\n\tfor (const tool of tools) {\n\t\tlines.push(formatToolProjection(tool));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function parseTextToolCalls(text: string, knownTools: readonly Tool[]): ParsedTextToolCalls {\n\tif (knownTools.length === 0) return { calls: [], text, attempted: false };\n\tconst matches = findToolEnvelopes(text);\n\tif (matches.length === 0) return { calls: [], text, attempted: false };\n\tif (hasOverlap(matches)) return { calls: [], text, attempted: true, failure: \"overlap\" };\n\tconst remainder = remainingText(text, matches);\n\tconst names = [...knownToolNames(knownTools)];\n\tconst calls = matches\n\t\t.map((match, index) => parseEnvelope(match, names, index + 1))\n\t\t.filter((call): call is ToolCall => call !== undefined);\n\treturn calls.length > 0\n\t\t? { calls, text: remainder.trim(), attempted: true }\n\t\t: { calls: [], text, attempted: true, failure: \"unrecognized\" };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caupulican/pi-ai",
3
- "version": "0.81.15",
3
+ "version": "0.81.16",
4
4
  "description": "Unified LLM API with automatic model discovery and provider configuration",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",