@cloudflare/tanstack-ai 0.1.2 → 0.1.4

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.
Files changed (70) hide show
  1. package/README.md +42 -0
  2. package/dist/_tsup-dts-rollup.d.cts +13 -4
  3. package/dist/_tsup-dts-rollup.d.ts +13 -4
  4. package/dist/adapters/anthropic.cjs +3 -3
  5. package/dist/adapters/anthropic.js +2 -2
  6. package/dist/adapters/grok.cjs +3 -3
  7. package/dist/adapters/grok.js +2 -2
  8. package/dist/adapters/openai.cjs +3 -3
  9. package/dist/adapters/openai.js +2 -2
  10. package/dist/adapters/openrouter.cjs +3 -3
  11. package/dist/adapters/openrouter.js +2 -2
  12. package/dist/adapters/workers-ai-image.cjs +3 -3
  13. package/dist/adapters/workers-ai-image.js +2 -2
  14. package/dist/adapters/workers-ai-summarize.cjs +3 -3
  15. package/dist/adapters/workers-ai-summarize.js +2 -2
  16. package/dist/adapters/workers-ai-transcription.cjs +3 -3
  17. package/dist/adapters/workers-ai-transcription.js +2 -2
  18. package/dist/adapters/workers-ai-tts.cjs +3 -3
  19. package/dist/adapters/workers-ai-tts.js +2 -2
  20. package/dist/adapters/workers-ai.cjs +3 -3
  21. package/dist/adapters/workers-ai.js +2 -2
  22. package/dist/{chunk-LG2I3ANT.cjs → chunk-32U73O6E.cjs} +49 -33
  23. package/dist/chunk-32U73O6E.cjs.map +1 -0
  24. package/dist/{chunk-ZHTFBZXJ.cjs → chunk-3PJHW45X.cjs} +6 -6
  25. package/dist/{chunk-ZHTFBZXJ.cjs.map → chunk-3PJHW45X.cjs.map} +1 -1
  26. package/dist/{chunk-T5KPTTLK.js → chunk-DG46OSFY.js} +2 -2
  27. package/dist/{chunk-IDPLTBQX.cjs → chunk-H24HFVUJ.cjs} +6 -6
  28. package/dist/{chunk-IDPLTBQX.cjs.map → chunk-H24HFVUJ.cjs.map} +1 -1
  29. package/dist/{chunk-JK5ZFOZZ.js → chunk-I2MCLFJ5.js} +2 -2
  30. package/dist/{chunk-OKU3GB5P.js → chunk-IPEZXCDR.js} +2 -2
  31. package/dist/{chunk-ARLHMZ5B.cjs → chunk-KDVHOUEP.cjs} +6 -6
  32. package/dist/{chunk-ARLHMZ5B.cjs.map → chunk-KDVHOUEP.cjs.map} +1 -1
  33. package/dist/{chunk-UWBO33IG.cjs → chunk-KW27GIQL.cjs} +5 -5
  34. package/dist/{chunk-UWBO33IG.cjs.map → chunk-KW27GIQL.cjs.map} +1 -1
  35. package/dist/{chunk-7KZQWFUE.cjs → chunk-MMTLH53H.cjs} +3 -3
  36. package/dist/chunk-MMTLH53H.cjs.map +1 -0
  37. package/dist/{chunk-DSBHOQQ4.js → chunk-MOAWHNNP.js} +2 -2
  38. package/dist/chunk-MOAWHNNP.js.map +1 -0
  39. package/dist/{chunk-3KUHT3K6.js → chunk-NSWLVANP.js} +46 -30
  40. package/dist/chunk-NSWLVANP.js.map +1 -0
  41. package/dist/{chunk-Y7W7NDVS.js → chunk-OGAH3FYW.js} +2 -2
  42. package/dist/{chunk-2QN5XFI2.js → chunk-QMRONSLN.js} +2 -2
  43. package/dist/{chunk-5A2F2QCL.js → chunk-RWLCEKT6.js} +2 -2
  44. package/dist/{chunk-O7MBRPCW.js → chunk-S5QBHI6O.js} +26 -29
  45. package/dist/chunk-S5QBHI6O.js.map +1 -0
  46. package/dist/{chunk-ICHJ2G63.cjs → chunk-TG4UQPGB.cjs} +3 -3
  47. package/dist/{chunk-ICHJ2G63.cjs.map → chunk-TG4UQPGB.cjs.map} +1 -1
  48. package/dist/{chunk-7SKFZ4SU.cjs → chunk-U2PMR3PT.cjs} +5 -5
  49. package/dist/{chunk-7SKFZ4SU.cjs.map → chunk-U2PMR3PT.cjs.map} +1 -1
  50. package/dist/{chunk-IMURYJRF.cjs → chunk-U5NL4EM4.cjs} +33 -36
  51. package/dist/chunk-U5NL4EM4.cjs.map +1 -0
  52. package/dist/{chunk-AYTKQRE4.cjs → chunk-XFQ3QESX.cjs} +6 -6
  53. package/dist/{chunk-AYTKQRE4.cjs.map → chunk-XFQ3QESX.cjs.map} +1 -1
  54. package/dist/{chunk-DZZVI4W5.js → chunk-ZJMMBD6H.js} +2 -2
  55. package/dist/index.cjs +11 -11
  56. package/dist/index.js +10 -10
  57. package/package.json +11 -10
  58. package/dist/chunk-3KUHT3K6.js.map +0 -1
  59. package/dist/chunk-7KZQWFUE.cjs.map +0 -1
  60. package/dist/chunk-DSBHOQQ4.js.map +0 -1
  61. package/dist/chunk-IMURYJRF.cjs.map +0 -1
  62. package/dist/chunk-LG2I3ANT.cjs.map +0 -1
  63. package/dist/chunk-O7MBRPCW.js.map +0 -1
  64. /package/dist/{chunk-T5KPTTLK.js.map → chunk-DG46OSFY.js.map} +0 -0
  65. /package/dist/{chunk-JK5ZFOZZ.js.map → chunk-I2MCLFJ5.js.map} +0 -0
  66. /package/dist/{chunk-OKU3GB5P.js.map → chunk-IPEZXCDR.js.map} +0 -0
  67. /package/dist/{chunk-Y7W7NDVS.js.map → chunk-OGAH3FYW.js.map} +0 -0
  68. /package/dist/{chunk-2QN5XFI2.js.map → chunk-QMRONSLN.js.map} +0 -0
  69. /package/dist/{chunk-5A2F2QCL.js.map → chunk-RWLCEKT6.js.map} +0 -0
  70. /package/dist/{chunk-DZZVI4W5.js.map → chunk-ZJMMBD6H.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/workers-ai.ts"],"sourcesContent":["import type { AiModels, BaseAiTextGeneration } from \"@cloudflare/workers-types\";\nimport type { StreamChunk, TextOptions } from \"@tanstack/ai\";\nimport {\n\tBaseTextAdapter,\n\ttype StructuredOutputOptions,\n\ttype StructuredOutputResult,\n} from \"@tanstack/ai/adapters\";\nimport OpenAI from \"openai\";\nimport {\n\ttype WorkersAiAdapterConfig,\n\ttype AiGatewayAdapterConfig,\n\tcreateGatewayFetch,\n\tcreateWorkersAiBindingFetch,\n\tisDirectBindingConfig,\n\tisDirectCredentialsConfig,\n\tvalidateWorkersAiConfig,\n} from \"../utils/create-fetcher\";\n\n// ---------------------------------------------------------------------------\n// Model types derived from @cloudflare/workers-types\n// ---------------------------------------------------------------------------\n\nexport type WorkersAiTextModel =\n\t| {\n\t\t\t[K in keyof AiModels]: AiModels[K] extends BaseAiTextGeneration ? K : never;\n\t }[keyof AiModels]\n\t| (string & {});\n\n// ---------------------------------------------------------------------------\n// Helpers: build the right OpenAI client depending on config mode\n// ---------------------------------------------------------------------------\n\nfunction buildWorkersAiClient(config: WorkersAiAdapterConfig): OpenAI {\n\tvalidateWorkersAiConfig(config);\n\n\tif (isDirectBindingConfig(config)) {\n\t\t// Plain binding mode: shim translates OpenAI fetch calls to env.AI.run()\n\t\treturn new OpenAI({\n\t\t\tapiKey: \"unused\",\n\t\t\tfetch: createWorkersAiBindingFetch(config.binding),\n\t\t});\n\t}\n\n\tif (isDirectCredentialsConfig(config)) {\n\t\t// Plain REST mode: point OpenAI SDK at Workers AI's OpenAI-compatible endpoint\n\t\treturn new OpenAI({\n\t\t\tbaseURL: `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/ai/v1`,\n\t\t\tapiKey: config.apiKey,\n\t\t});\n\t}\n\n\t// Gateway mode (existing): use createGatewayFetch\n\tconst gatewayConfig = config as AiGatewayAdapterConfig;\n\treturn new OpenAI({\n\t\tfetch: createGatewayFetch(\"workers-ai\", gatewayConfig),\n\t\tapiKey: gatewayConfig.apiKey ?? \"unused\",\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Shared message-building helpers\n// ---------------------------------------------------------------------------\n\ninterface MessageLike {\n\trole: string;\n\tcontent: string | null | Array<{ type: string; content?: string }>;\n\ttoolCalls?: Array<{\n\t\tid: string;\n\t\tfunction: { name: string; arguments: string };\n\t}>;\n\ttoolCallId?: string;\n}\n\nfunction extractTextContent(\n\tcontent: string | null | Array<{ type: string; content?: string }>,\n): string {\n\tif (content === null) return \"\";\n\tif (typeof content === \"string\") return content;\n\treturn content\n\t\t.filter((p) => p.type === \"text\")\n\t\t.map((p) => p.content || \"\")\n\t\t.join(\"\");\n}\n\n/**\n * Build OpenAI-compatible user message content, preserving image parts.\n *\n * If the content has only text parts, returns a plain string.\n * If it includes image parts, returns an array of content parts in\n * OpenAI's multi-modal format (text + image_url).\n */\nfunction buildUserContent(\n\tcontent: string | null | Array<{ type: string; content?: string; image_url?: unknown }>,\n): string | OpenAI.Chat.ChatCompletionContentPart[] {\n\tif (content === null) return \"\";\n\tif (typeof content === \"string\") return content;\n\n\tconst hasImages = content.some((p) => p.type === \"image_url\" || p.type === \"image\");\n\tif (!hasImages) {\n\t\t// No images — return plain text for simpler messages\n\t\treturn content\n\t\t\t.filter((p) => p.type === \"text\")\n\t\t\t.map((p) => p.content || \"\")\n\t\t\t.join(\"\");\n\t}\n\n\t// Multi-modal: build array of text + image_url parts\n\tconst parts: OpenAI.Chat.ChatCompletionContentPart[] = [];\n\tfor (const part of content) {\n\t\tif (part.type === \"text\" && part.content) {\n\t\t\tparts.push({ type: \"text\", text: part.content });\n\t\t} else if (part.type === \"image_url\" && part.content) {\n\t\t\tparts.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: { url: part.content },\n\t\t\t});\n\t\t} else if (part.type === \"image_url\" && part.image_url) {\n\t\t\tparts.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: part.image_url as OpenAI.Chat.ChatCompletionContentPartImage.ImageURL,\n\t\t\t});\n\t\t}\n\t}\n\treturn parts;\n}\n\nfunction buildOpenAIMessages(\n\tsystemPrompts: string[] | undefined,\n\tmessages: MessageLike[],\n\toptions?: { includeToolMessages?: boolean },\n): OpenAI.Chat.ChatCompletionMessageParam[] {\n\tconst includeTools = options?.includeToolMessages ?? true;\n\tconst openAIMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [];\n\n\tif (systemPrompts && systemPrompts.length > 0) {\n\t\topenAIMessages.push({\n\t\t\trole: \"system\",\n\t\t\tcontent: systemPrompts.join(\"\\n\"),\n\t\t});\n\t}\n\n\tfor (const message of messages) {\n\t\tif (message.role === \"user\") {\n\t\t\topenAIMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: buildUserContent(message.content),\n\t\t\t});\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst assistantMessage: OpenAI.Chat.ChatCompletionAssistantMessageParam = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: extractTextContent(message.content),\n\t\t\t};\n\t\t\tif (includeTools && message.toolCalls && message.toolCalls.length > 0) {\n\t\t\t\tassistantMessage.tool_calls = message.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: tc.function.name,\n\t\t\t\t\t\targuments: tc.function.arguments,\n\t\t\t\t\t},\n\t\t\t\t}));\n\t\t\t}\n\t\t\topenAIMessages.push(assistantMessage);\n\t\t} else if (includeTools && message.role === \"tool\") {\n\t\t\tlet toolContent: string;\n\t\t\tif (typeof message.content === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tJSON.parse(message.content);\n\t\t\t\t\ttoolContent = message.content;\n\t\t\t\t} catch {\n\t\t\t\t\ttoolContent = JSON.stringify(message.content);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttoolContent = JSON.stringify(message.content);\n\t\t\t}\n\t\t\topenAIMessages.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\ttool_call_id: message.toolCallId || `tool_${crypto.randomUUID().slice(0, 8)}`,\n\t\t\t\tcontent: toolContent,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn openAIMessages;\n}\n\nfunction buildOpenAITools(\n\ttools: Array<{ name: string; description: string; inputSchema?: unknown }> | undefined,\n): OpenAI.Chat.ChatCompletionTool[] | undefined {\n\tif (!tools) return undefined;\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\" as const,\n\t\tfunction: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.inputSchema as Record<string, unknown>,\n\t\t},\n\t}));\n}\n\n// ---------------------------------------------------------------------------\n// ID generation\n// ---------------------------------------------------------------------------\n\nfunction generateId(prefix: string): string {\n\treturn `${prefix}-${crypto.randomUUID()}`;\n}\n\n// ---------------------------------------------------------------------------\n// WorkersAiTextAdapter: chat / structured output via OpenAI Chat Completions\n// ---------------------------------------------------------------------------\n\n// TODO: Replace `any` generic params with proper types once BaseTextAdapter's\n// provider-options generics stabilize. Workers AI doesn't have provider-specific\n// options in the TanStack sense, so `any` is pragmatic for now.\nexport class WorkersAiTextAdapter<TModel extends WorkersAiTextModel> extends BaseTextAdapter<\n\tTModel,\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- BaseTextAdapter generic params are opaque\n\tany,\n\tany,\n\tany\n> {\n\tname = \"workers-ai\" as const;\n\n\tprivate client: OpenAI;\n\n\tconstructor(model: TModel, config: WorkersAiAdapterConfig) {\n\t\tsuper({ apiKey: \"unused\" }, model);\n\t\tthis.client = buildWorkersAiClient(config);\n\t}\n\n\tasync *chatStream(options: TextOptions<any>): AsyncIterable<StreamChunk> {\n\t\tconst { systemPrompts, messages, tools, temperature, model } = options;\n\n\t\tconst openAIMessages = buildOpenAIMessages(systemPrompts, messages);\n\t\tconst openAITools = buildOpenAITools(tools);\n\n\t\tconst timestamp = Date.now();\n\t\tconst runId = generateId(\"workers-ai\");\n\t\tconst messageId = generateId(\"workers-ai\");\n\t\tlet hasEmittedRunStarted = false;\n\t\tlet hasEmittedTextMessageStart = false;\n\t\tlet accumulatedContent = \"\";\n\t\tlet hasEmittedStepStarted = false;\n\t\tlet accumulatedReasoning = \"\";\n\t\tconst stepId = generateId(\"workers-ai-step\");\n\t\tlet hasReceivedFinishReason = false;\n\t\tconst toolCallsInProgress = new Map<\n\t\t\tnumber,\n\t\t\t{ id: string; name: string; arguments: string; started: boolean }\n\t\t>();\n\n\t\ttry {\n\t\t\tlet stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;\n\t\t\ttry {\n\t\t\t\tstream = await this.client.chat.completions.create({\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\tmessages: openAIMessages,\n\t\t\t\t\ttools: openAITools,\n\t\t\t\t\ttemperature,\n\t\t\t\t\tstream: true,\n\t\t\t\t\tstream_options: { include_usage: true },\n\t\t\t\t});\n\t\t\t} catch (streamError: unknown) {\n\t\t\t\t// Some models (e.g. GPT-OSS) don't support streaming via the REST API.\n\t\t\t\t// Fall back to a non-streaming call and yield the result as a single chunk.\n\t\t\t\tconsole.warn(\n\t\t\t\t\t\"[tanstack-ai] Streaming failed, falling back to non-streaming:\",\n\t\t\t\t\tstreamError instanceof Error ? streamError.message : streamError,\n\t\t\t\t);\n\t\t\t\tconst nonStreamResult = await this.client.chat.completions.create({\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\tmessages: openAIMessages,\n\t\t\t\t\ttools: openAITools,\n\t\t\t\t\ttemperature,\n\t\t\t\t});\n\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_STARTED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t} satisfies StreamChunk;\n\n\t\t\t\tconst msg = nonStreamResult.choices[0]?.message;\n\t\t\t\tif (msg?.content) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_START\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_CONTENT\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tdelta: msg.content,\n\t\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_END\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\tif (msg?.tool_calls) {\n\t\t\t\t\tfor (const tc of msg.tool_calls) {\n\t\t\t\t\t\tif (tc.type !== \"function\") continue;\n\t\t\t\t\t\tconst fn = tc.function;\n\t\t\t\t\t\tlet parsedInput: unknown = {};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tparsedInput = fn.arguments ? JSON.parse(fn.arguments) : {};\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tparsedInput = {};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TOOL_CALL_START\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: fn.name,\n\t\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TOOL_CALL_END\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: fn.name,\n\t\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst finishReason = nonStreamResult.choices[0]?.finish_reason;\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_FINISHED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t\tusage: nonStreamResult.usage\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpromptTokens: nonStreamResult.usage.prompt_tokens,\n\t\t\t\t\t\t\t\tcompletionTokens: nonStreamResult.usage.completion_tokens,\n\t\t\t\t\t\t\t\ttotalTokens: nonStreamResult.usage.total_tokens,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tfinishReason:\n\t\t\t\t\t\tfinishReason === \"tool_calls\" || finishReason === \"function_call\"\n\t\t\t\t\t\t\t? \"tool_calls\"\n\t\t\t\t\t\t\t: ((finishReason as \"stop\" | \"length\" | \"content_filter\") ?? \"stop\"),\n\t\t\t\t} satisfies StreamChunk;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tif (!chunk.choices || chunk.choices.length === 0) continue;\n\t\t\t\tconst choice = chunk.choices[0];\n\t\t\t\tif (!choice) continue;\n\n\t\t\t\t// Emit RUN_STARTED on first chunk\n\t\t\t\tif (!hasEmittedRunStarted) {\n\t\t\t\t\thasEmittedRunStarted = true;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"RUN_STARTED\",\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\tconst delta = choice.delta;\n\n\t\t\t\t// Reasoning content (used by models like QwQ, DeepSeek R1, Kimi K2.5)\n\t\t\t\t// The OpenAI SDK doesn't type this field, but models send it as an extension.\n\t\t\t\tconst reasoningContent = (delta as Record<string, unknown>).reasoning_content as\n\t\t\t\t\t| string\n\t\t\t\t\t| undefined;\n\t\t\t\tif (reasoningContent) {\n\t\t\t\t\t// RUN_STARTED is already guaranteed by the guard above\n\t\t\t\t\tif (!hasEmittedStepStarted) {\n\t\t\t\t\t\thasEmittedStepStarted = true;\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"STEP_STARTED\",\n\t\t\t\t\t\t\tstepId,\n\t\t\t\t\t\t\tstepType: \"thinking\",\n\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\t\t\t\t\taccumulatedReasoning += reasoningContent;\n\t\t\t\t\t// TODO: TanStack AI's StreamProcessor currently treats STEP_FINISHED as an\n\t\t\t\t\t// incremental reasoning event (with `delta` + accumulated `content`), so we\n\t\t\t\t\t// emit one per token. If TanStack AI adds a dedicated STEP_CONTENT event\n\t\t\t\t\t// type, this should be updated to emit STEP_CONTENT per token and a single\n\t\t\t\t\t// STEP_FINISHED when reasoning ends (i.e. when the first non-reasoning\n\t\t\t\t\t// content or finish_reason arrives).\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"STEP_FINISHED\",\n\t\t\t\t\t\tstepId,\n\t\t\t\t\t\tdelta: reasoningContent,\n\t\t\t\t\t\tcontent: accumulatedReasoning,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\t// Text content\n\t\t\t\tif (delta.content) {\n\t\t\t\t\tif (!hasEmittedTextMessageStart) {\n\t\t\t\t\t\thasEmittedTextMessageStart = true;\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TEXT_MESSAGE_START\",\n\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\n\t\t\t\t\taccumulatedContent += delta.content;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_CONTENT\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tdelta: delta.content,\n\t\t\t\t\t\tcontent: accumulatedContent,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\t// Tool calls\n\t\t\t\tif (delta.tool_calls) {\n\t\t\t\t\tfor (const toolCallDelta of delta.tool_calls) {\n\t\t\t\t\t\tconst index = toolCallDelta.index;\n\n\t\t\t\t\t\tif (!toolCallsInProgress.has(index)) {\n\t\t\t\t\t\t\ttoolCallsInProgress.set(index, {\n\t\t\t\t\t\t\t\tid: toolCallDelta.id || \"\",\n\t\t\t\t\t\t\t\tname: toolCallDelta.function?.name || \"\",\n\t\t\t\t\t\t\t\targuments: \"\",\n\t\t\t\t\t\t\t\tstarted: false,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst toolCall = toolCallsInProgress.get(index)!;\n\n\t\t\t\t\t\tif (toolCallDelta.id) {\n\t\t\t\t\t\t\ttoolCall.id = toolCallDelta.id;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (toolCallDelta.function?.name) {\n\t\t\t\t\t\t\ttoolCall.name = toolCallDelta.function.name;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (toolCallDelta.function?.arguments) {\n\t\t\t\t\t\t\ttoolCall.arguments += toolCallDelta.function.arguments;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Emit TOOL_CALL_START once we have id and name\n\t\t\t\t\t\tif (toolCall.id && toolCall.name && !toolCall.started) {\n\t\t\t\t\t\t\ttoolCall.started = true;\n\t\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\t\ttype: \"TOOL_CALL_START\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Stream tool call arguments\n\t\t\t\t\t\tif (toolCallDelta.function?.arguments && toolCall.started) {\n\t\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\t\ttype: \"TOOL_CALL_ARGS\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\tdelta: toolCallDelta.function.arguments,\n\t\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Finish\n\t\t\t\tif (choice.finish_reason) {\n\t\t\t\t\thasReceivedFinishReason = true;\n\n\t\t\t\t\t// End tool calls\n\t\t\t\t\tif (choice.finish_reason === \"tool_calls\" || toolCallsInProgress.size > 0) {\n\t\t\t\t\t\tfor (const [, toolCall] of toolCallsInProgress) {\n\t\t\t\t\t\t\tlet parsedInput: unknown = {};\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tparsedInput = toolCall.arguments\n\t\t\t\t\t\t\t\t\t? JSON.parse(toolCall.arguments)\n\t\t\t\t\t\t\t\t\t: {};\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tparsedInput = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\t\ttype: \"TOOL_CALL_END\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst computedFinishReason =\n\t\t\t\t\t\tchoice.finish_reason === \"tool_calls\" ||\n\t\t\t\t\t\tchoice.finish_reason === \"function_call\" ||\n\t\t\t\t\t\ttoolCallsInProgress.size > 0\n\t\t\t\t\t\t\t? \"tool_calls\"\n\t\t\t\t\t\t\t: (choice.finish_reason as \"stop\" | \"length\" | \"content_filter\");\n\n\t\t\t\t\t// End text message if started\n\t\t\t\t\tif (hasEmittedTextMessageStart) {\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TEXT_MESSAGE_END\",\n\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit RUN_FINISHED\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"RUN_FINISHED\",\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tusage: chunk.usage\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tpromptTokens: chunk.usage.prompt_tokens,\n\t\t\t\t\t\t\t\t\tcompletionTokens: chunk.usage.completion_tokens,\n\t\t\t\t\t\t\t\t\ttotalTokens: chunk.usage.total_tokens,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\tfinishReason: computedFinishReason,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Premature stream termination: the stream ended without a finish_reason.\n\t\t\t// This can happen when Workers AI truncates a response or the connection drops.\n\t\t\t// Emit proper closing events so the consumer doesn't hang.\n\t\t\tif (hasEmittedRunStarted && !hasReceivedFinishReason) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t\"[tanstack-ai] Stream ended without finish_reason — possible truncation or connection drop\",\n\t\t\t\t);\n\n\t\t\t\t// Close any open tool calls\n\t\t\t\tfor (const [, toolCall] of toolCallsInProgress) {\n\t\t\t\t\tif (toolCall.started) {\n\t\t\t\t\t\tlet parsedInput: unknown = {};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tparsedInput = toolCall.arguments ? JSON.parse(toolCall.arguments) : {};\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tparsedInput = {};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TOOL_CALL_END\",\n\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Close text message if open\n\t\t\t\tif (hasEmittedTextMessageStart) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_END\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_FINISHED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t\tfinishReason: \"stop\",\n\t\t\t\t} satisfies StreamChunk;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst code =\n\t\t\t\terror instanceof Error ? (error as Error & { code?: string }).code : undefined;\n\t\t\tif (!hasEmittedRunStarted) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_STARTED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t} satisfies StreamChunk;\n\t\t\t}\n\t\t\tyield {\n\t\t\t\ttype: \"RUN_ERROR\",\n\t\t\t\trunId,\n\t\t\t\tmodel: model ?? this.model,\n\t\t\t\ttimestamp,\n\t\t\t\terror: {\n\t\t\t\t\tmessage: message || \"Unknown error\",\n\t\t\t\t\tcode,\n\t\t\t\t},\n\t\t\t} satisfies StreamChunk;\n\t\t}\n\t}\n\n\tasync structuredOutput(\n\t\toptions: StructuredOutputOptions<any>,\n\t): Promise<StructuredOutputResult<unknown>> {\n\t\tconst { outputSchema, chatOptions } = options;\n\t\tconst { systemPrompts, messages, temperature, model } = chatOptions;\n\n\t\tconst openAIMessages = buildOpenAIMessages(systemPrompts, messages, {\n\t\t\tincludeToolMessages: false,\n\t\t});\n\n\t\tconst response = await this.client.chat.completions.create({\n\t\t\tmodel: model ?? this.model,\n\t\t\tmessages: openAIMessages,\n\t\t\ttemperature,\n\t\t\tstream: false,\n\t\t\tresponse_format: {\n\t\t\t\ttype: \"json_schema\",\n\t\t\t\tjson_schema: {\n\t\t\t\t\tname: \"structured_output\",\n\t\t\t\t\tstrict: true,\n\t\t\t\t\tschema: outputSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\n\t\tconst choice = response.choices?.[0];\n\n\t\tif (!choice) {\n\t\t\tthrow new Error(\n\t\t\t\t`Workers AI structured output returned no choices: ${JSON.stringify(response)}`,\n\t\t\t);\n\t\t}\n\n\t\tconst rawContent = choice.message?.content ?? \"\";\n\n\t\t// Workers AI REST endpoint may return `content` as an already-parsed object\n\t\t// when using json_schema response format, so normalise both cases.\n\t\tlet data: unknown;\n\t\tlet rawText: string;\n\n\t\tif (typeof rawContent === \"string\") {\n\t\t\trawText = rawContent;\n\t\t\ttry {\n\t\t\t\tdata = JSON.parse(rawText);\n\t\t\t} catch {\n\t\t\t\tdata = rawText;\n\t\t\t}\n\t\t} else {\n\t\t\t// Already an object — stringify for rawText, use directly for data\n\t\t\tdata = rawContent;\n\t\t\trawText = JSON.stringify(rawContent);\n\t\t}\n\n\t\treturn { data, rawText };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\nexport function createWorkersAiChat(model: WorkersAiTextModel, config: WorkersAiAdapterConfig) {\n\treturn new WorkersAiTextAdapter(model, config);\n}\n"],"mappings":";;;;;;;;;;;;AAEA;AAAA,EACC;AAAA,OAGM;AACP,OAAO,YAAY;AAyBnB,SAAS,qBAAqB,QAAwC;AACrE,0BAAwB,MAAM;AAE9B,MAAI,sBAAsB,MAAM,GAAG;AAElC,WAAO,IAAI,OAAO;AAAA,MACjB,QAAQ;AAAA,MACR,OAAO,4BAA4B,OAAO,OAAO;AAAA,IAClD,CAAC;AAAA,EACF;AAEA,MAAI,0BAA0B,MAAM,GAAG;AAEtC,WAAO,IAAI,OAAO;AAAA,MACjB,SAAS,iDAAiD,OAAO,SAAS;AAAA,MAC1E,QAAQ,OAAO;AAAA,IAChB,CAAC;AAAA,EACF;AAGA,QAAM,gBAAgB;AACtB,SAAO,IAAI,OAAO;AAAA,IACjB,OAAO,mBAAmB,cAAc,aAAa;AAAA,IACrD,QAAQ,cAAc,UAAU;AAAA,EACjC,CAAC;AACF;AAgBA,SAAS,mBACR,SACS;AACT,MAAI,YAAY,KAAM,QAAO;AAC7B,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,SAAO,QACL,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,EAC/B,IAAI,CAAC,MAAM,EAAE,WAAW,EAAE,EAC1B,KAAK,EAAE;AACV;AASA,SAAS,iBACR,SACmD;AACnD,MAAI,YAAY,KAAM,QAAO;AAC7B,MAAI,OAAO,YAAY,SAAU,QAAO;AAExC,QAAM,YAAY,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,SAAS,OAAO;AAClF,MAAI,CAAC,WAAW;AAEf,WAAO,QACL,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,EAC/B,IAAI,CAAC,MAAM,EAAE,WAAW,EAAE,EAC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P,gBAAU,KAAK,UAAU,UAAU;AAAA,IACpC;AAEA,WAAO,EAAE,MAAM,QAAQ;AAAA,EACxB;AACD;AAMO,SAAS,oBAAoB,OAA2B,QAAgC;AAC9F,SAAO,IAAI,qBAAqB,OAAO,MAAM;AAC9C;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-7KZQWFUE.cjs","../src/adapters/anthropic.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA;AACC;AACA;AACA;AAAA,qDAEM;AAMP,SAAS,oBAAA,CAAqB,MAAA,EAAgC;AAC7D,EAAA,OAAO;AAAA,IACN,MAAA,mBAAQ,MAAA,CAAO,MAAA,UAAU,UAAA;AAAA,IACzB,KAAA,EAAO,kDAAA,WAAmB,EAAa,MAAA,EAAQ;AAAA,MAC9C,mBAAA,mBAAqB,MAAA,CAAO,gBAAA,UAAoB;AAAA,IACjD,CAAC;AAAA,EACF,CAAA;AACD;AASO,SAAS,mBAAA,CACf,KAAA,EACA,MAAA,EACiB;AACjB,EAAA,OAAO,IAAI,sCAAA,CAAqB,oBAAA,CAAqB,MAAM,CAAA,EAAG,KAAK,CAAA;AACpE;AAMO,SAAS,wBAAA,CACf,KAAA,EACA,MAAA,EACC;AACD,EAAA,OAAO,IAAI,2CAAA,CAA0B,oBAAA,CAAqB,MAAM,CAAA,EAAG,KAAK,CAAA;AACzE;ADnBA;AACA;AACE;AACA;AACA;AACF,yKAAC","file":"/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-7KZQWFUE.cjs","sourcesContent":[null,"import {\n\tAnthropicTextAdapter,\n\tAnthropicSummarizeAdapter,\n\tANTHROPIC_MODELS,\n\ttype AnthropicChatModel,\n} from \"@tanstack/ai-anthropic\";\nimport type { AnyTextAdapter } from \"@tanstack/ai\";\nimport { createGatewayFetch, type AiGatewayAdapterConfig } from \"../utils/create-fetcher\";\n\nexport type AnthropicGatewayConfig = AiGatewayAdapterConfig & { anthropicVersion?: string };\n\nfunction buildAnthropicConfig(config: AnthropicGatewayConfig) {\n\treturn {\n\t\tapiKey: config.apiKey ?? \"unused\",\n\t\tfetch: createGatewayFetch(\"anthropic\", config, {\n\t\t\t\"anthropic-version\": config.anthropicVersion ?? \"2023-06-01\",\n\t\t}),\n\t};\n}\n\n/**\n * Creates an Anthropic chat adapter which uses Cloudflare AI Gateway.\n * Supports both binding and credential-based configurations.\n *\n * Since AnthropicTextConfig extends the Anthropic SDK's ClientOptions,\n * we can inject the gateway fetch directly — no subclassing needed.\n */\nexport function createAnthropicChat(\n\tmodel: AnthropicChatModel,\n\tconfig: AnthropicGatewayConfig,\n): AnyTextAdapter {\n\treturn new AnthropicTextAdapter(buildAnthropicConfig(config), model);\n}\n\n/**\n * Creates an Anthropic summarize adapter which uses Cloudflare AI Gateway.\n * Supports both binding and credential-based configurations.\n */\nexport function createAnthropicSummarize(\n\tmodel: AnthropicChatModel,\n\tconfig: AnthropicGatewayConfig,\n) {\n\treturn new AnthropicSummarizeAdapter(buildAnthropicConfig(config), model);\n}\n\nexport { ANTHROPIC_MODELS, type AnthropicChatModel };\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/anthropic.ts"],"sourcesContent":["import {\n\tAnthropicTextAdapter,\n\tAnthropicSummarizeAdapter,\n\tANTHROPIC_MODELS,\n\ttype AnthropicChatModel,\n} from \"@tanstack/ai-anthropic\";\nimport type { AnyTextAdapter } from \"@tanstack/ai\";\nimport { createGatewayFetch, type AiGatewayAdapterConfig } from \"../utils/create-fetcher\";\n\nexport type AnthropicGatewayConfig = AiGatewayAdapterConfig & { anthropicVersion?: string };\n\nfunction buildAnthropicConfig(config: AnthropicGatewayConfig) {\n\treturn {\n\t\tapiKey: config.apiKey ?? \"unused\",\n\t\tfetch: createGatewayFetch(\"anthropic\", config, {\n\t\t\t\"anthropic-version\": config.anthropicVersion ?? \"2023-06-01\",\n\t\t}),\n\t};\n}\n\n/**\n * Creates an Anthropic chat adapter which uses Cloudflare AI Gateway.\n * Supports both binding and credential-based configurations.\n *\n * Since AnthropicTextConfig extends the Anthropic SDK's ClientOptions,\n * we can inject the gateway fetch directly — no subclassing needed.\n */\nexport function createAnthropicChat(\n\tmodel: AnthropicChatModel,\n\tconfig: AnthropicGatewayConfig,\n): AnyTextAdapter {\n\treturn new AnthropicTextAdapter(buildAnthropicConfig(config), model);\n}\n\n/**\n * Creates an Anthropic summarize adapter which uses Cloudflare AI Gateway.\n * Supports both binding and credential-based configurations.\n */\nexport function createAnthropicSummarize(\n\tmodel: AnthropicChatModel,\n\tconfig: AnthropicGatewayConfig,\n) {\n\treturn new AnthropicSummarizeAdapter(buildAnthropicConfig(config), model);\n}\n\nexport { ANTHROPIC_MODELS, type AnthropicChatModel };\n"],"mappings":";;;;;AAAA;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,OAEM;AAMP,SAAS,qBAAqB,QAAgC;AAC7D,SAAO;AAAA,IACN,QAAQ,OAAO,UAAU;AAAA,IACzB,OAAO,mBAAmB,aAAa,QAAQ;AAAA,MAC9C,qBAAqB,OAAO,oBAAoB;AAAA,IACjD,CAAC;AAAA,EACF;AACD;AASO,SAAS,oBACf,OACA,QACiB;AACjB,SAAO,IAAI,qBAAqB,qBAAqB,MAAM,GAAG,KAAK;AACpE;AAMO,SAAS,yBACf,OACA,QACC;AACD,SAAO,IAAI,0BAA0B,qBAAqB,MAAM,GAAG,KAAK;AACzE;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-IMURYJRF.cjs","../src/utils/create-fetcher.ts"],"names":[],"mappings":"AAAA;ACqHO,SAAS,qBAAA,CACf,MAAA,EACyC;AAGzC,EAAA,OACC,UAAA,GAAa,OAAA,GACb,OAAQ,MAAA,CAAO,OAAA,CAA+C,QAAA,IAAY,UAAA;AAE5E;AAGO,SAAS,yBAAA,CACf,MAAA,EAC6C;AAC7C,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;AACX,oBAAA;AAGpB,sBAAA;AAEL,oBAAA;AACM,kBAAA;AACN,oBAAA;AACD,kBAAA;AACD,gBAAA;AAEkB,gBAAA;AACb,kBAAA;AACI,kBAAA;AACR,kBAAA;AACA,kBAAA;AACS,kBAAA;AACR,oBAAA;AACQ,sBAAA;AAC8B,sBAAA;AACtB,sBAAA;AAChB,oBAAA;AACD,kBAAA;AACD,gBAAA;AACW,gBAAA;AAC6B,kBAAA;AAAU;AAAM;AACxD,gBAAA;AACD,cAAA;AACD,YAAA;AACW,UAAA;AAEE,YAAA;AACd,UAAA;AACD,QAAA;AACD,MAAA;AACkB,MAAA;AACI,QAAA;AAED,UAAA;AACd,YAAA;AACI,YAAA;AACR,YAAA;AACA,YAAA;AACS,YAAA;AACR,cAAA;AACQ,gBAAA;AACC,gBAAA;AACqC,gBAAA;AAC9C,cAAA;AACD,YAAA;AACD,UAAA;AACgD,UAAA;AAAqB;AAAO;AAC7E,QAAA;AAGqD,QAAA;AACtD,MAAA;AACA,IAAA;AACF,EAAA;AACD;ADhUiE;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-IMURYJRF.cjs","sourcesContent":[null,"// ---------------------------------------------------------------------------\n// AI Gateway types (for third-party providers + Workers AI through gateway)\n// ---------------------------------------------------------------------------\n\nexport interface CloudflareAiGateway {\n\trun(request: unknown): Promise<Response>;\n}\n\nexport interface AiGatewayBindingConfig {\n\t/**\n\t * The AI Gateway binding\n\t * @example\n\t * env.AI.gateway('my-gateway-id')\n\t */\n\tbinding: CloudflareAiGateway;\n\t/**\n\t * The Provider API Key if you want to manually pass it, ignore if using Unified Billing or BYOK.\n\t */\n\tapiKey?: string;\n}\n\nexport type AiGatewayCredentialsConfig = {\n\t/**\n\t * The Cloudflare account ID\n\t */\n\taccountId: string;\n\t/**\n\t * The AI Gateway ID\n\t */\n\tgatewayId: string;\n} & (\n\t| {\n\t\t\t/** Cloudflare API Key for AI Gateway */\n\t\t\tcfApiKey: string;\n\t\t\tapiKey?: string;\n\t }\n\t| {\n\t\t\t/** Provider API Key */\n\t\t\tapiKey: string;\n\t\t\t/** Cloudflare API Key for AI Gateway */\n\t\t\tcfApiKey?: string;\n\t }\n);\n\nexport interface AiGatewayConfig {\n\tskipCache?: boolean;\n\tcacheTtl?: number;\n\tcustomCacheKey?: string;\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type AiGatewayAdapterConfig = (AiGatewayBindingConfig | AiGatewayCredentialsConfig) &\n\tAiGatewayConfig;\n\n// ---------------------------------------------------------------------------\n// Plain Workers AI types (direct binding or REST, no gateway)\n// ---------------------------------------------------------------------------\n\n/**\n * The Workers AI binding interface (env.AI).\n * Accepts a model name and inputs, returns results directly.\n * Includes `gateway()` which is present on `env.AI` but not on `env.AI.gateway(id)`,\n * enabling structural discrimination from `CloudflareAiGateway`.\n */\nexport interface WorkersAiBinding {\n\trun(\n\t\tmodel: string,\n\t\tinputs: Record<string, unknown>,\n\t\toptions?: Record<string, unknown>,\n\t): Promise<unknown>;\n\tgateway(gatewayId: string): CloudflareAiGateway;\n}\n\nexport interface WorkersAiDirectBindingConfig {\n\t/**\n\t * The Workers AI binding (env.AI).\n\t * @example\n\t * { binding: env.AI }\n\t */\n\tbinding: WorkersAiBinding;\n}\n\nexport interface WorkersAiDirectCredentialsConfig {\n\t/**\n\t * The Cloudflare account ID\n\t */\n\taccountId: string;\n\t/**\n\t * The Cloudflare API key for Workers AI\n\t */\n\tapiKey: string;\n}\n\n/**\n * Config for Workers AI adapters. Supports four modes:\n * - Plain binding: `{ binding: env.AI }`\n * - Plain REST: `{ accountId, apiKey }`\n * - AI Gateway binding: `{ binding: env.AI.gateway(id) }`\n * - AI Gateway REST: `{ accountId, gatewayId, ... }`\n *\n * The third union member intersects `AiGatewayAdapterConfig` with `{ apiKey?: string }`.\n * For the gateway binding variant, `AiGatewayBindingConfig` already includes `apiKey?`,\n * so the intersection is redundant there. For the gateway credentials variant, this\n * `apiKey` represents the Workers AI token (used in the `Authorization` header to the\n * upstream provider), distinct from `cfApiKey` (used in the `cf-aig-authorization`\n * header for authenticated gateways).\n */\nexport type WorkersAiAdapterConfig =\n\t| WorkersAiDirectBindingConfig\n\t| WorkersAiDirectCredentialsConfig\n\t| (AiGatewayAdapterConfig & { apiKey?: string });\n\n// ---------------------------------------------------------------------------\n// Config detection helpers\n// ---------------------------------------------------------------------------\n\n/** Returns true if this is a plain Workers AI binding config (`{ binding: env.AI }`) */\nexport function isDirectBindingConfig(\n\tconfig: WorkersAiAdapterConfig,\n): config is WorkersAiDirectBindingConfig {\n\t// env.AI has a .gateway() method; env.AI.gateway(id) does not.\n\t// This distinguishes direct bindings from AI Gateway bindings.\n\treturn (\n\t\t\"binding\" in config &&\n\t\ttypeof (config.binding as unknown as Record<string, unknown>).gateway === \"function\"\n\t);\n}\n\n/** Returns true if this is a plain Workers AI REST config (accountId + apiKey, no gatewayId) */\nexport function isDirectCredentialsConfig(\n\tconfig: WorkersAiAdapterConfig,\n): config is WorkersAiDirectCredentialsConfig {\n\treturn \"accountId\" in config && \"apiKey\" in config && !(\"gatewayId\" in config);\n}\n\n/** Returns true if this is an AI Gateway config (has gateway binding or `gatewayId`) */\nexport function isGatewayConfig(config: WorkersAiAdapterConfig): config is AiGatewayAdapterConfig {\n\tif (\"gatewayId\" in config) return true;\n\t// Has `binding` but NOT a direct Workers AI binding (no .gateway method)\n\treturn \"binding\" in config && !isDirectBindingConfig(config);\n}\n\n// ---------------------------------------------------------------------------\n// Config validation\n// ---------------------------------------------------------------------------\n\n/**\n * Validates that a WorkersAiAdapterConfig contains a valid configuration.\n * Throws an error if neither a binding, credentials (accountId + apiKey),\n * nor a gateway configuration is provided.\n */\nexport function validateWorkersAiConfig(config: WorkersAiAdapterConfig): void {\n\tif (\n\t\t!isDirectBindingConfig(config) &&\n\t\t!isDirectCredentialsConfig(config) &&\n\t\t!isGatewayConfig(config)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Invalid Workers AI configuration: you must provide either a binding (e.g. { binding: env.AI }), \" +\n\t\t\t\t\"credentials ({ accountId, apiKey }), or a gateway configuration ({ binding: env.AI.gateway(id) } \" +\n\t\t\t\t\"or { accountId, gatewayId }).\",\n\t\t);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// createGatewayFetch -- for routing through AI Gateway\n// ---------------------------------------------------------------------------\n\nexport function createGatewayFetch(\n\tprovider: string,\n\tconfig: AiGatewayAdapterConfig,\n\theaders: Record<string, string> = {},\n): typeof fetch {\n\treturn (input, init) => {\n\t\tlet query: Record<string, unknown> = {};\n\n\t\tconst url =\n\t\t\ttypeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\t\tconst urlObj = new URL(url);\n\n\t\t// Extract endpoint path (remove /v1/ prefix if present)\n\t\tconst endpoint = urlObj.pathname.replace(/^\\/v1\\//, \"\").replace(/^\\//, \"\") + urlObj.search;\n\n\t\tif (init?.body) {\n\t\t\ttry {\n\t\t\t\tquery = JSON.parse(init.body as string);\n\t\t\t} catch {\n\t\t\t\tquery = { _raw: init.body };\n\t\t\t}\n\t\t}\n\n\t\tconst cacheHeaders: Record<string, string> = {};\n\n\t\tif (\"skipCache\" in config && config.skipCache) {\n\t\t\tcacheHeaders[\"cf-aig-skip-cache\"] = \"true\";\n\t\t}\n\n\t\tif (typeof config.cacheTtl === \"number\") {\n\t\t\tcacheHeaders[\"cf-aig-cache-ttl\"] = String(config.cacheTtl);\n\t\t}\n\n\t\tif (typeof config.customCacheKey === \"string\") {\n\t\t\tcacheHeaders[\"cf-aig-cache-key\"] = config.customCacheKey;\n\t\t}\n\n\t\tif (typeof config.metadata === \"object\") {\n\t\t\tcacheHeaders[\"cf-aig-metadata\"] = JSON.stringify(config.metadata);\n\t\t}\n\n\t\tconst request: {\n\t\t\tprovider: string;\n\t\t\tendpoint: string;\n\t\t\theaders: Record<string, string>;\n\t\t\tquery: Record<string, unknown>;\n\t\t} = {\n\t\t\tprovider,\n\t\t\tendpoint,\n\t\t\theaders: {\n\t\t\t\t...(init?.headers as Record<string, string> | undefined),\n\t\t\t\t...headers,\n\t\t\t\t...cacheHeaders,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tquery,\n\t\t};\n\n\t\tif (provider === \"workers-ai\") {\n\t\t\trequest.endpoint = query.model as string;\n\t\t\tdelete query.model;\n\t\t\tdelete query.instructions;\n\t\t}\n\n\t\tif (config.apiKey) {\n\t\t\trequest.headers[\"authorization\"] = `Bearer ${config.apiKey}`;\n\t\t}\n\n\t\tif (\"binding\" in config) {\n\t\t\treturn config.binding.run(request);\n\t\t}\n\n\t\treturn fetch(\n\t\t\t`https://gateway.ai.cloudflare.com/v1/${config.accountId}/${config.gatewayId}`,\n\t\t\t{\n\t\t\t\t...init,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...headers,\n\t\t\t\t\t...cacheHeaders,\n\t\t\t\t\t...(config.cfApiKey\n\t\t\t\t\t\t? { \"cf-aig-authorization\": `Bearer ${config.cfApiKey}` }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(request),\n\t\t\t},\n\t\t);\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// createWorkersAiBindingFetch -- shim that makes env.AI look like an OpenAI endpoint\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize messages before passing to Workers AI binding.\n *\n * The binding has strict schema validation that may differ from the OpenAI API:\n * - `content` must be a string (not null)\n * - `tool_call_id` must match `[a-zA-Z0-9]{9}` pattern\n *\n * This function patches these fields so that the full tool-call round-trip works\n * even though the binding's own generated IDs may not pass its validation.\n */\nfunction normalizeMessagesForBinding(\n\tmessages: Record<string, unknown>[],\n): Record<string, unknown>[] {\n\treturn messages.map((msg) => {\n\t\tconst normalized = { ...msg };\n\n\t\t// content: null → content: \"\"\n\t\tif (normalized.content === null || normalized.content === undefined) {\n\t\t\tnormalized.content = \"\";\n\t\t}\n\n\t\t// Normalize tool_call_id on tool messages\n\t\tif (normalized.tool_call_id && typeof normalized.tool_call_id === \"string\") {\n\t\t\tnormalized.tool_call_id = sanitizeToolCallId(normalized.tool_call_id);\n\t\t}\n\n\t\t// Normalize tool_calls[].id on assistant messages\n\t\tif (Array.isArray(normalized.tool_calls)) {\n\t\t\tnormalized.tool_calls = (normalized.tool_calls as Record<string, unknown>[]).map(\n\t\t\t\t(tc) => {\n\t\t\t\t\tif (tc.id && typeof tc.id === \"string\") {\n\t\t\t\t\t\treturn { ...tc, id: sanitizeToolCallId(tc.id) };\n\t\t\t\t\t}\n\t\t\t\t\treturn tc;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\treturn normalized;\n\t});\n}\n\n/**\n * Strip non-alphanumeric characters and ensure the ID is exactly 9 chars,\n * matching Workers AI's `[a-zA-Z0-9]{9}` validation pattern.\n *\n * **Why this exists:** The Workers AI binding validates `tool_call_id` with\n * a strict `[a-zA-Z0-9]{9}` regex, but it *generates* IDs like\n * `chatcmpl-tool-875d3ec6179676ae` (with dashes, >9 chars). Those IDs are\n * then rejected when sent back in a follow-up request. This is a known\n * Workers AI issue — see workers-ai.md (Issue 3). Once the Workers AI team\n * fixes the validation, this function becomes an idempotent no-op for\n * IDs that already match the pattern.\n */\nfunction sanitizeToolCallId(id: string): string {\n\tconst alphanumeric = id.replace(/[^a-zA-Z0-9]/g, \"\");\n\t// Pad with zeros if too short, truncate if too long\n\treturn alphanumeric.slice(0, 9).padEnd(9, \"0\");\n}\n\n/**\n * Creates a fetch function that intercepts OpenAI SDK requests and translates them\n * to Workers AI binding calls (env.AI.run). This allows the WorkersAiTextAdapter\n * to use the OpenAI SDK against a plain Workers AI binding.\n *\n * NOTE: The `input` URL parameter is intentionally ignored. The model name and all\n * request parameters are extracted from the JSON body, matching Workers AI's\n * `binding.run(model, inputs)` calling convention.\n */\nexport function createWorkersAiBindingFetch(binding: WorkersAiBinding): typeof fetch {\n\treturn async (_input, init) => {\n\t\tif (!init?.body) {\n\t\t\treturn new Response(\"No body\", { status: 400 });\n\t\t}\n\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = JSON.parse(init.body as string);\n\t\t} catch {\n\t\t\treturn new Response(\"Invalid JSON body\", { status: 400 });\n\t\t}\n\n\t\tconst model = body.model as string;\n\t\tconst stream = body.stream as boolean | undefined;\n\n\t\t// Build Workers AI inputs from OpenAI format\n\t\tconst inputs: Record<string, unknown> = {};\n\t\tif (body.messages) {\n\t\t\tinputs.messages = normalizeMessagesForBinding(\n\t\t\t\tbody.messages as Record<string, unknown>[],\n\t\t\t);\n\t\t}\n\t\tif (body.tools) inputs.tools = body.tools;\n\t\tif (typeof body.temperature === \"number\") inputs.temperature = body.temperature;\n\t\tif (typeof body.max_tokens === \"number\") inputs.max_tokens = body.max_tokens;\n\t\tif (body.response_format) inputs.response_format = body.response_format;\n\t\tif (stream) inputs.stream = true;\n\n\t\tconst result = await binding.run(model, inputs);\n\n\t\tif (stream && result instanceof ReadableStream) {\n\t\t\t// Workers AI returns an SSE stream with `data: {\"response\":\"chunk\"}` format.\n\t\t\t// Transform it to OpenAI-compatible SSE format.\n\t\t\tconst transformed = transformWorkersAiStream(\n\t\t\t\tresult as ReadableStream<Uint8Array>,\n\t\t\t\tmodel,\n\t\t\t);\n\t\t\treturn new Response(transformed, {\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/event-stream\",\n\t\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Graceful degradation: some models return a complete (non-streaming)\n\t\t// response even when `stream: true` is requested. Fall through to the\n\t\t// non-streaming wrapper which produces a valid OpenAI Chat Completion\n\t\t// response that the SDK can consume.\n\n\t\t// Non-streaming: Workers AI returns { response: \"text\", tool_calls?: [...] }\n\t\t// Wrap into OpenAI Chat Completion format.\n\t\tconst responseObj =\n\t\t\ttypeof result === \"object\" && result !== null\n\t\t\t\t? (result as Record<string, unknown>)\n\t\t\t\t: { response: String(result) };\n\n\t\tconst responseText = typeof responseObj.response === \"string\" ? responseObj.response : \"\";\n\n\t\tconst message: Record<string, unknown> = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: responseText,\n\t\t};\n\t\tlet finishReason = \"stop\";\n\n\t\t// Handle tool calls if present in Workers AI response\n\t\tif (Array.isArray(responseObj.tool_calls) && responseObj.tool_calls.length > 0) {\n\t\t\tfinishReason = \"tool_calls\";\n\t\t\tmessage.tool_calls = responseObj.tool_calls.map(\n\t\t\t\t(tc: {\n\t\t\t\t\tid?: string;\n\t\t\t\t\tname?: string;\n\t\t\t\t\targuments: unknown;\n\t\t\t\t\tfunction?: { name: string; arguments?: unknown };\n\t\t\t\t}) => ({\n\t\t\t\t\tid: sanitizeToolCallId(tc.id || crypto.randomUUID()),\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: tc.function?.name || tc.name || \"\",\n\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\ttypeof (tc.function?.arguments ?? tc.arguments) === \"string\"\n\t\t\t\t\t\t\t\t? ((tc.function?.arguments ?? tc.arguments) as string)\n\t\t\t\t\t\t\t\t: JSON.stringify(tc.function?.arguments ?? tc.arguments ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tconst openAiResponse = {\n\t\t\tid: `workers-ai-${crypto.randomUUID()}`,\n\t\t\tobject: \"chat.completion\",\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel,\n\t\t\tchoices: [{ index: 0, message, finish_reason: finishReason }],\n\t\t};\n\n\t\treturn new Response(JSON.stringify(openAiResponse), {\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t});\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Stream transformer: Workers AI SSE -> OpenAI-compatible SSE\n// Uses TransformStream for proper backpressure.\n// ---------------------------------------------------------------------------\n\n/**\n * Transforms a Workers AI SSE stream (data: {\"response\":\"chunk\"}) into\n * an OpenAI-compatible SSE stream (data: {\"choices\":[{\"delta\":{\"content\":\"chunk\"}}]}).\n *\n * Workers AI binding streams tool calls in an OpenAI-like nested format:\n * { tool_calls: [{ id, type, index, function: { name, arguments } }] }\n * Arguments are streamed incrementally across multiple SSE chunks, so the\n * transformer must forward them as incremental deltas rather than a single blob.\n */\nfunction transformWorkersAiStream(\n\tsource: ReadableStream<Uint8Array>,\n\tmodel: string,\n): ReadableStream<Uint8Array> {\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\t// Generate a stable ID and timestamp for the entire stream, matching OpenAI's\n\t// convention where all chunks in a single response share the same id/created.\n\tconst streamId = `workers-ai-${crypto.randomUUID()}`;\n\tconst created = Math.floor(Date.now() / 1000);\n\tlet buffer = \"\";\n\tlet hasToolCalls = false;\n\t// When true, the source stream is already in OpenAI format (some models\n\t// like Qwen3, Kimi K2.5 stream OpenAI-compatible SSE through the binding).\n\t// In that case, flush() should only emit [DONE] and skip the finish chunk.\n\tlet isOpenAiFormat = false;\n\t// Track which tool call indices we've already emitted an `id` for,\n\t// so subsequent argument deltas don't duplicate the id/type/name fields.\n\tconst emittedToolCallStart = new Set<number>();\n\n\treturn source.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tbuffer += decoder.decode(chunk, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tconst trimmed = line.trim();\n\t\t\t\t\tif (!trimmed || !trimmed.startsWith(\"data: \")) continue;\n\t\t\t\t\tconst data = trimmed.slice(6);\n\n\t\t\t\t\t// Swallow source [DONE]; we emit our own in flush()\n\t\t\t\t\tif (data === \"[DONE]\") continue;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = JSON.parse(data);\n\n\t\t\t\t\t\t// Some models (Qwen3, Kimi K2.5) return OpenAI-compatible format\n\t\t\t\t\t\t// directly through the binding, with `choices[].delta.content` and\n\t\t\t\t\t\t// optional `reasoning_content`. Detect this and pass through as-is.\n\t\t\t\t\t\tif (parsed.choices !== undefined) {\n\t\t\t\t\t\t\t// Already OpenAI format — pass through with only tool_call_id\n\t\t\t\t\t\t\t// sanitization for any tool calls present.\n\t\t\t\t\t\t\tisOpenAiFormat = true;\n\t\t\t\t\t\t\tconst choice = parsed.choices?.[0];\n\t\t\t\t\t\t\tif (choice?.delta?.tool_calls) {\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\t\t\t\t\t\t\t\tfor (const tc of choice.delta.tool_calls) {\n\t\t\t\t\t\t\t\t\tif (tc.id && typeof tc.id === \"string\") {\n\t\t\t\t\t\t\t\t\t\ttc.id = sanitizeToolCallId(tc.id);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (choice?.finish_reason === \"tool_calls\") {\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(parsed)}\\n\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// --- Workers AI native format handling below ---\n\n\t\t\t\t\t\t// Text content\n\t\t\t\t\t\tif (parsed.response != null && parsed.response !== \"\") {\n\t\t\t\t\t\t\tconst openAiChunk = {\n\t\t\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\t\t\tcreated,\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\t\t\tdelta: { content: parsed.response },\n\t\t\t\t\t\t\t\t\t\tfinish_reason: null,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(openAiChunk)}\\n\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Tool calls — Workers AI binding streams these incrementally:\n\t\t\t\t\t\t// Chunk A: { id, type, index, function: { name } } — start\n\t\t\t\t\t\t// Chunk B: { index, function: { arguments: \"partial...\" } } — args delta\n\t\t\t\t\t\t// Chunk C: { index, function: { arguments: \"rest...\" } } — args delta\n\t\t\t\t\t\t// Chunk D: { id: null, type: null, index, function: { name: null, arguments: \"\" } } — finalize (skip)\n\t\t\t\t\t\tif (Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n\t\t\t\t\t\t\tfor (const tc of parsed.tool_calls) {\n\t\t\t\t\t\t\t\tconst tcIndex = tc.index ?? 0;\n\n\t\t\t\t\t\t\t\t// Resolve name and arguments from either nested or flat format\n\t\t\t\t\t\t\t\tconst tcName = tc.function?.name ?? tc.name ?? null;\n\t\t\t\t\t\t\t\tconst tcArgs = tc.function?.arguments ?? tc.arguments ?? null;\n\t\t\t\t\t\t\t\tconst tcId = tc.id ?? null;\n\n\t\t\t\t\t\t\t\t// Skip finalization chunks where everything is null/empty\n\t\t\t\t\t\t\t\tif (!tcId && !tcName && (!tcArgs || tcArgs === \"\")) continue;\n\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\n\t\t\t\t\t\t\t\t// Build the OpenAI-compatible tool_calls delta\n\t\t\t\t\t\t\t\tconst toolCallDelta: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t\tindex: tcIndex,\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tif (!emittedToolCallStart.has(tcIndex)) {\n\t\t\t\t\t\t\t\t\t// First chunk for this tool call index — emit id, type, name.\n\t\t\t\t\t\t\t\t\t// Use sanitizeToolCallId so the ID survives round-trip through\n\t\t\t\t\t\t\t\t\t// the binding's strict `[a-zA-Z0-9]{9}` validation.\n\t\t\t\t\t\t\t\t\temittedToolCallStart.add(tcIndex);\n\t\t\t\t\t\t\t\t\tconst rawId = tcId || `call${streamId}${tcIndex}`;\n\t\t\t\t\t\t\t\t\ttoolCallDelta.id = sanitizeToolCallId(rawId);\n\t\t\t\t\t\t\t\t\ttoolCallDelta.type = \"function\";\n\t\t\t\t\t\t\t\t\ttoolCallDelta.function = {\n\t\t\t\t\t\t\t\t\t\tname: tcName || \"\",\n\t\t\t\t\t\t\t\t\t\t// Include arguments if they arrive in the same chunk\n\t\t\t\t\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\t\t\t\t\ttcArgs != null\n\t\t\t\t\t\t\t\t\t\t\t\t? typeof tcArgs === \"string\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? tcArgs\n\t\t\t\t\t\t\t\t\t\t\t\t\t: JSON.stringify(tcArgs)\n\t\t\t\t\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Subsequent chunks — only include arguments delta\n\t\t\t\t\t\t\t\t\tif (tcArgs != null && tcArgs !== \"\") {\n\t\t\t\t\t\t\t\t\t\ttoolCallDelta.function = {\n\t\t\t\t\t\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\t\t\t\t\t\ttypeof tcArgs === \"string\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? tcArgs\n\t\t\t\t\t\t\t\t\t\t\t\t\t: JSON.stringify(tcArgs),\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcontinue; // Nothing useful to forward\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst toolChunk = {\n\t\t\t\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\t\t\t\tcreated,\n\t\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\t\t\t\tdelta: { tool_calls: [toolCallDelta] },\n\t\t\t\t\t\t\t\t\t\t\tfinish_reason: null,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(toolChunk)}\\n\\n`),\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} catch (e) {\n\t\t\t\t\t\t// Log malformed SSE events for debugging; don't break the stream.\n\t\t\t\t\t\tconsole.warn(\"[tanstack-ai] failed to parse SSE event:\", data, e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tif (!isOpenAiFormat) {\n\t\t\t\t\t// Workers AI native format: emit a finish chunk with stop/tool_calls\n\t\t\t\t\tconst finalChunk = {\n\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\tcreated,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\tdelta: {},\n\t\t\t\t\t\t\t\tfinish_reason: hasToolCalls ? \"tool_calls\" : \"stop\",\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\tcontroller.enqueue(encoder.encode(`data: ${JSON.stringify(finalChunk)}\\n\\n`));\n\t\t\t\t}\n\t\t\t\t// OpenAI format already includes its own finish_reason in the stream.\n\t\t\t\t// Either way, emit a [DONE] sentinel.\n\t\t\t\tcontroller.enqueue(encoder.encode(\"data: [DONE]\\n\\n\"));\n\t\t\t},\n\t\t}),\n\t);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-LG2I3ANT.cjs","../src/adapters/workers-ai.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACTA;AACC;AAAA,iDAGM;AACP,gFAAmB;AAyBnB,SAAS,oBAAA,CAAqB,MAAA,EAAwC;AACrE,EAAA,uDAAA,MAA8B,CAAA;AAE9B,EAAA,GAAA,CAAI,qDAAA,MAA4B,CAAA,EAAG;AAElC,IAAA,OAAO,IAAI,qBAAA,CAAO;AAAA,MACjB,MAAA,EAAQ,QAAA;AAAA,MACR,KAAA,EAAO,2DAAA,MAA4B,CAAO,OAAO;AAAA,IAClD,CAAC,CAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAI,yDAAA,MAAgC,CAAA,EAAG;AAEtC,IAAA,OAAO,IAAI,qBAAA,CAAO;AAAA,MACjB,OAAA,EAAS,CAAA,8CAAA,EAAiD,MAAA,CAAO,SAAS,CAAA,MAAA,CAAA;AAAA,MAC1E,MAAA,EAAQ,MAAA,CAAO;AAAA,IAChB,CAAC,CAAA;AAAA,EACF;AAGA,EAAA,MAAM,cAAA,EAAgB,MAAA;AACtB,EAAA,OAAO,IAAI,qBAAA,CAAO;AAAA,IACjB,KAAA,EAAO,kDAAA,YAAmB,EAAc,aAAa,CAAA;AAAA,IACrD,MAAA,mBAAQ,aAAA,CAAc,MAAA,UAAU;AAAA,EACjC,CAAC,CAAA;AACF;AAgBA,SAAS,kBAAA,CACR,OAAA,EACS;AACT,EAAA,GAAA,CAAI,QAAA,IAAY,IAAA,EAAM,OAAO,EAAA;AA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AA;AAEM,QAAA;AACC,UAAA;AACN,UAAA;AACqB,UAAA;AACrB,UAAA;AACc,UAAA;AACf,QAAA;AACD,MAAA;AACe,IAAA;AACsD,MAAA;AAEC,MAAA;AAC3C,MAAA;AACpB,QAAA;AACC,UAAA;AACN,UAAA;AACqB,UAAA;AACrB,UAAA;AACD,QAAA;AACD,MAAA;AACM,MAAA;AACC,QAAA;AACN,QAAA;AACqB,QAAA;AACrB,QAAA;AACO,QAAA;AACc,UAAA;AACpB,UAAA;AACD,QAAA;AACD,MAAA;AACD,IAAA;AACD,EAAA;AAI4C,EAAA;AACL,IAAA;AACkB,IAAA;AAEY,IAAA;AAC9C,MAAA;AACrB,IAAA;AAE0D,IAAA;AACrC,MAAA;AACX,MAAA;AACV,MAAA;AACQ,MAAA;AACS,MAAA;AACV,QAAA;AACO,QAAA;AACN,UAAA;AACE,UAAA;AACA,UAAA;AACT,QAAA;AACD,MAAA;AACA,IAAA;AAEkC,IAAA;AAEtB,IAAA;AACF,MAAA;AACmE,QAAA;AAC7E,MAAA;AACD,IAAA;AAE8C,IAAA;AAI1C,IAAA;AACA,IAAA;AAEgC,IAAA;AACzB,MAAA;AACN,MAAA;AACsB,QAAA;AAClB,MAAA;AACA,QAAA;AACR,MAAA;AACM,IAAA;AAEC,MAAA;AAC4B,MAAA;AACpC,IAAA;AAEuB,IAAA;AACxB,EAAA;AACD;AAM+F;AACjD,EAAA;AAC9C;ADvLoF;AACA;AACA;AACA;AACA","file":"/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-LG2I3ANT.cjs","sourcesContent":[null,"import type { AiModels, BaseAiTextGeneration } from \"@cloudflare/workers-types\";\nimport type { StreamChunk, TextOptions } from \"@tanstack/ai\";\nimport {\n\tBaseTextAdapter,\n\ttype StructuredOutputOptions,\n\ttype StructuredOutputResult,\n} from \"@tanstack/ai/adapters\";\nimport OpenAI from \"openai\";\nimport {\n\ttype WorkersAiAdapterConfig,\n\ttype AiGatewayAdapterConfig,\n\tcreateGatewayFetch,\n\tcreateWorkersAiBindingFetch,\n\tisDirectBindingConfig,\n\tisDirectCredentialsConfig,\n\tvalidateWorkersAiConfig,\n} from \"../utils/create-fetcher\";\n\n// ---------------------------------------------------------------------------\n// Model types derived from @cloudflare/workers-types\n// ---------------------------------------------------------------------------\n\nexport type WorkersAiTextModel =\n\t| {\n\t\t\t[K in keyof AiModels]: AiModels[K] extends BaseAiTextGeneration ? K : never;\n\t }[keyof AiModels]\n\t| (string & {});\n\n// ---------------------------------------------------------------------------\n// Helpers: build the right OpenAI client depending on config mode\n// ---------------------------------------------------------------------------\n\nfunction buildWorkersAiClient(config: WorkersAiAdapterConfig): OpenAI {\n\tvalidateWorkersAiConfig(config);\n\n\tif (isDirectBindingConfig(config)) {\n\t\t// Plain binding mode: shim translates OpenAI fetch calls to env.AI.run()\n\t\treturn new OpenAI({\n\t\t\tapiKey: \"unused\",\n\t\t\tfetch: createWorkersAiBindingFetch(config.binding),\n\t\t});\n\t}\n\n\tif (isDirectCredentialsConfig(config)) {\n\t\t// Plain REST mode: point OpenAI SDK at Workers AI's OpenAI-compatible endpoint\n\t\treturn new OpenAI({\n\t\t\tbaseURL: `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/ai/v1`,\n\t\t\tapiKey: config.apiKey,\n\t\t});\n\t}\n\n\t// Gateway mode (existing): use createGatewayFetch\n\tconst gatewayConfig = config as AiGatewayAdapterConfig;\n\treturn new OpenAI({\n\t\tfetch: createGatewayFetch(\"workers-ai\", gatewayConfig),\n\t\tapiKey: gatewayConfig.apiKey ?? \"unused\",\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Shared message-building helpers\n// ---------------------------------------------------------------------------\n\ninterface MessageLike {\n\trole: string;\n\tcontent: string | null | Array<{ type: string; content?: string }>;\n\ttoolCalls?: Array<{\n\t\tid: string;\n\t\tfunction: { name: string; arguments: string };\n\t}>;\n\ttoolCallId?: string;\n}\n\nfunction extractTextContent(\n\tcontent: string | null | Array<{ type: string; content?: string }>,\n): string {\n\tif (content === null) return \"\";\n\tif (typeof content === \"string\") return content;\n\treturn content\n\t\t.filter((p) => p.type === \"text\")\n\t\t.map((p) => p.content || \"\")\n\t\t.join(\"\");\n}\n\n/**\n * Build OpenAI-compatible user message content, preserving image parts.\n *\n * If the content has only text parts, returns a plain string.\n * If it includes image parts, returns an array of content parts in\n * OpenAI's multi-modal format (text + image_url).\n */\nfunction buildUserContent(\n\tcontent: string | null | Array<{ type: string; content?: string; image_url?: unknown }>,\n): string | OpenAI.Chat.ChatCompletionContentPart[] {\n\tif (content === null) return \"\";\n\tif (typeof content === \"string\") return content;\n\n\tconst hasImages = content.some((p) => p.type === \"image_url\" || p.type === \"image\");\n\tif (!hasImages) {\n\t\t// No images — return plain text for simpler messages\n\t\treturn content\n\t\t\t.filter((p) => p.type === \"text\")\n\t\t\t.map((p) => p.content || \"\")\n\t\t\t.join(\"\");\n\t}\n\n\t// Multi-modal: build array of text + image_url parts\n\tconst parts: OpenAI.Chat.ChatCompletionContentPart[] = [];\n\tfor (const part of content) {\n\t\tif (part.type === \"text\" && part.content) {\n\t\t\tparts.push({ type: \"text\", text: part.content });\n\t\t} else if (part.type === \"image_url\" && part.content) {\n\t\t\tparts.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: { url: part.content },\n\t\t\t});\n\t\t} else if (part.type === \"image_url\" && part.image_url) {\n\t\t\tparts.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: part.image_url as OpenAI.Chat.ChatCompletionContentPartImage.ImageURL,\n\t\t\t});\n\t\t}\n\t}\n\treturn parts;\n}\n\nfunction buildOpenAIMessages(\n\tsystemPrompts: string[] | undefined,\n\tmessages: MessageLike[],\n\toptions?: { includeToolMessages?: boolean },\n): OpenAI.Chat.ChatCompletionMessageParam[] {\n\tconst includeTools = options?.includeToolMessages ?? true;\n\tconst openAIMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [];\n\n\tif (systemPrompts && systemPrompts.length > 0) {\n\t\topenAIMessages.push({\n\t\t\trole: \"system\",\n\t\t\tcontent: systemPrompts.join(\"\\n\"),\n\t\t});\n\t}\n\n\tfor (const message of messages) {\n\t\tif (message.role === \"user\") {\n\t\t\topenAIMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: buildUserContent(message.content),\n\t\t\t});\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst assistantMessage: OpenAI.Chat.ChatCompletionAssistantMessageParam = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: extractTextContent(message.content),\n\t\t\t};\n\t\t\tif (includeTools && message.toolCalls && message.toolCalls.length > 0) {\n\t\t\t\tassistantMessage.tool_calls = message.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: tc.function.name,\n\t\t\t\t\t\targuments: tc.function.arguments,\n\t\t\t\t\t},\n\t\t\t\t}));\n\t\t\t}\n\t\t\topenAIMessages.push(assistantMessage);\n\t\t} else if (includeTools && message.role === \"tool\") {\n\t\t\tlet toolContent: string;\n\t\t\tif (typeof message.content === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tJSON.parse(message.content);\n\t\t\t\t\ttoolContent = message.content;\n\t\t\t\t} catch {\n\t\t\t\t\ttoolContent = JSON.stringify(message.content);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttoolContent = JSON.stringify(message.content);\n\t\t\t}\n\t\t\topenAIMessages.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\ttool_call_id: message.toolCallId || `tool_${crypto.randomUUID().slice(0, 8)}`,\n\t\t\t\tcontent: toolContent,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn openAIMessages;\n}\n\nfunction buildOpenAITools(\n\ttools: Array<{ name: string; description: string; inputSchema?: unknown }> | undefined,\n): OpenAI.Chat.ChatCompletionTool[] | undefined {\n\tif (!tools) return undefined;\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\" as const,\n\t\tfunction: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.inputSchema as Record<string, unknown>,\n\t\t},\n\t}));\n}\n\n// ---------------------------------------------------------------------------\n// ID generation\n// ---------------------------------------------------------------------------\n\nfunction generateId(prefix: string): string {\n\treturn `${prefix}-${crypto.randomUUID()}`;\n}\n\n// ---------------------------------------------------------------------------\n// WorkersAiTextAdapter: chat / structured output via OpenAI Chat Completions\n// ---------------------------------------------------------------------------\n\n// TODO: Replace `any` generic params with proper types once BaseTextAdapter's\n// provider-options generics stabilize. Workers AI doesn't have provider-specific\n// options in the TanStack sense, so `any` is pragmatic for now.\nexport class WorkersAiTextAdapter<TModel extends WorkersAiTextModel> extends BaseTextAdapter<\n\tTModel,\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- BaseTextAdapter generic params are opaque\n\tany,\n\tany,\n\tany\n> {\n\tname = \"workers-ai\" as const;\n\n\tprivate client: OpenAI;\n\n\tconstructor(model: TModel, config: WorkersAiAdapterConfig) {\n\t\tsuper({ apiKey: \"unused\" }, model);\n\t\tthis.client = buildWorkersAiClient(config);\n\t}\n\n\tasync *chatStream(options: TextOptions<any>): AsyncIterable<StreamChunk> {\n\t\tconst { systemPrompts, messages, tools, temperature, model } = options;\n\n\t\tconst openAIMessages = buildOpenAIMessages(systemPrompts, messages);\n\t\tconst openAITools = buildOpenAITools(tools);\n\n\t\tconst timestamp = Date.now();\n\t\tconst runId = generateId(\"workers-ai\");\n\t\tconst messageId = generateId(\"workers-ai\");\n\t\tlet hasEmittedRunStarted = false;\n\t\tlet hasEmittedTextMessageStart = false;\n\t\tlet accumulatedContent = \"\";\n\t\tlet hasEmittedStepStarted = false;\n\t\tlet accumulatedReasoning = \"\";\n\t\tconst stepId = generateId(\"workers-ai-step\");\n\t\tlet hasReceivedFinishReason = false;\n\t\tconst toolCallsInProgress = new Map<\n\t\t\tnumber,\n\t\t\t{ id: string; name: string; arguments: string; started: boolean }\n\t\t>();\n\n\t\ttry {\n\t\t\tlet stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;\n\t\t\ttry {\n\t\t\t\tstream = await this.client.chat.completions.create({\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\tmessages: openAIMessages,\n\t\t\t\t\ttools: openAITools,\n\t\t\t\t\ttemperature,\n\t\t\t\t\tstream: true,\n\t\t\t\t\tstream_options: { include_usage: true },\n\t\t\t\t});\n\t\t\t} catch (streamError: unknown) {\n\t\t\t\t// Some models (e.g. GPT-OSS) don't support streaming via the REST API.\n\t\t\t\t// Fall back to a non-streaming call and yield the result as a single chunk.\n\t\t\t\tconsole.warn(\n\t\t\t\t\t\"[tanstack-ai] Streaming failed, falling back to non-streaming:\",\n\t\t\t\t\tstreamError instanceof Error ? streamError.message : streamError,\n\t\t\t\t);\n\t\t\t\tconst nonStreamResult = await this.client.chat.completions.create({\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\tmessages: openAIMessages,\n\t\t\t\t\ttools: openAITools,\n\t\t\t\t\ttemperature,\n\t\t\t\t});\n\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_STARTED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t} satisfies StreamChunk;\n\n\t\t\t\tconst msg = nonStreamResult.choices[0]?.message;\n\t\t\t\tif (msg?.content) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_START\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_CONTENT\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tdelta: msg.content,\n\t\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_END\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\tif (msg?.tool_calls) {\n\t\t\t\t\tfor (const tc of msg.tool_calls) {\n\t\t\t\t\t\tif (tc.type !== \"function\") continue;\n\t\t\t\t\t\tconst fn = tc.function;\n\t\t\t\t\t\tlet parsedInput: unknown = {};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tparsedInput = fn.arguments ? JSON.parse(fn.arguments) : {};\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tparsedInput = {};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TOOL_CALL_START\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: fn.name,\n\t\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TOOL_CALL_END\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: fn.name,\n\t\t\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst finishReason = nonStreamResult.choices[0]?.finish_reason;\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_FINISHED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: nonStreamResult.model || model || this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t\tusage: nonStreamResult.usage\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpromptTokens: nonStreamResult.usage.prompt_tokens,\n\t\t\t\t\t\t\t\tcompletionTokens: nonStreamResult.usage.completion_tokens,\n\t\t\t\t\t\t\t\ttotalTokens: nonStreamResult.usage.total_tokens,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tfinishReason:\n\t\t\t\t\t\tfinishReason === \"tool_calls\" || finishReason === \"function_call\"\n\t\t\t\t\t\t\t? \"tool_calls\"\n\t\t\t\t\t\t\t: ((finishReason as \"stop\" | \"length\" | \"content_filter\") ?? \"stop\"),\n\t\t\t\t} satisfies StreamChunk;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tif (!chunk.choices || chunk.choices.length === 0) continue;\n\t\t\t\tconst choice = chunk.choices[0];\n\t\t\t\tif (!choice) continue;\n\n\t\t\t\t// Emit RUN_STARTED on first chunk\n\t\t\t\tif (!hasEmittedRunStarted) {\n\t\t\t\t\thasEmittedRunStarted = true;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"RUN_STARTED\",\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\tconst delta = choice.delta;\n\n\t\t\t\t// Reasoning content (used by models like QwQ, DeepSeek R1, Kimi K2.5)\n\t\t\t\t// The OpenAI SDK doesn't type this field, but models send it as an extension.\n\t\t\t\tconst reasoningContent = (delta as Record<string, unknown>).reasoning_content as\n\t\t\t\t\t| string\n\t\t\t\t\t| undefined;\n\t\t\t\tif (reasoningContent) {\n\t\t\t\t\t// RUN_STARTED is already guaranteed by the guard above\n\t\t\t\t\tif (!hasEmittedStepStarted) {\n\t\t\t\t\t\thasEmittedStepStarted = true;\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"STEP_STARTED\",\n\t\t\t\t\t\t\tstepId,\n\t\t\t\t\t\t\tstepType: \"thinking\",\n\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\t\t\t\t\taccumulatedReasoning += reasoningContent;\n\t\t\t\t\t// TODO: TanStack AI's StreamProcessor currently treats STEP_FINISHED as an\n\t\t\t\t\t// incremental reasoning event (with `delta` + accumulated `content`), so we\n\t\t\t\t\t// emit one per token. If TanStack AI adds a dedicated STEP_CONTENT event\n\t\t\t\t\t// type, this should be updated to emit STEP_CONTENT per token and a single\n\t\t\t\t\t// STEP_FINISHED when reasoning ends (i.e. when the first non-reasoning\n\t\t\t\t\t// content or finish_reason arrives).\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"STEP_FINISHED\",\n\t\t\t\t\t\tstepId,\n\t\t\t\t\t\tdelta: reasoningContent,\n\t\t\t\t\t\tcontent: accumulatedReasoning,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\t// Text content\n\t\t\t\tif (delta.content) {\n\t\t\t\t\tif (!hasEmittedTextMessageStart) {\n\t\t\t\t\t\thasEmittedTextMessageStart = true;\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TEXT_MESSAGE_START\",\n\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\n\t\t\t\t\taccumulatedContent += delta.content;\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_CONTENT\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tdelta: delta.content,\n\t\t\t\t\t\tcontent: accumulatedContent,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\t// Tool calls\n\t\t\t\tif (delta.tool_calls) {\n\t\t\t\t\tfor (const toolCallDelta of delta.tool_calls) {\n\t\t\t\t\t\tconst index = toolCallDelta.index;\n\n\t\t\t\t\t\tif (!toolCallsInProgress.has(index)) {\n\t\t\t\t\t\t\ttoolCallsInProgress.set(index, {\n\t\t\t\t\t\t\t\tid: toolCallDelta.id || \"\",\n\t\t\t\t\t\t\t\tname: toolCallDelta.function?.name || \"\",\n\t\t\t\t\t\t\t\targuments: \"\",\n\t\t\t\t\t\t\t\tstarted: false,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst toolCall = toolCallsInProgress.get(index)!;\n\n\t\t\t\t\t\tif (toolCallDelta.id) {\n\t\t\t\t\t\t\ttoolCall.id = toolCallDelta.id;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (toolCallDelta.function?.name) {\n\t\t\t\t\t\t\ttoolCall.name = toolCallDelta.function.name;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (toolCallDelta.function?.arguments) {\n\t\t\t\t\t\t\ttoolCall.arguments += toolCallDelta.function.arguments;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Emit TOOL_CALL_START once we have id and name\n\t\t\t\t\t\tif (toolCall.id && toolCall.name && !toolCall.started) {\n\t\t\t\t\t\t\ttoolCall.started = true;\n\t\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\t\ttype: \"TOOL_CALL_START\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Stream tool call arguments\n\t\t\t\t\t\tif (toolCallDelta.function?.arguments && toolCall.started) {\n\t\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\t\ttype: \"TOOL_CALL_ARGS\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\tdelta: toolCallDelta.function.arguments,\n\t\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Finish\n\t\t\t\tif (choice.finish_reason) {\n\t\t\t\t\thasReceivedFinishReason = true;\n\n\t\t\t\t\t// End tool calls\n\t\t\t\t\tif (choice.finish_reason === \"tool_calls\" || toolCallsInProgress.size > 0) {\n\t\t\t\t\t\tfor (const [, toolCall] of toolCallsInProgress) {\n\t\t\t\t\t\t\tlet parsedInput: unknown = {};\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tparsedInput = toolCall.arguments\n\t\t\t\t\t\t\t\t\t? JSON.parse(toolCall.arguments)\n\t\t\t\t\t\t\t\t\t: {};\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tparsedInput = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\t\ttype: \"TOOL_CALL_END\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst computedFinishReason =\n\t\t\t\t\t\tchoice.finish_reason === \"tool_calls\" ||\n\t\t\t\t\t\tchoice.finish_reason === \"function_call\" ||\n\t\t\t\t\t\ttoolCallsInProgress.size > 0\n\t\t\t\t\t\t\t? \"tool_calls\"\n\t\t\t\t\t\t\t: (choice.finish_reason as \"stop\" | \"length\" | \"content_filter\");\n\n\t\t\t\t\t// End text message if started\n\t\t\t\t\tif (hasEmittedTextMessageStart) {\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TEXT_MESSAGE_END\",\n\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit RUN_FINISHED\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"RUN_FINISHED\",\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tmodel: chunk.model || model || this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tusage: chunk.usage\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tpromptTokens: chunk.usage.prompt_tokens,\n\t\t\t\t\t\t\t\t\tcompletionTokens: chunk.usage.completion_tokens,\n\t\t\t\t\t\t\t\t\ttotalTokens: chunk.usage.total_tokens,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\tfinishReason: computedFinishReason,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Premature stream termination: the stream ended without a finish_reason.\n\t\t\t// This can happen when Workers AI truncates a response or the connection drops.\n\t\t\t// Emit proper closing events so the consumer doesn't hang.\n\t\t\tif (hasEmittedRunStarted && !hasReceivedFinishReason) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t\"[tanstack-ai] Stream ended without finish_reason — possible truncation or connection drop\",\n\t\t\t\t);\n\n\t\t\t\t// Close any open tool calls\n\t\t\t\tfor (const [, toolCall] of toolCallsInProgress) {\n\t\t\t\t\tif (toolCall.started) {\n\t\t\t\t\t\tlet parsedInput: unknown = {};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tparsedInput = toolCall.arguments ? JSON.parse(toolCall.arguments) : {};\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tparsedInput = {};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"TOOL_CALL_END\",\n\t\t\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Close text message if open\n\t\t\t\tif (hasEmittedTextMessageStart) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"TEXT_MESSAGE_END\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t} satisfies StreamChunk;\n\t\t\t\t}\n\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_FINISHED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t\tfinishReason: \"stop\",\n\t\t\t\t} satisfies StreamChunk;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst code =\n\t\t\t\terror instanceof Error ? (error as Error & { code?: string }).code : undefined;\n\t\t\tif (!hasEmittedRunStarted) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"RUN_STARTED\",\n\t\t\t\t\trunId,\n\t\t\t\t\tmodel: model ?? this.model,\n\t\t\t\t\ttimestamp,\n\t\t\t\t} satisfies StreamChunk;\n\t\t\t}\n\t\t\tyield {\n\t\t\t\ttype: \"RUN_ERROR\",\n\t\t\t\trunId,\n\t\t\t\tmodel: model ?? this.model,\n\t\t\t\ttimestamp,\n\t\t\t\terror: {\n\t\t\t\t\tmessage: message || \"Unknown error\",\n\t\t\t\t\tcode,\n\t\t\t\t},\n\t\t\t} satisfies StreamChunk;\n\t\t}\n\t}\n\n\tasync structuredOutput(\n\t\toptions: StructuredOutputOptions<any>,\n\t): Promise<StructuredOutputResult<unknown>> {\n\t\tconst { outputSchema, chatOptions } = options;\n\t\tconst { systemPrompts, messages, temperature, model } = chatOptions;\n\n\t\tconst openAIMessages = buildOpenAIMessages(systemPrompts, messages, {\n\t\t\tincludeToolMessages: false,\n\t\t});\n\n\t\tconst response = await this.client.chat.completions.create({\n\t\t\tmodel: model ?? this.model,\n\t\t\tmessages: openAIMessages,\n\t\t\ttemperature,\n\t\t\tstream: false,\n\t\t\tresponse_format: {\n\t\t\t\ttype: \"json_schema\",\n\t\t\t\tjson_schema: {\n\t\t\t\t\tname: \"structured_output\",\n\t\t\t\t\tstrict: true,\n\t\t\t\t\tschema: outputSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\n\t\tconst choice = response.choices?.[0];\n\n\t\tif (!choice) {\n\t\t\tthrow new Error(\n\t\t\t\t`Workers AI structured output returned no choices: ${JSON.stringify(response)}`,\n\t\t\t);\n\t\t}\n\n\t\tconst rawContent = choice.message?.content ?? \"\";\n\n\t\t// Workers AI REST endpoint may return `content` as an already-parsed object\n\t\t// when using json_schema response format, so normalise both cases.\n\t\tlet data: unknown;\n\t\tlet rawText: string;\n\n\t\tif (typeof rawContent === \"string\") {\n\t\t\trawText = rawContent;\n\t\t\ttry {\n\t\t\t\tdata = JSON.parse(rawText);\n\t\t\t} catch {\n\t\t\t\tdata = rawText;\n\t\t\t}\n\t\t} else {\n\t\t\t// Already an object — stringify for rawText, use directly for data\n\t\t\tdata = rawContent;\n\t\t\trawText = JSON.stringify(rawContent);\n\t\t}\n\n\t\treturn { data, rawText };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\nexport function createWorkersAiChat(model: WorkersAiTextModel, config: WorkersAiAdapterConfig) {\n\treturn new WorkersAiTextAdapter(model, config);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/create-fetcher.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// AI Gateway types (for third-party providers + Workers AI through gateway)\n// ---------------------------------------------------------------------------\n\nexport interface CloudflareAiGateway {\n\trun(request: unknown): Promise<Response>;\n}\n\nexport interface AiGatewayBindingConfig {\n\t/**\n\t * The AI Gateway binding\n\t * @example\n\t * env.AI.gateway('my-gateway-id')\n\t */\n\tbinding: CloudflareAiGateway;\n\t/**\n\t * The Provider API Key if you want to manually pass it, ignore if using Unified Billing or BYOK.\n\t */\n\tapiKey?: string;\n}\n\nexport type AiGatewayCredentialsConfig = {\n\t/**\n\t * The Cloudflare account ID\n\t */\n\taccountId: string;\n\t/**\n\t * The AI Gateway ID\n\t */\n\tgatewayId: string;\n} & (\n\t| {\n\t\t\t/** Cloudflare API Key for AI Gateway */\n\t\t\tcfApiKey: string;\n\t\t\tapiKey?: string;\n\t }\n\t| {\n\t\t\t/** Provider API Key */\n\t\t\tapiKey: string;\n\t\t\t/** Cloudflare API Key for AI Gateway */\n\t\t\tcfApiKey?: string;\n\t }\n);\n\nexport interface AiGatewayConfig {\n\tskipCache?: boolean;\n\tcacheTtl?: number;\n\tcustomCacheKey?: string;\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type AiGatewayAdapterConfig = (AiGatewayBindingConfig | AiGatewayCredentialsConfig) &\n\tAiGatewayConfig;\n\n// ---------------------------------------------------------------------------\n// Plain Workers AI types (direct binding or REST, no gateway)\n// ---------------------------------------------------------------------------\n\n/**\n * The Workers AI binding interface (env.AI).\n * Accepts a model name and inputs, returns results directly.\n * Includes `gateway()` which is present on `env.AI` but not on `env.AI.gateway(id)`,\n * enabling structural discrimination from `CloudflareAiGateway`.\n */\nexport interface WorkersAiBinding {\n\trun(\n\t\tmodel: string,\n\t\tinputs: Record<string, unknown>,\n\t\toptions?: Record<string, unknown>,\n\t): Promise<unknown>;\n\tgateway(gatewayId: string): CloudflareAiGateway;\n}\n\nexport interface WorkersAiDirectBindingConfig {\n\t/**\n\t * The Workers AI binding (env.AI).\n\t * @example\n\t * { binding: env.AI }\n\t */\n\tbinding: WorkersAiBinding;\n}\n\nexport interface WorkersAiDirectCredentialsConfig {\n\t/**\n\t * The Cloudflare account ID\n\t */\n\taccountId: string;\n\t/**\n\t * The Cloudflare API key for Workers AI\n\t */\n\tapiKey: string;\n}\n\n/**\n * Config for Workers AI adapters. Supports four modes:\n * - Plain binding: `{ binding: env.AI }`\n * - Plain REST: `{ accountId, apiKey }`\n * - AI Gateway binding: `{ binding: env.AI.gateway(id) }`\n * - AI Gateway REST: `{ accountId, gatewayId, ... }`\n *\n * The third union member intersects `AiGatewayAdapterConfig` with `{ apiKey?: string }`.\n * For the gateway binding variant, `AiGatewayBindingConfig` already includes `apiKey?`,\n * so the intersection is redundant there. For the gateway credentials variant, this\n * `apiKey` represents the Workers AI token (used in the `Authorization` header to the\n * upstream provider), distinct from `cfApiKey` (used in the `cf-aig-authorization`\n * header for authenticated gateways).\n */\nexport type WorkersAiAdapterConfig =\n\t| WorkersAiDirectBindingConfig\n\t| WorkersAiDirectCredentialsConfig\n\t| (AiGatewayAdapterConfig & { apiKey?: string });\n\n// ---------------------------------------------------------------------------\n// Config detection helpers\n// ---------------------------------------------------------------------------\n\n/** Returns true if this is a plain Workers AI binding config (`{ binding: env.AI }`) */\nexport function isDirectBindingConfig(\n\tconfig: WorkersAiAdapterConfig,\n): config is WorkersAiDirectBindingConfig {\n\t// env.AI has a .gateway() method; env.AI.gateway(id) does not.\n\t// This distinguishes direct bindings from AI Gateway bindings.\n\treturn (\n\t\t\"binding\" in config &&\n\t\ttypeof (config.binding as unknown as Record<string, unknown>).gateway === \"function\"\n\t);\n}\n\n/** Returns true if this is a plain Workers AI REST config (accountId + apiKey, no gatewayId) */\nexport function isDirectCredentialsConfig(\n\tconfig: WorkersAiAdapterConfig,\n): config is WorkersAiDirectCredentialsConfig {\n\treturn \"accountId\" in config && \"apiKey\" in config && !(\"gatewayId\" in config);\n}\n\n/** Returns true if this is an AI Gateway config (has gateway binding or `gatewayId`) */\nexport function isGatewayConfig(config: WorkersAiAdapterConfig): config is AiGatewayAdapterConfig {\n\tif (\"gatewayId\" in config) return true;\n\t// Has `binding` but NOT a direct Workers AI binding (no .gateway method)\n\treturn \"binding\" in config && !isDirectBindingConfig(config);\n}\n\n// ---------------------------------------------------------------------------\n// Config validation\n// ---------------------------------------------------------------------------\n\n/**\n * Validates that a WorkersAiAdapterConfig contains a valid configuration.\n * Throws an error if neither a binding, credentials (accountId + apiKey),\n * nor a gateway configuration is provided.\n */\nexport function validateWorkersAiConfig(config: WorkersAiAdapterConfig): void {\n\tif (\n\t\t!isDirectBindingConfig(config) &&\n\t\t!isDirectCredentialsConfig(config) &&\n\t\t!isGatewayConfig(config)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Invalid Workers AI configuration: you must provide either a binding (e.g. { binding: env.AI }), \" +\n\t\t\t\t\"credentials ({ accountId, apiKey }), or a gateway configuration ({ binding: env.AI.gateway(id) } \" +\n\t\t\t\t\"or { accountId, gatewayId }).\",\n\t\t);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// createGatewayFetch -- for routing through AI Gateway\n// ---------------------------------------------------------------------------\n\nexport function createGatewayFetch(\n\tprovider: string,\n\tconfig: AiGatewayAdapterConfig,\n\theaders: Record<string, string> = {},\n): typeof fetch {\n\treturn (input, init) => {\n\t\tlet query: Record<string, unknown> = {};\n\n\t\tconst url =\n\t\t\ttypeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\t\tconst urlObj = new URL(url);\n\n\t\t// Extract endpoint path (remove /v1/ prefix if present)\n\t\tconst endpoint = urlObj.pathname.replace(/^\\/v1\\//, \"\").replace(/^\\//, \"\") + urlObj.search;\n\n\t\tif (init?.body) {\n\t\t\ttry {\n\t\t\t\tquery = JSON.parse(init.body as string);\n\t\t\t} catch {\n\t\t\t\tquery = { _raw: init.body };\n\t\t\t}\n\t\t}\n\n\t\tconst cacheHeaders: Record<string, string> = {};\n\n\t\tif (\"skipCache\" in config && config.skipCache) {\n\t\t\tcacheHeaders[\"cf-aig-skip-cache\"] = \"true\";\n\t\t}\n\n\t\tif (typeof config.cacheTtl === \"number\") {\n\t\t\tcacheHeaders[\"cf-aig-cache-ttl\"] = String(config.cacheTtl);\n\t\t}\n\n\t\tif (typeof config.customCacheKey === \"string\") {\n\t\t\tcacheHeaders[\"cf-aig-cache-key\"] = config.customCacheKey;\n\t\t}\n\n\t\tif (typeof config.metadata === \"object\") {\n\t\t\tcacheHeaders[\"cf-aig-metadata\"] = JSON.stringify(config.metadata);\n\t\t}\n\n\t\tconst request: {\n\t\t\tprovider: string;\n\t\t\tendpoint: string;\n\t\t\theaders: Record<string, string>;\n\t\t\tquery: Record<string, unknown>;\n\t\t} = {\n\t\t\tprovider,\n\t\t\tendpoint,\n\t\t\theaders: {\n\t\t\t\t...(init?.headers as Record<string, string> | undefined),\n\t\t\t\t...headers,\n\t\t\t\t...cacheHeaders,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tquery,\n\t\t};\n\n\t\tif (provider === \"workers-ai\") {\n\t\t\trequest.endpoint = query.model as string;\n\t\t\tdelete query.model;\n\t\t\tdelete query.instructions;\n\t\t}\n\n\t\tif (config.apiKey) {\n\t\t\trequest.headers[\"authorization\"] = `Bearer ${config.apiKey}`;\n\t\t}\n\n\t\tif (\"binding\" in config) {\n\t\t\treturn config.binding.run(request);\n\t\t}\n\n\t\treturn fetch(\n\t\t\t`https://gateway.ai.cloudflare.com/v1/${config.accountId}/${config.gatewayId}`,\n\t\t\t{\n\t\t\t\t...init,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...headers,\n\t\t\t\t\t...cacheHeaders,\n\t\t\t\t\t...(config.cfApiKey\n\t\t\t\t\t\t? { \"cf-aig-authorization\": `Bearer ${config.cfApiKey}` }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(request),\n\t\t\t},\n\t\t);\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// createWorkersAiBindingFetch -- shim that makes env.AI look like an OpenAI endpoint\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize messages before passing to Workers AI binding.\n *\n * The binding has strict schema validation that may differ from the OpenAI API:\n * - `content` must be a string (not null)\n * - `tool_call_id` must match `[a-zA-Z0-9]{9}` pattern\n *\n * This function patches these fields so that the full tool-call round-trip works\n * even though the binding's own generated IDs may not pass its validation.\n */\nfunction normalizeMessagesForBinding(\n\tmessages: Record<string, unknown>[],\n): Record<string, unknown>[] {\n\treturn messages.map((msg) => {\n\t\tconst normalized = { ...msg };\n\n\t\t// content: null → content: \"\"\n\t\tif (normalized.content === null || normalized.content === undefined) {\n\t\t\tnormalized.content = \"\";\n\t\t}\n\n\t\t// Normalize tool_call_id on tool messages\n\t\tif (normalized.tool_call_id && typeof normalized.tool_call_id === \"string\") {\n\t\t\tnormalized.tool_call_id = sanitizeToolCallId(normalized.tool_call_id);\n\t\t}\n\n\t\t// Normalize tool_calls[].id on assistant messages\n\t\tif (Array.isArray(normalized.tool_calls)) {\n\t\t\tnormalized.tool_calls = (normalized.tool_calls as Record<string, unknown>[]).map(\n\t\t\t\t(tc) => {\n\t\t\t\t\tif (tc.id && typeof tc.id === \"string\") {\n\t\t\t\t\t\treturn { ...tc, id: sanitizeToolCallId(tc.id) };\n\t\t\t\t\t}\n\t\t\t\t\treturn tc;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\treturn normalized;\n\t});\n}\n\n/**\n * Strip non-alphanumeric characters and ensure the ID is exactly 9 chars,\n * matching Workers AI's `[a-zA-Z0-9]{9}` validation pattern.\n *\n * **Why this exists:** The Workers AI binding validates `tool_call_id` with\n * a strict `[a-zA-Z0-9]{9}` regex, but it *generates* IDs like\n * `chatcmpl-tool-875d3ec6179676ae` (with dashes, >9 chars). Those IDs are\n * then rejected when sent back in a follow-up request. This is a known\n * Workers AI issue — see workers-ai.md (Issue 3). Once the Workers AI team\n * fixes the validation, this function becomes an idempotent no-op for\n * IDs that already match the pattern.\n */\nfunction sanitizeToolCallId(id: string): string {\n\tconst alphanumeric = id.replace(/[^a-zA-Z0-9]/g, \"\");\n\t// Pad with zeros if too short, truncate if too long\n\treturn alphanumeric.slice(0, 9).padEnd(9, \"0\");\n}\n\n/**\n * Creates a fetch function that intercepts OpenAI SDK requests and translates them\n * to Workers AI binding calls (env.AI.run). This allows the WorkersAiTextAdapter\n * to use the OpenAI SDK against a plain Workers AI binding.\n *\n * NOTE: The `input` URL parameter is intentionally ignored. The model name and all\n * request parameters are extracted from the JSON body, matching Workers AI's\n * `binding.run(model, inputs)` calling convention.\n */\nexport function createWorkersAiBindingFetch(binding: WorkersAiBinding): typeof fetch {\n\treturn async (_input, init) => {\n\t\tif (!init?.body) {\n\t\t\treturn new Response(\"No body\", { status: 400 });\n\t\t}\n\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = JSON.parse(init.body as string);\n\t\t} catch {\n\t\t\treturn new Response(\"Invalid JSON body\", { status: 400 });\n\t\t}\n\n\t\tconst model = body.model as string;\n\t\tconst stream = body.stream as boolean | undefined;\n\n\t\t// Build Workers AI inputs from OpenAI format\n\t\tconst inputs: Record<string, unknown> = {};\n\t\tif (body.messages) {\n\t\t\tinputs.messages = normalizeMessagesForBinding(\n\t\t\t\tbody.messages as Record<string, unknown>[],\n\t\t\t);\n\t\t}\n\t\tif (body.tools) inputs.tools = body.tools;\n\t\tif (typeof body.temperature === \"number\") inputs.temperature = body.temperature;\n\t\tif (typeof body.max_tokens === \"number\") inputs.max_tokens = body.max_tokens;\n\t\tif (body.response_format) inputs.response_format = body.response_format;\n\t\tif (stream) inputs.stream = true;\n\n\t\tconst result = await binding.run(model, inputs);\n\n\t\tif (stream && result instanceof ReadableStream) {\n\t\t\t// Workers AI returns an SSE stream with `data: {\"response\":\"chunk\"}` format.\n\t\t\t// Transform it to OpenAI-compatible SSE format.\n\t\t\tconst transformed = transformWorkersAiStream(\n\t\t\t\tresult as ReadableStream<Uint8Array>,\n\t\t\t\tmodel,\n\t\t\t);\n\t\t\treturn new Response(transformed, {\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/event-stream\",\n\t\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Graceful degradation: some models return a complete (non-streaming)\n\t\t// response even when `stream: true` is requested. Fall through to the\n\t\t// non-streaming wrapper which produces a valid OpenAI Chat Completion\n\t\t// response that the SDK can consume.\n\n\t\t// Non-streaming: Workers AI returns { response: \"text\", tool_calls?: [...] }\n\t\t// Wrap into OpenAI Chat Completion format.\n\t\tconst responseObj =\n\t\t\ttypeof result === \"object\" && result !== null\n\t\t\t\t? (result as Record<string, unknown>)\n\t\t\t\t: { response: String(result) };\n\n\t\tconst responseText = typeof responseObj.response === \"string\" ? responseObj.response : \"\";\n\n\t\tconst message: Record<string, unknown> = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: responseText,\n\t\t};\n\t\tlet finishReason = \"stop\";\n\n\t\t// Handle tool calls if present in Workers AI response\n\t\tif (Array.isArray(responseObj.tool_calls) && responseObj.tool_calls.length > 0) {\n\t\t\tfinishReason = \"tool_calls\";\n\t\t\tmessage.tool_calls = responseObj.tool_calls.map(\n\t\t\t\t(tc: {\n\t\t\t\t\tid?: string;\n\t\t\t\t\tname?: string;\n\t\t\t\t\targuments: unknown;\n\t\t\t\t\tfunction?: { name: string; arguments?: unknown };\n\t\t\t\t}) => ({\n\t\t\t\t\tid: sanitizeToolCallId(tc.id || crypto.randomUUID()),\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: tc.function?.name || tc.name || \"\",\n\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\ttypeof (tc.function?.arguments ?? tc.arguments) === \"string\"\n\t\t\t\t\t\t\t\t? ((tc.function?.arguments ?? tc.arguments) as string)\n\t\t\t\t\t\t\t\t: JSON.stringify(tc.function?.arguments ?? tc.arguments ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tconst openAiResponse = {\n\t\t\tid: `workers-ai-${crypto.randomUUID()}`,\n\t\t\tobject: \"chat.completion\",\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel,\n\t\t\tchoices: [{ index: 0, message, finish_reason: finishReason }],\n\t\t};\n\n\t\treturn new Response(JSON.stringify(openAiResponse), {\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t});\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Stream transformer: Workers AI SSE -> OpenAI-compatible SSE\n// Uses TransformStream for proper backpressure.\n// ---------------------------------------------------------------------------\n\n/**\n * Transforms a Workers AI SSE stream (data: {\"response\":\"chunk\"}) into\n * an OpenAI-compatible SSE stream (data: {\"choices\":[{\"delta\":{\"content\":\"chunk\"}}]}).\n *\n * Workers AI binding streams tool calls in an OpenAI-like nested format:\n * { tool_calls: [{ id, type, index, function: { name, arguments } }] }\n * Arguments are streamed incrementally across multiple SSE chunks, so the\n * transformer must forward them as incremental deltas rather than a single blob.\n */\nfunction transformWorkersAiStream(\n\tsource: ReadableStream<Uint8Array>,\n\tmodel: string,\n): ReadableStream<Uint8Array> {\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\t// Generate a stable ID and timestamp for the entire stream, matching OpenAI's\n\t// convention where all chunks in a single response share the same id/created.\n\tconst streamId = `workers-ai-${crypto.randomUUID()}`;\n\tconst created = Math.floor(Date.now() / 1000);\n\tlet buffer = \"\";\n\tlet hasToolCalls = false;\n\t// When true, the source stream is already in OpenAI format (some models\n\t// like Qwen3, Kimi K2.5 stream OpenAI-compatible SSE through the binding).\n\t// In that case, flush() should only emit [DONE] and skip the finish chunk.\n\tlet isOpenAiFormat = false;\n\t// Track which tool call indices we've already emitted an `id` for,\n\t// so subsequent argument deltas don't duplicate the id/type/name fields.\n\tconst emittedToolCallStart = new Set<number>();\n\n\treturn source.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tbuffer += decoder.decode(chunk, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tconst trimmed = line.trim();\n\t\t\t\t\tif (!trimmed || !trimmed.startsWith(\"data: \")) continue;\n\t\t\t\t\tconst data = trimmed.slice(6);\n\n\t\t\t\t\t// Swallow source [DONE]; we emit our own in flush()\n\t\t\t\t\tif (data === \"[DONE]\") continue;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = JSON.parse(data);\n\n\t\t\t\t\t\t// Some models (Qwen3, Kimi K2.5) return OpenAI-compatible format\n\t\t\t\t\t\t// directly through the binding, with `choices[].delta.content` and\n\t\t\t\t\t\t// optional `reasoning_content`. Detect this and pass through as-is.\n\t\t\t\t\t\tif (parsed.choices !== undefined) {\n\t\t\t\t\t\t\t// Already OpenAI format — pass through with only tool_call_id\n\t\t\t\t\t\t\t// sanitization for any tool calls present.\n\t\t\t\t\t\t\tisOpenAiFormat = true;\n\t\t\t\t\t\t\tconst choice = parsed.choices?.[0];\n\t\t\t\t\t\t\tif (choice?.delta?.tool_calls) {\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\t\t\t\t\t\t\t\tfor (const tc of choice.delta.tool_calls) {\n\t\t\t\t\t\t\t\t\tif (tc.id && typeof tc.id === \"string\") {\n\t\t\t\t\t\t\t\t\t\ttc.id = sanitizeToolCallId(tc.id);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (choice?.finish_reason === \"tool_calls\") {\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(parsed)}\\n\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// --- Workers AI native format handling below ---\n\n\t\t\t\t\t\t// Text content\n\t\t\t\t\t\tif (parsed.response != null && parsed.response !== \"\") {\n\t\t\t\t\t\t\tconst openAiChunk = {\n\t\t\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\t\t\tcreated,\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\t\t\tdelta: { content: parsed.response },\n\t\t\t\t\t\t\t\t\t\tfinish_reason: null,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(openAiChunk)}\\n\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Tool calls — Workers AI binding streams these incrementally:\n\t\t\t\t\t\t// Chunk A: { id, type, index, function: { name } } — start\n\t\t\t\t\t\t// Chunk B: { index, function: { arguments: \"partial...\" } } — args delta\n\t\t\t\t\t\t// Chunk C: { index, function: { arguments: \"rest...\" } } — args delta\n\t\t\t\t\t\t// Chunk D: { id: null, type: null, index, function: { name: null, arguments: \"\" } } — finalize (skip)\n\t\t\t\t\t\tif (Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n\t\t\t\t\t\t\tfor (const tc of parsed.tool_calls) {\n\t\t\t\t\t\t\t\tconst tcIndex = tc.index ?? 0;\n\n\t\t\t\t\t\t\t\t// Resolve name and arguments from either nested or flat format\n\t\t\t\t\t\t\t\tconst tcName = tc.function?.name ?? tc.name ?? null;\n\t\t\t\t\t\t\t\tconst tcArgs = tc.function?.arguments ?? tc.arguments ?? null;\n\t\t\t\t\t\t\t\tconst tcId = tc.id ?? null;\n\n\t\t\t\t\t\t\t\t// Skip finalization chunks where everything is null/empty\n\t\t\t\t\t\t\t\tif (!tcId && !tcName && (!tcArgs || tcArgs === \"\")) continue;\n\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\n\t\t\t\t\t\t\t\t// Build the OpenAI-compatible tool_calls delta\n\t\t\t\t\t\t\t\tconst toolCallDelta: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t\tindex: tcIndex,\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tif (!emittedToolCallStart.has(tcIndex)) {\n\t\t\t\t\t\t\t\t\t// First chunk for this tool call index — emit id, type, name.\n\t\t\t\t\t\t\t\t\t// Use sanitizeToolCallId so the ID survives round-trip through\n\t\t\t\t\t\t\t\t\t// the binding's strict `[a-zA-Z0-9]{9}` validation.\n\t\t\t\t\t\t\t\t\temittedToolCallStart.add(tcIndex);\n\t\t\t\t\t\t\t\t\tconst rawId = tcId || `call${streamId}${tcIndex}`;\n\t\t\t\t\t\t\t\t\ttoolCallDelta.id = sanitizeToolCallId(rawId);\n\t\t\t\t\t\t\t\t\ttoolCallDelta.type = \"function\";\n\t\t\t\t\t\t\t\t\ttoolCallDelta.function = {\n\t\t\t\t\t\t\t\t\t\tname: tcName || \"\",\n\t\t\t\t\t\t\t\t\t\t// Include arguments if they arrive in the same chunk\n\t\t\t\t\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\t\t\t\t\ttcArgs != null\n\t\t\t\t\t\t\t\t\t\t\t\t? typeof tcArgs === \"string\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? tcArgs\n\t\t\t\t\t\t\t\t\t\t\t\t\t: JSON.stringify(tcArgs)\n\t\t\t\t\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Subsequent chunks — only include arguments delta\n\t\t\t\t\t\t\t\t\tif (tcArgs != null && tcArgs !== \"\") {\n\t\t\t\t\t\t\t\t\t\ttoolCallDelta.function = {\n\t\t\t\t\t\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\t\t\t\t\t\ttypeof tcArgs === \"string\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? tcArgs\n\t\t\t\t\t\t\t\t\t\t\t\t\t: JSON.stringify(tcArgs),\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcontinue; // Nothing useful to forward\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst toolChunk = {\n\t\t\t\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\t\t\t\tcreated,\n\t\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\t\t\t\tdelta: { tool_calls: [toolCallDelta] },\n\t\t\t\t\t\t\t\t\t\t\tfinish_reason: null,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(toolChunk)}\\n\\n`),\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} catch (e) {\n\t\t\t\t\t\t// Log malformed SSE events for debugging; don't break the stream.\n\t\t\t\t\t\tconsole.warn(\"[tanstack-ai] failed to parse SSE event:\", data, e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tif (!isOpenAiFormat) {\n\t\t\t\t\t// Workers AI native format: emit a finish chunk with stop/tool_calls\n\t\t\t\t\tconst finalChunk = {\n\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\tcreated,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\tdelta: {},\n\t\t\t\t\t\t\t\tfinish_reason: hasToolCalls ? \"tool_calls\" : \"stop\",\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\tcontroller.enqueue(encoder.encode(`data: ${JSON.stringify(finalChunk)}\\n\\n`));\n\t\t\t\t}\n\t\t\t\t// OpenAI format already includes its own finish_reason in the stream.\n\t\t\t\t// Either way, emit a [DONE] sentinel.\n\t\t\t\tcontroller.enqueue(encoder.encode(\"data: [DONE]\\n\\n\"));\n\t\t\t},\n\t\t}),\n\t);\n}\n"],"mappings":";AAqHO,SAAS,sBACf,QACyC;AAGzC,SACC,aAAa,UACb,OAAQ,OAAO,QAA+C,YAAY;AAE5E;AAGO,SAAS,0BACf,QAC6C;AAC7C,SAAO,eAAe,UAAU,YAAY,UAAU,EAAE,eAAe;AACxE;AAGO,SAAS,gBAAgB,QAAkE;AACjG,MAAI,eAAe,OAAQ,QAAO;AAElC,SAAO,aAAa,UAAU,CAAC,sBAAsB,MAAM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