@mariozechner/pi-ai 0.67.5 → 0.67.6

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 (43) hide show
  1. package/dist/index.d.ts +2 -2
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/models.generated.d.ts.map +1 -1
  5. package/dist/models.generated.js +5 -5
  6. package/dist/models.generated.js.map +1 -1
  7. package/dist/providers/amazon-bedrock.d.ts +12 -0
  8. package/dist/providers/amazon-bedrock.d.ts.map +1 -1
  9. package/dist/providers/amazon-bedrock.js +12 -1
  10. package/dist/providers/amazon-bedrock.js.map +1 -1
  11. package/dist/providers/anthropic.d.ts +13 -0
  12. package/dist/providers/anthropic.d.ts.map +1 -1
  13. package/dist/providers/anthropic.js +17 -5
  14. package/dist/providers/anthropic.js.map +1 -1
  15. package/dist/providers/azure-openai-responses.d.ts.map +1 -1
  16. package/dist/providers/azure-openai-responses.js +5 -1
  17. package/dist/providers/azure-openai-responses.js.map +1 -1
  18. package/dist/providers/faux.d.ts.map +1 -1
  19. package/dist/providers/faux.js +1 -0
  20. package/dist/providers/faux.js.map +1 -1
  21. package/dist/providers/google-gemini-cli.d.ts.map +1 -1
  22. package/dist/providers/google-gemini-cli.js +3 -0
  23. package/dist/providers/google-gemini-cli.js.map +1 -1
  24. package/dist/providers/openai-codex-responses.d.ts.map +1 -1
  25. package/dist/providers/openai-codex-responses.js +2 -7
  26. package/dist/providers/openai-codex-responses.js.map +1 -1
  27. package/dist/providers/openai-completions.d.ts.map +1 -1
  28. package/dist/providers/openai-completions.js +5 -1
  29. package/dist/providers/openai-completions.js.map +1 -1
  30. package/dist/providers/openai-responses.d.ts.map +1 -1
  31. package/dist/providers/openai-responses.js +6 -2
  32. package/dist/providers/openai-responses.js.map +1 -1
  33. package/dist/providers/simple-options.d.ts.map +1 -1
  34. package/dist/providers/simple-options.js +1 -0
  35. package/dist/providers/simple-options.js.map +1 -1
  36. package/dist/types.d.ts +9 -0
  37. package/dist/types.d.ts.map +1 -1
  38. package/dist/types.js.map +1 -1
  39. package/dist/utils/headers.d.ts +2 -0
  40. package/dist/utils/headers.d.ts.map +1 -0
  41. package/dist/utils/headers.js +8 -0
  42. package/dist/utils/headers.js.map +1 -0
  43. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"azure-openai-responses.js","sourceRoot":"","sources":["../../src/providers/azure-openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAU7C,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACvH,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAEvE,MAAM,yBAAyB,GAAG,IAAI,CAAC;AACvC,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,cAAc,EAAE,UAAU,EAAE,wBAAwB,CAAC,CAAC,CAAC;AAE5G,SAAS,sBAAsB,CAAC,KAAyB,EAAuB;IAC/E,MAAM,GAAG,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,IAAI,CAAC,KAAK;QAAE,OAAO,GAAG,CAAC;IACvB,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACtC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,OAAO;YAAE,SAAS;QACvB,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACxD,IAAI,CAAC,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AAS,CAAC;IAC/C,CAAC;IAED,IAAI,OAAO,EAAE,WAAW,KAAK,SAAS,EAAE,CAAC;QACxC,MAAM,CAAC,WAAW,GAAG,OAAO,EAAE,WAAW,CAAC;IAC3C,CAAC;IAED,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,MAAM,CAAC,KAAK,GAAG,qBAAqB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC;IAED,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;QACrB,IAAI,OAAO,EAAE,eAAe,IAAI,OAAO,EAAE,gBAAgB,EAAE,CAAC;YAC3D,MAAM,CAAC,SAAS,GAAG;gBAClB,MAAM,EAAE,OAAO,EAAE,eAAe,IAAI,QAAQ;gBAC5C,OAAO,EAAE,OAAO,EAAE,gBAAgB,IAAI,MAAM;aAC5C,CAAC;YACF,MAAM,CAAC,OAAO,GAAG,CAAC,6BAA6B,CAAC,CAAC;QAClD,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;QACvC,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import { AzureOpenAI } from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { supportsXhigh } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\nconst DEFAULT_AZURE_API_VERSION = \"v1\";\nconst AZURE_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\", \"azure-openai-responses\"]);\n\nfunction parseDeploymentNameMap(value: string | undefined): Map<string, string> {\n\tconst map = new Map<string, string>();\n\tif (!value) return map;\n\tfor (const entry of value.split(\",\")) {\n\t\tconst trimmed = entry.trim();\n\t\tif (!trimmed) continue;\n\t\tconst [modelId, deploymentName] = trimmed.split(\"=\", 2);\n\t\tif (!modelId || !deploymentName) continue;\n\t\tmap.set(modelId.trim(), deploymentName.trim());\n\t}\n\treturn map;\n}\n\nfunction resolveDeploymentName(model: Model<\"azure-openai-responses\">, options?: AzureOpenAIResponsesOptions): string {\n\tif (options?.azureDeploymentName) {\n\t\treturn options.azureDeploymentName;\n\t}\n\tconst mappedDeployment = parseDeploymentNameMap(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(model.id);\n\treturn mappedDeployment || model.id;\n}\n\n// Azure OpenAI Responses-specific options\nexport interface AzureOpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tazureApiVersion?: string;\n\tazureResourceName?: string;\n\tazureBaseUrl?: string;\n\tazureDeploymentName?: string;\n}\n\n/**\n * Generate function for Azure OpenAI Responses API\n */\nexport const streamAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", AzureOpenAIResponsesOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions?: AzureOpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst deploymentName = resolveDeploymentName(model, options);\n\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"azure-openai-responses\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\t// Create Azure OpenAI client\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst client = createClient(model, apiKey, options);\n\t\t\tlet params = buildParams(model, context, options, deploymentName);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as ResponseCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst openaiStream = await client.responses.create(\n\t\t\t\tparams,\n\t\t\t\toptions?.signal ? { signal: options.signal } : undefined,\n\t\t\t);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);\n\n\treturn streamAzureOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies AzureOpenAIResponsesOptions);\n};\n\nfunction normalizeAzureBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\nfunction buildDefaultBaseUrl(resourceName: string): string {\n\treturn `https://${resourceName}.openai.azure.com/openai/v1`;\n}\n\nfunction resolveAzureConfig(\n\tmodel: Model<\"azure-openai-responses\">,\n\toptions?: AzureOpenAIResponsesOptions,\n): { baseUrl: string; apiVersion: string } {\n\tconst apiVersion = options?.azureApiVersion || process.env.AZURE_OPENAI_API_VERSION || DEFAULT_AZURE_API_VERSION;\n\n\tconst baseUrl = options?.azureBaseUrl?.trim() || process.env.AZURE_OPENAI_BASE_URL?.trim() || undefined;\n\tconst resourceName = options?.azureResourceName || process.env.AZURE_OPENAI_RESOURCE_NAME;\n\n\tlet resolvedBaseUrl = baseUrl;\n\n\tif (!resolvedBaseUrl && resourceName) {\n\t\tresolvedBaseUrl = buildDefaultBaseUrl(resourceName);\n\t}\n\n\tif (!resolvedBaseUrl && model.baseUrl) {\n\t\tresolvedBaseUrl = model.baseUrl;\n\t}\n\n\tif (!resolvedBaseUrl) {\n\t\tthrow new Error(\n\t\t\t\"Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.\",\n\t\t);\n\t}\n\n\treturn {\n\t\tbaseUrl: normalizeAzureBaseUrl(resolvedBaseUrl),\n\t\tapiVersion,\n\t};\n}\n\nfunction createClient(model: Model<\"azure-openai-responses\">, apiKey: string, options?: AzureOpenAIResponsesOptions) {\n\tif (!apiKey) {\n\t\tif (!process.env.AZURE_OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.AZURE_OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\n\tif (options?.headers) {\n\t\tObject.assign(headers, options.headers);\n\t}\n\n\tconst { baseUrl, apiVersion } = resolveAzureConfig(model, options);\n\n\treturn new AzureOpenAI({\n\t\tapiKey,\n\t\tapiVersion,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t\tbaseURL: baseUrl,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions: AzureOpenAIResponsesOptions | undefined,\n\tdeploymentName: string,\n) {\n\tconst messages = convertResponsesMessages(model, context, AZURE_TOOL_CALL_PROVIDERS);\n\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: deploymentName,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: options?.sessionId,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = options?.maxTokens;\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\n\tif (model.reasoning) {\n\t\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: options?.reasoningEffort || \"medium\",\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else {\n\t\t\tparams.reasoning = { effort: \"none\" };\n\t\t}\n\t}\n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,IAAI,OAAO,EAAE,SAAS,EAAE,CAAC;QACxB,MAAM,CAAC,iBAAiB,GAAG,OAAO,EAAE,SAAS,CAAC;IAC/C,CAAC;IAED,IAAI,OAAO,EAAE,WAAW,KAAK,SAAS,EAAE,CAAC;QACxC,MAAM,CAAC,WAAW,GAAG,OAAO,EAAE,WAAW,CAAC;IAC3C,CAAC;IAED,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,MAAM,CAAC,KAAK,GAAG,qBAAqB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC;IAED,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;QACrB,IAAI,OAAO,EAAE,eAAe,IAAI,OAAO,EAAE,gBAAgB,EAAE,CAAC;YAC3D,MAAM,CAAC,SAAS,GAAG;gBAClB,MAAM,EAAE,OAAO,EAAE,eAAe,IAAI,QAAQ;gBAC5C,OAAO,EAAE,OAAO,EAAE,gBAAgB,IAAI,MAAM;aAC5C,CAAC;YACF,MAAM,CAAC,OAAO,GAAG,CAAC,6BAA6B,CAAC,CAAC;QAClD,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;QACvC,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import { AzureOpenAI } from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { supportsXhigh } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { headersToRecord } from \"../utils/headers.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\nconst DEFAULT_AZURE_API_VERSION = \"v1\";\nconst AZURE_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\", \"azure-openai-responses\"]);\n\nfunction parseDeploymentNameMap(value: string | undefined): Map<string, string> {\n\tconst map = new Map<string, string>();\n\tif (!value) return map;\n\tfor (const entry of value.split(\",\")) {\n\t\tconst trimmed = entry.trim();\n\t\tif (!trimmed) continue;\n\t\tconst [modelId, deploymentName] = trimmed.split(\"=\", 2);\n\t\tif (!modelId || !deploymentName) continue;\n\t\tmap.set(modelId.trim(), deploymentName.trim());\n\t}\n\treturn map;\n}\n\nfunction resolveDeploymentName(model: Model<\"azure-openai-responses\">, options?: AzureOpenAIResponsesOptions): string {\n\tif (options?.azureDeploymentName) {\n\t\treturn options.azureDeploymentName;\n\t}\n\tconst mappedDeployment = parseDeploymentNameMap(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(model.id);\n\treturn mappedDeployment || model.id;\n}\n\n// Azure OpenAI Responses-specific options\nexport interface AzureOpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tazureApiVersion?: string;\n\tazureResourceName?: string;\n\tazureBaseUrl?: string;\n\tazureDeploymentName?: string;\n}\n\n/**\n * Generate function for Azure OpenAI Responses API\n */\nexport const streamAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", AzureOpenAIResponsesOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions?: AzureOpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst deploymentName = resolveDeploymentName(model, options);\n\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"azure-openai-responses\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\t// Create Azure OpenAI client\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst client = createClient(model, apiKey, options);\n\t\t\tlet params = buildParams(model, context, options, deploymentName);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as ResponseCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst { data: openaiStream, response } = await client.responses\n\t\t\t\t.create(params, options?.signal ? { signal: options.signal } : undefined)\n\t\t\t\t.withResponse();\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);\n\n\treturn streamAzureOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies AzureOpenAIResponsesOptions);\n};\n\nfunction normalizeAzureBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\nfunction buildDefaultBaseUrl(resourceName: string): string {\n\treturn `https://${resourceName}.openai.azure.com/openai/v1`;\n}\n\nfunction resolveAzureConfig(\n\tmodel: Model<\"azure-openai-responses\">,\n\toptions?: AzureOpenAIResponsesOptions,\n): { baseUrl: string; apiVersion: string } {\n\tconst apiVersion = options?.azureApiVersion || process.env.AZURE_OPENAI_API_VERSION || DEFAULT_AZURE_API_VERSION;\n\n\tconst baseUrl = options?.azureBaseUrl?.trim() || process.env.AZURE_OPENAI_BASE_URL?.trim() || undefined;\n\tconst resourceName = options?.azureResourceName || process.env.AZURE_OPENAI_RESOURCE_NAME;\n\n\tlet resolvedBaseUrl = baseUrl;\n\n\tif (!resolvedBaseUrl && resourceName) {\n\t\tresolvedBaseUrl = buildDefaultBaseUrl(resourceName);\n\t}\n\n\tif (!resolvedBaseUrl && model.baseUrl) {\n\t\tresolvedBaseUrl = model.baseUrl;\n\t}\n\n\tif (!resolvedBaseUrl) {\n\t\tthrow new Error(\n\t\t\t\"Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.\",\n\t\t);\n\t}\n\n\treturn {\n\t\tbaseUrl: normalizeAzureBaseUrl(resolvedBaseUrl),\n\t\tapiVersion,\n\t};\n}\n\nfunction createClient(model: Model<\"azure-openai-responses\">, apiKey: string, options?: AzureOpenAIResponsesOptions) {\n\tif (!apiKey) {\n\t\tif (!process.env.AZURE_OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.AZURE_OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\n\tif (options?.headers) {\n\t\tObject.assign(headers, options.headers);\n\t}\n\n\tconst { baseUrl, apiVersion } = resolveAzureConfig(model, options);\n\n\treturn new AzureOpenAI({\n\t\tapiKey,\n\t\tapiVersion,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t\tbaseURL: baseUrl,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions: AzureOpenAIResponsesOptions | undefined,\n\tdeploymentName: string,\n) {\n\tconst messages = convertResponsesMessages(model, context, AZURE_TOOL_CALL_PROVIDERS);\n\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: deploymentName,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: options?.sessionId,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = options?.maxTokens;\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\n\tif (model.reasoning) {\n\t\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: options?.reasoningEffort || \"medium\",\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else {\n\t\t\tparams.reasoning = { effort: \"none\" };\n\t\t}\n\t}\n\n\treturn params;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"faux.d.ts","sourceRoot":"","sources":["../../src/providers/faux.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,gBAAgB,EAEhB,OAAO,EAGP,KAAK,EAGL,aAAa,EACb,WAAW,EACX,eAAe,EACf,QAAQ,EAGR,MAAM,aAAa,CAAC;AAoBrB,MAAM,WAAW,mBAAmB;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,KAAK,CAAC,EAAE,CAAC,MAAM,GAAG,OAAO,CAAC,EAAE,CAAC;IAC7B,IAAI,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;IAChF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,eAAe,GAAG,QAAQ,CAAC;AAExE,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CAElD;AAED,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,eAAe,CAE9D;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,GAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,QAAQ,CAOrH;AASD,wBAAgB,oBAAoB,CACnC,OAAO,EAA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,EAAE,gBAAgB,EAAE,KAAK,IAAI,CAAC;IACtD,eAAe,EAAE,CAAC,SAAS,EAAE,gBAAgB,EAAE,KAAK,IAAI,CAAC;IACzD,uBAAuB,EAAE,MAAM,MAAM,CAAC;IACtC,UAAU,EAAE,MAAM,IAAI,CAAC;CACvB;AAyQD,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,2BAAgC,GAAG,wBAAwB,CA2GxG","sourcesContent":["import { registerApiProvider, unregisterApiProviders } from \"../api-registry.js\";\nimport type {\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tToolCall,\n\tToolResultMessage,\n\tUsage,\n} from \"../types.js\";\nimport { createAssistantMessageEventStream } from \"../utils/event-stream.js\";\n\nconst DEFAULT_API = \"faux\";\nconst DEFAULT_PROVIDER = \"faux\";\nconst DEFAULT_MODEL_ID = \"faux-1\";\nconst DEFAULT_MODEL_NAME = \"Faux Model\";\nconst DEFAULT_BASE_URL = \"http://localhost:0\";\nconst DEFAULT_MIN_TOKEN_SIZE = 3;\nconst DEFAULT_MAX_TOKEN_SIZE = 5;\n\nconst DEFAULT_USAGE: Usage = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FauxModelDefinition {\n\tid: string;\n\tname?: string;\n\treasoning?: boolean;\n\tinput?: (\"text\" | \"image\")[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n}\n\nexport type FauxContentBlock = TextContent | ThinkingContent | ToolCall;\n\nexport function fauxText(text: string): TextContent {\n\treturn { type: \"text\", text };\n}\n\nexport function fauxThinking(thinking: string): ThinkingContent {\n\treturn { type: \"thinking\", thinking };\n}\n\nexport function fauxToolCall(name: string, arguments_: ToolCall[\"arguments\"], options: { id?: string } = {}): ToolCall {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: options.id ?? randomId(\"tool\"),\n\t\tname,\n\t\targuments: arguments_,\n\t};\n}\n\nfunction normalizeFauxAssistantContent(content: string | FauxContentBlock | FauxContentBlock[]): FauxContentBlock[] {\n\tif (typeof content === \"string\") {\n\t\treturn [fauxText(content)];\n\t}\n\treturn Array.isArray(content) ? content : [content];\n}\n\nexport function fauxAssistantMessage(\n\tcontent: string | FauxContentBlock | FauxContentBlock[],\n\toptions: {\n\t\tstopReason?: AssistantMessage[\"stopReason\"];\n\t\terrorMessage?: string;\n\t\tresponseId?: string;\n\t\ttimestamp?: number;\n\t} = {},\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: normalizeFauxAssistantContent(content),\n\t\tapi: DEFAULT_API,\n\t\tprovider: DEFAULT_PROVIDER,\n\t\tmodel: DEFAULT_MODEL_ID,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: options.stopReason ?? \"stop\",\n\t\terrorMessage: options.errorMessage,\n\t\tresponseId: options.responseId,\n\t\ttimestamp: options.timestamp ?? Date.now(),\n\t};\n}\n\nexport type FauxResponseFactory = (\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tstate: { callCount: number },\n\tmodel: Model<string>,\n) => AssistantMessage | Promise<AssistantMessage>;\n\nexport type FauxResponseStep = AssistantMessage | FauxResponseFactory;\n\nexport interface RegisterFauxProviderOptions {\n\tapi?: string;\n\tprovider?: string;\n\tmodels?: FauxModelDefinition[];\n\ttokensPerSecond?: number;\n\ttokenSize?: {\n\t\tmin?: number;\n\t\tmax?: number;\n\t};\n}\n\nexport interface FauxProviderRegistration {\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: { callCount: number };\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n\tunregister: () => void;\n}\n\nfunction estimateTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction randomId(prefix: string): string {\n\treturn `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction contentToText(content: string | Array<TextContent | ImageContent>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\treturn `[image:${block.mimeType}:${block.data.length}]`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction assistantContentToText(content: Array<TextContent | ThinkingContent | ToolCall>): string {\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\treturn block.thinking;\n\t\t\t}\n\t\t\treturn `${block.name}:${JSON.stringify(block.arguments)}`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction toolResultToText(message: ToolResultMessage): string {\n\treturn [message.toolName, ...message.content.map((block) => contentToText([block]))].join(\"\\n\");\n}\n\nfunction messageToText(message: Message): string {\n\tif (message.role === \"user\") {\n\t\treturn contentToText(message.content);\n\t}\n\tif (message.role === \"assistant\") {\n\t\treturn assistantContentToText(message.content);\n\t}\n\treturn toolResultToText(message);\n}\n\nfunction serializeContext(context: Context): string {\n\tconst parts: string[] = [];\n\tif (context.systemPrompt) {\n\t\tparts.push(`system:${context.systemPrompt}`);\n\t}\n\tfor (const message of context.messages) {\n\t\tparts.push(`${message.role}:${messageToText(message)}`);\n\t}\n\tif (context.tools?.length) {\n\t\tparts.push(`tools:${JSON.stringify(context.tools)}`);\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\nfunction commonPrefixLength(a: string, b: string): number {\n\tconst length = Math.min(a.length, b.length);\n\tlet index = 0;\n\twhile (index < length && a[index] === b[index]) {\n\t\tindex++;\n\t}\n\treturn index;\n}\n\nfunction withUsageEstimate(\n\tmessage: AssistantMessage,\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tpromptCache: Map<string, string>,\n): AssistantMessage {\n\tconst promptText = serializeContext(context);\n\tconst promptTokens = estimateTokens(promptText);\n\tconst outputTokens = estimateTokens(assistantContentToText(message.content));\n\tlet input = promptTokens;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tconst sessionId = options?.sessionId;\n\n\tif (sessionId && options?.cacheRetention !== \"none\") {\n\t\tconst previousPrompt = promptCache.get(sessionId);\n\t\tif (previousPrompt) {\n\t\t\tconst cachedChars = commonPrefixLength(previousPrompt, promptText);\n\t\t\tcacheRead = estimateTokens(previousPrompt.slice(0, cachedChars));\n\t\t\tcacheWrite = estimateTokens(promptText.slice(cachedChars));\n\t\t\tinput = Math.max(0, promptTokens - cacheRead);\n\t\t} else {\n\t\t\tcacheWrite = promptTokens;\n\t\t}\n\t\tpromptCache.set(sessionId, promptText);\n\t}\n\n\treturn {\n\t\t...message,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput: outputTokens,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens: input + outputTokens + cacheRead + cacheWrite,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t};\n}\n\nfunction splitStringByTokenSize(text: string, minTokenSize: number, maxTokenSize: number): string[] {\n\tconst chunks: string[] = [];\n\tlet index = 0;\n\twhile (index < text.length) {\n\t\tconst tokenSize = minTokenSize + Math.floor(Math.random() * (maxTokenSize - minTokenSize + 1));\n\t\tconst charSize = Math.max(1, tokenSize * 4);\n\t\tchunks.push(text.slice(index, index + charSize));\n\t\tindex += charSize;\n\t}\n\treturn chunks.length > 0 ? chunks : [\"\"];\n}\n\nfunction cloneMessage(message: AssistantMessage, api: string, provider: string, modelId: string): AssistantMessage {\n\tconst cloned = structuredClone(message);\n\treturn {\n\t\t...cloned,\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\ttimestamp: cloned.timestamp ?? Date.now(),\n\t\tusage: cloned.usage ?? DEFAULT_USAGE,\n\t};\n}\n\nfunction createErrorMessage(error: unknown, api: string, provider: string, modelId: string): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAbortedMessage(partial: AssistantMessage): AssistantMessage {\n\treturn {\n\t\t...partial,\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: \"Request was aborted\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction scheduleChunk(chunk: string, tokensPerSecond: number | undefined): Promise<void> {\n\tif (!tokensPerSecond || tokensPerSecond <= 0) {\n\t\treturn new Promise((resolve) => queueMicrotask(resolve));\n\t}\n\tconst delayMs = (estimateTokens(chunk) / tokensPerSecond) * 1000;\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\nasync function streamWithDeltas(\n\tstream: AssistantMessageEventStream,\n\tmessage: AssistantMessage,\n\tminTokenSize: number,\n\tmaxTokenSize: number,\n\ttokensPerSecond: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tconst partial: AssistantMessage = { ...message, content: [] };\n\tif (signal?.aborted) {\n\t\tconst aborted = createAbortedMessage(partial);\n\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\tstream.end(aborted);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"start\", partial: { ...partial } });\n\n\tfor (let index = 0; index < message.content.length; index++) {\n\t\tif (signal?.aborted) {\n\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\tstream.end(aborted);\n\t\t\treturn;\n\t\t}\n\n\t\tconst block = message.content[index];\n\n\t\tif (block.type === \"thinking\") {\n\t\t\tpartial.content = [...partial.content, { type: \"thinking\", thinking: \"\" }];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as ThinkingContent).thinking += chunk;\n\t\t\t\tstream.push({ type: \"thinking_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: index,\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: { ...partial },\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (block.type === \"text\") {\n\t\t\tpartial.content = [...partial.content, { type: \"text\", text: \"\" }];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as TextContent).text += chunk;\n\t\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } });\n\t\t\tcontinue;\n\t\t}\n\n\t\tpartial.content = [...partial.content, { type: \"toolCall\", id: block.id, name: block.name, arguments: {} }];\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } });\n\t\tfor (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {\n\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\tstream.end(aborted);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t}\n\t\t(partial.content[index] as ToolCall).arguments = block.arguments;\n\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } });\n\t}\n\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\tstream.push({ type: \"error\", reason: message.stopReason, error: message });\n\t\tstream.end(message);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"done\", reason: message.stopReason, message });\n\tstream.end(message);\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst api = options.api ?? randomId(DEFAULT_API);\n\tconst provider = options.provider ?? DEFAULT_PROVIDER;\n\tconst sourceId = randomId(\"faux-provider\");\n\tconst minTokenSize = Math.max(\n\t\t1,\n\t\tMath.min(options.tokenSize?.min ?? DEFAULT_MIN_TOKEN_SIZE, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE),\n\t);\n\tconst maxTokenSize = Math.max(minTokenSize, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE);\n\tlet pendingResponses: FauxResponseStep[] = [];\n\tconst tokensPerSecond = options.tokensPerSecond;\n\tconst state = { callCount: 0 };\n\tconst promptCache = new Map<string, string>();\n\n\tconst modelDefinitions = options.models?.length\n\t\t? options.models\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tid: DEFAULT_MODEL_ID,\n\t\t\t\t\tname: DEFAULT_MODEL_NAME,\n\t\t\t\t\treasoning: false,\n\t\t\t\t\tinput: [\"text\", \"image\"] as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: 128000,\n\t\t\t\t\tmaxTokens: 16384,\n\t\t\t\t},\n\t\t\t];\n\tconst models = modelDefinitions.map((definition) => ({\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi,\n\t\tprovider,\n\t\tbaseUrl: DEFAULT_BASE_URL,\n\t\treasoning: definition.reasoning ?? false,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t})) as [Model<string>, ...Model<string>[]];\n\n\tconst stream: StreamFunction<string, StreamOptions> = (requestModel, context, streamOptions) => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst step = pendingResponses.shift();\n\t\tstate.callCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tif (!step) {\n\t\t\t\t\tlet message = createErrorMessage(\n\t\t\t\t\t\tnew Error(\"No more faux responses queued\"),\n\t\t\t\t\t\tapi,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\trequestModel.id,\n\t\t\t\t\t);\n\t\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\t\touter.end(message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst resolved =\n\t\t\t\t\ttypeof step === \"function\" ? await step(context, streamOptions, state, requestModel) : step;\n\t\t\t\tlet message = cloneMessage(resolved, api, provider, requestModel.id);\n\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\tawait streamWithDeltas(outer, message, minTokenSize, maxTokenSize, tokensPerSecond, streamOptions?.signal);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst streamSimple: StreamFunction<string, SimpleStreamOptions> = (streamModel, context, streamOptions) =>\n\t\tstream(streamModel, context, streamOptions);\n\n\tregisterApiProvider({ api, stream, streamSimple }, sourceId);\n\n\tfunction getModel(): Model<string>;\n\tfunction getModel(requestedModelId: string): Model<string> | undefined;\n\tfunction getModel(requestedModelId?: string): Model<string> | undefined {\n\t\tif (!requestedModelId) {\n\t\t\treturn models[0];\n\t\t}\n\t\treturn models.find((candidate) => candidate.id === requestedModelId);\n\t}\n\n\treturn {\n\t\tapi,\n\t\tmodels,\n\t\tgetModel,\n\t\tstate,\n\t\tsetResponses(responses) {\n\t\t\tpendingResponses = [...responses];\n\t\t},\n\t\tappendResponses(responses) {\n\t\t\tpendingResponses.push(...responses);\n\t\t},\n\t\tgetPendingResponseCount() {\n\t\t\treturn pendingResponses.length;\n\t\t},\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"faux.d.ts","sourceRoot":"","sources":["../../src/providers/faux.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,gBAAgB,EAEhB,OAAO,EAGP,KAAK,EAGL,aAAa,EACb,WAAW,EACX,eAAe,EACf,QAAQ,EAGR,MAAM,aAAa,CAAC;AAoBrB,MAAM,WAAW,mBAAmB;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAA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,CAAC,CAAC;AAElD,MAAM,MAAM,gBAAgB,GAAG,gBAAgB,GAAG,mBAAmB,CAAC;AAEtE,MAAM,WAAW,2BAA2B;IAC3C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,mBAAmB,EAAE,CAAC;IAC/B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,EAAE;QACX,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;KACb,CAAC;CACF;AAED,MAAM,WAAW,wBAAwB;IACxC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC5C,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IACrD,KAAK,EAAE;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7B,YAAY,EAAE,CAAC,SAAS,EAAE,gBAAgB,EAAE,KAAK,IAAI,CAAC;IACtD,eAAe,EAAE,CAAC,SAAS,EAAE,gBAAgB,EAAE,KAAK,IAAI,CAAC;IACzD,uBAAuB,EAAE,MAAM,MAAM,CAAC;IACtC,UAAU,EAAE,MAAM,IAAI,CAAC;CACvB;AAyQD,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,2BAAgC,GAAG,wBAAwB,CA4GxG","sourcesContent":["import { registerApiProvider, unregisterApiProviders } from \"../api-registry.js\";\nimport type {\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tToolCall,\n\tToolResultMessage,\n\tUsage,\n} from \"../types.js\";\nimport { createAssistantMessageEventStream } from \"../utils/event-stream.js\";\n\nconst DEFAULT_API = \"faux\";\nconst DEFAULT_PROVIDER = \"faux\";\nconst DEFAULT_MODEL_ID = \"faux-1\";\nconst DEFAULT_MODEL_NAME = \"Faux Model\";\nconst DEFAULT_BASE_URL = \"http://localhost:0\";\nconst DEFAULT_MIN_TOKEN_SIZE = 3;\nconst DEFAULT_MAX_TOKEN_SIZE = 5;\n\nconst DEFAULT_USAGE: Usage = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FauxModelDefinition {\n\tid: string;\n\tname?: string;\n\treasoning?: boolean;\n\tinput?: (\"text\" | \"image\")[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n}\n\nexport type FauxContentBlock = TextContent | ThinkingContent | ToolCall;\n\nexport function fauxText(text: string): TextContent {\n\treturn { type: \"text\", text };\n}\n\nexport function fauxThinking(thinking: string): ThinkingContent {\n\treturn { type: \"thinking\", thinking };\n}\n\nexport function fauxToolCall(name: string, arguments_: ToolCall[\"arguments\"], options: { id?: string } = {}): ToolCall {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: options.id ?? randomId(\"tool\"),\n\t\tname,\n\t\targuments: arguments_,\n\t};\n}\n\nfunction normalizeFauxAssistantContent(content: string | FauxContentBlock | FauxContentBlock[]): FauxContentBlock[] {\n\tif (typeof content === \"string\") {\n\t\treturn [fauxText(content)];\n\t}\n\treturn Array.isArray(content) ? content : [content];\n}\n\nexport function fauxAssistantMessage(\n\tcontent: string | FauxContentBlock | FauxContentBlock[],\n\toptions: {\n\t\tstopReason?: AssistantMessage[\"stopReason\"];\n\t\terrorMessage?: string;\n\t\tresponseId?: string;\n\t\ttimestamp?: number;\n\t} = {},\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: normalizeFauxAssistantContent(content),\n\t\tapi: DEFAULT_API,\n\t\tprovider: DEFAULT_PROVIDER,\n\t\tmodel: DEFAULT_MODEL_ID,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: options.stopReason ?? \"stop\",\n\t\terrorMessage: options.errorMessage,\n\t\tresponseId: options.responseId,\n\t\ttimestamp: options.timestamp ?? Date.now(),\n\t};\n}\n\nexport type FauxResponseFactory = (\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tstate: { callCount: number },\n\tmodel: Model<string>,\n) => AssistantMessage | Promise<AssistantMessage>;\n\nexport type FauxResponseStep = AssistantMessage | FauxResponseFactory;\n\nexport interface RegisterFauxProviderOptions {\n\tapi?: string;\n\tprovider?: string;\n\tmodels?: FauxModelDefinition[];\n\ttokensPerSecond?: number;\n\ttokenSize?: {\n\t\tmin?: number;\n\t\tmax?: number;\n\t};\n}\n\nexport interface FauxProviderRegistration {\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: { callCount: number };\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n\tunregister: () => void;\n}\n\nfunction estimateTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction randomId(prefix: string): string {\n\treturn `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction contentToText(content: string | Array<TextContent | ImageContent>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\treturn `[image:${block.mimeType}:${block.data.length}]`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction assistantContentToText(content: Array<TextContent | ThinkingContent | ToolCall>): string {\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\treturn block.thinking;\n\t\t\t}\n\t\t\treturn `${block.name}:${JSON.stringify(block.arguments)}`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction toolResultToText(message: ToolResultMessage): string {\n\treturn [message.toolName, ...message.content.map((block) => contentToText([block]))].join(\"\\n\");\n}\n\nfunction messageToText(message: Message): string {\n\tif (message.role === \"user\") {\n\t\treturn contentToText(message.content);\n\t}\n\tif (message.role === \"assistant\") {\n\t\treturn assistantContentToText(message.content);\n\t}\n\treturn toolResultToText(message);\n}\n\nfunction serializeContext(context: Context): string {\n\tconst parts: string[] = [];\n\tif (context.systemPrompt) {\n\t\tparts.push(`system:${context.systemPrompt}`);\n\t}\n\tfor (const message of context.messages) {\n\t\tparts.push(`${message.role}:${messageToText(message)}`);\n\t}\n\tif (context.tools?.length) {\n\t\tparts.push(`tools:${JSON.stringify(context.tools)}`);\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\nfunction commonPrefixLength(a: string, b: string): number {\n\tconst length = Math.min(a.length, b.length);\n\tlet index = 0;\n\twhile (index < length && a[index] === b[index]) {\n\t\tindex++;\n\t}\n\treturn index;\n}\n\nfunction withUsageEstimate(\n\tmessage: AssistantMessage,\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tpromptCache: Map<string, string>,\n): AssistantMessage {\n\tconst promptText = serializeContext(context);\n\tconst promptTokens = estimateTokens(promptText);\n\tconst outputTokens = estimateTokens(assistantContentToText(message.content));\n\tlet input = promptTokens;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tconst sessionId = options?.sessionId;\n\n\tif (sessionId && options?.cacheRetention !== \"none\") {\n\t\tconst previousPrompt = promptCache.get(sessionId);\n\t\tif (previousPrompt) {\n\t\t\tconst cachedChars = commonPrefixLength(previousPrompt, promptText);\n\t\t\tcacheRead = estimateTokens(previousPrompt.slice(0, cachedChars));\n\t\t\tcacheWrite = estimateTokens(promptText.slice(cachedChars));\n\t\t\tinput = Math.max(0, promptTokens - cacheRead);\n\t\t} else {\n\t\t\tcacheWrite = promptTokens;\n\t\t}\n\t\tpromptCache.set(sessionId, promptText);\n\t}\n\n\treturn {\n\t\t...message,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput: outputTokens,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens: input + outputTokens + cacheRead + cacheWrite,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t};\n}\n\nfunction splitStringByTokenSize(text: string, minTokenSize: number, maxTokenSize: number): string[] {\n\tconst chunks: string[] = [];\n\tlet index = 0;\n\twhile (index < text.length) {\n\t\tconst tokenSize = minTokenSize + Math.floor(Math.random() * (maxTokenSize - minTokenSize + 1));\n\t\tconst charSize = Math.max(1, tokenSize * 4);\n\t\tchunks.push(text.slice(index, index + charSize));\n\t\tindex += charSize;\n\t}\n\treturn chunks.length > 0 ? chunks : [\"\"];\n}\n\nfunction cloneMessage(message: AssistantMessage, api: string, provider: string, modelId: string): AssistantMessage {\n\tconst cloned = structuredClone(message);\n\treturn {\n\t\t...cloned,\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\ttimestamp: cloned.timestamp ?? Date.now(),\n\t\tusage: cloned.usage ?? DEFAULT_USAGE,\n\t};\n}\n\nfunction createErrorMessage(error: unknown, api: string, provider: string, modelId: string): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAbortedMessage(partial: AssistantMessage): AssistantMessage {\n\treturn {\n\t\t...partial,\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: \"Request was aborted\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction scheduleChunk(chunk: string, tokensPerSecond: number | undefined): Promise<void> {\n\tif (!tokensPerSecond || tokensPerSecond <= 0) {\n\t\treturn new Promise((resolve) => queueMicrotask(resolve));\n\t}\n\tconst delayMs = (estimateTokens(chunk) / tokensPerSecond) * 1000;\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\nasync function streamWithDeltas(\n\tstream: AssistantMessageEventStream,\n\tmessage: AssistantMessage,\n\tminTokenSize: number,\n\tmaxTokenSize: number,\n\ttokensPerSecond: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tconst partial: AssistantMessage = { ...message, content: [] };\n\tif (signal?.aborted) {\n\t\tconst aborted = createAbortedMessage(partial);\n\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\tstream.end(aborted);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"start\", partial: { ...partial } });\n\n\tfor (let index = 0; index < message.content.length; index++) {\n\t\tif (signal?.aborted) {\n\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\tstream.end(aborted);\n\t\t\treturn;\n\t\t}\n\n\t\tconst block = message.content[index];\n\n\t\tif (block.type === \"thinking\") {\n\t\t\tpartial.content = [...partial.content, { type: \"thinking\", thinking: \"\" }];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as ThinkingContent).thinking += chunk;\n\t\t\t\tstream.push({ type: \"thinking_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: index,\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: { ...partial },\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (block.type === \"text\") {\n\t\t\tpartial.content = [...partial.content, { type: \"text\", text: \"\" }];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as TextContent).text += chunk;\n\t\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } });\n\t\t\tcontinue;\n\t\t}\n\n\t\tpartial.content = [...partial.content, { type: \"toolCall\", id: block.id, name: block.name, arguments: {} }];\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } });\n\t\tfor (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {\n\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\tstream.end(aborted);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t}\n\t\t(partial.content[index] as ToolCall).arguments = block.arguments;\n\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } });\n\t}\n\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\tstream.push({ type: \"error\", reason: message.stopReason, error: message });\n\t\tstream.end(message);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"done\", reason: message.stopReason, message });\n\tstream.end(message);\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst api = options.api ?? randomId(DEFAULT_API);\n\tconst provider = options.provider ?? DEFAULT_PROVIDER;\n\tconst sourceId = randomId(\"faux-provider\");\n\tconst minTokenSize = Math.max(\n\t\t1,\n\t\tMath.min(options.tokenSize?.min ?? DEFAULT_MIN_TOKEN_SIZE, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE),\n\t);\n\tconst maxTokenSize = Math.max(minTokenSize, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE);\n\tlet pendingResponses: FauxResponseStep[] = [];\n\tconst tokensPerSecond = options.tokensPerSecond;\n\tconst state = { callCount: 0 };\n\tconst promptCache = new Map<string, string>();\n\n\tconst modelDefinitions = options.models?.length\n\t\t? options.models\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tid: DEFAULT_MODEL_ID,\n\t\t\t\t\tname: DEFAULT_MODEL_NAME,\n\t\t\t\t\treasoning: false,\n\t\t\t\t\tinput: [\"text\", \"image\"] as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: 128000,\n\t\t\t\t\tmaxTokens: 16384,\n\t\t\t\t},\n\t\t\t];\n\tconst models = modelDefinitions.map((definition) => ({\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi,\n\t\tprovider,\n\t\tbaseUrl: DEFAULT_BASE_URL,\n\t\treasoning: definition.reasoning ?? false,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t})) as [Model<string>, ...Model<string>[]];\n\n\tconst stream: StreamFunction<string, StreamOptions> = (requestModel, context, streamOptions) => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst step = pendingResponses.shift();\n\t\tstate.callCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tawait streamOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t\t\t\tif (!step) {\n\t\t\t\t\tlet message = createErrorMessage(\n\t\t\t\t\t\tnew Error(\"No more faux responses queued\"),\n\t\t\t\t\t\tapi,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\trequestModel.id,\n\t\t\t\t\t);\n\t\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\t\touter.end(message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst resolved =\n\t\t\t\t\ttypeof step === \"function\" ? await step(context, streamOptions, state, requestModel) : step;\n\t\t\t\tlet message = cloneMessage(resolved, api, provider, requestModel.id);\n\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\tawait streamWithDeltas(outer, message, minTokenSize, maxTokenSize, tokensPerSecond, streamOptions?.signal);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst streamSimple: StreamFunction<string, SimpleStreamOptions> = (streamModel, context, streamOptions) =>\n\t\tstream(streamModel, context, streamOptions);\n\n\tregisterApiProvider({ api, stream, streamSimple }, sourceId);\n\n\tfunction getModel(): Model<string>;\n\tfunction getModel(requestedModelId: string): Model<string> | undefined;\n\tfunction getModel(requestedModelId?: string): Model<string> | undefined {\n\t\tif (!requestedModelId) {\n\t\t\treturn models[0];\n\t\t}\n\t\treturn models.find((candidate) => candidate.id === requestedModelId);\n\t}\n\n\treturn {\n\t\tapi,\n\t\tmodels,\n\t\tgetModel,\n\t\tstate,\n\t\tsetResponses(responses) {\n\t\t\tpendingResponses = [...responses];\n\t\t},\n\t\tappendResponses(responses) {\n\t\t\tpendingResponses.push(...responses);\n\t\t},\n\t\tgetPendingResponseCount() {\n\t\t\treturn pendingResponses.length;\n\t\t},\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n"]}
@@ -317,6 +317,7 @@ export function registerFauxProvider(options = {}) {
317
317
  state.callCount++;
318
318
  queueMicrotask(async () => {
319
319
  try {
320
+ await streamOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);
320
321
  if (!step) {
321
322
  let message = createErrorMessage(new Error("No more faux responses queued"), api, provider, requestModel.id);
322
323
  message = withUsageEstimate(message, context, streamOptions, promptCache);
@@ -1 +1 @@
1
- {"version":3,"file":"faux.js","sourceRoot":"","sources":["../../src/providers/faux.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAiBjF,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAE7E,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAClC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,gBAAgB,GAAG,oBAAoB,CAAC;AAC9C,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,sBAAsB,GAAG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AAG;YACzB,OAAO,gBAAgB,CAAC,MAAM,CAAC;QAAA,CAC/B;QACD,UAAU,GAAG;YACZ,sBAAsB,CAAC,QAAQ,CAAC,CAAC;QAAA,CACjC;KACD,CAAC;AAAA,CACF","sourcesContent":["import { registerApiProvider, unregisterApiProviders } from \"../api-registry.js\";\nimport type {\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tToolCall,\n\tToolResultMessage,\n\tUsage,\n} from \"../types.js\";\nimport { createAssistantMessageEventStream } from \"../utils/event-stream.js\";\n\nconst DEFAULT_API = \"faux\";\nconst DEFAULT_PROVIDER = \"faux\";\nconst DEFAULT_MODEL_ID = \"faux-1\";\nconst DEFAULT_MODEL_NAME = \"Faux Model\";\nconst DEFAULT_BASE_URL = \"http://localhost:0\";\nconst DEFAULT_MIN_TOKEN_SIZE = 3;\nconst DEFAULT_MAX_TOKEN_SIZE = 5;\n\nconst DEFAULT_USAGE: Usage = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FauxModelDefinition {\n\tid: string;\n\tname?: string;\n\treasoning?: boolean;\n\tinput?: (\"text\" | \"image\")[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n}\n\nexport type FauxContentBlock = TextContent | ThinkingContent | ToolCall;\n\nexport function fauxText(text: string): TextContent {\n\treturn { type: \"text\", text };\n}\n\nexport function fauxThinking(thinking: string): ThinkingContent {\n\treturn { type: \"thinking\", thinking };\n}\n\nexport function fauxToolCall(name: string, arguments_: ToolCall[\"arguments\"], options: { id?: string } = {}): ToolCall {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: options.id ?? randomId(\"tool\"),\n\t\tname,\n\t\targuments: arguments_,\n\t};\n}\n\nfunction normalizeFauxAssistantContent(content: string | FauxContentBlock | FauxContentBlock[]): FauxContentBlock[] {\n\tif (typeof content === \"string\") {\n\t\treturn [fauxText(content)];\n\t}\n\treturn Array.isArray(content) ? content : [content];\n}\n\nexport function fauxAssistantMessage(\n\tcontent: string | FauxContentBlock | FauxContentBlock[],\n\toptions: {\n\t\tstopReason?: AssistantMessage[\"stopReason\"];\n\t\terrorMessage?: string;\n\t\tresponseId?: string;\n\t\ttimestamp?: number;\n\t} = {},\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: normalizeFauxAssistantContent(content),\n\t\tapi: DEFAULT_API,\n\t\tprovider: DEFAULT_PROVIDER,\n\t\tmodel: DEFAULT_MODEL_ID,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: options.stopReason ?? \"stop\",\n\t\terrorMessage: options.errorMessage,\n\t\tresponseId: options.responseId,\n\t\ttimestamp: options.timestamp ?? Date.now(),\n\t};\n}\n\nexport type FauxResponseFactory = (\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tstate: { callCount: number },\n\tmodel: Model<string>,\n) => AssistantMessage | Promise<AssistantMessage>;\n\nexport type FauxResponseStep = AssistantMessage | FauxResponseFactory;\n\nexport interface RegisterFauxProviderOptions {\n\tapi?: string;\n\tprovider?: string;\n\tmodels?: FauxModelDefinition[];\n\ttokensPerSecond?: number;\n\ttokenSize?: {\n\t\tmin?: number;\n\t\tmax?: number;\n\t};\n}\n\nexport interface FauxProviderRegistration {\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: { callCount: number };\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n\tunregister: () => void;\n}\n\nfunction estimateTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction randomId(prefix: string): string {\n\treturn `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction contentToText(content: string | Array<TextContent | ImageContent>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\treturn `[image:${block.mimeType}:${block.data.length}]`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction assistantContentToText(content: Array<TextContent | ThinkingContent | ToolCall>): string {\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\treturn block.thinking;\n\t\t\t}\n\t\t\treturn `${block.name}:${JSON.stringify(block.arguments)}`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction toolResultToText(message: ToolResultMessage): string {\n\treturn [message.toolName, ...message.content.map((block) => contentToText([block]))].join(\"\\n\");\n}\n\nfunction messageToText(message: Message): string {\n\tif (message.role === \"user\") {\n\t\treturn contentToText(message.content);\n\t}\n\tif (message.role === \"assistant\") {\n\t\treturn assistantContentToText(message.content);\n\t}\n\treturn toolResultToText(message);\n}\n\nfunction serializeContext(context: Context): string {\n\tconst parts: string[] = [];\n\tif (context.systemPrompt) {\n\t\tparts.push(`system:${context.systemPrompt}`);\n\t}\n\tfor (const message of context.messages) {\n\t\tparts.push(`${message.role}:${messageToText(message)}`);\n\t}\n\tif (context.tools?.length) {\n\t\tparts.push(`tools:${JSON.stringify(context.tools)}`);\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\nfunction commonPrefixLength(a: string, b: string): number {\n\tconst length = Math.min(a.length, b.length);\n\tlet index = 0;\n\twhile (index < length && a[index] === b[index]) {\n\t\tindex++;\n\t}\n\treturn index;\n}\n\nfunction withUsageEstimate(\n\tmessage: AssistantMessage,\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tpromptCache: Map<string, string>,\n): AssistantMessage {\n\tconst promptText = serializeContext(context);\n\tconst promptTokens = estimateTokens(promptText);\n\tconst outputTokens = estimateTokens(assistantContentToText(message.content));\n\tlet input = promptTokens;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tconst sessionId = options?.sessionId;\n\n\tif (sessionId && options?.cacheRetention !== \"none\") {\n\t\tconst previousPrompt = promptCache.get(sessionId);\n\t\tif (previousPrompt) {\n\t\t\tconst cachedChars = commonPrefixLength(previousPrompt, promptText);\n\t\t\tcacheRead = estimateTokens(previousPrompt.slice(0, cachedChars));\n\t\t\tcacheWrite = estimateTokens(promptText.slice(cachedChars));\n\t\t\tinput = Math.max(0, promptTokens - cacheRead);\n\t\t} else {\n\t\t\tcacheWrite = promptTokens;\n\t\t}\n\t\tpromptCache.set(sessionId, promptText);\n\t}\n\n\treturn {\n\t\t...message,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput: outputTokens,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens: input + outputTokens + cacheRead + cacheWrite,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t};\n}\n\nfunction splitStringByTokenSize(text: string, minTokenSize: number, maxTokenSize: number): string[] {\n\tconst chunks: string[] = [];\n\tlet index = 0;\n\twhile (index < text.length) {\n\t\tconst tokenSize = minTokenSize + Math.floor(Math.random() * (maxTokenSize - minTokenSize + 1));\n\t\tconst charSize = Math.max(1, tokenSize * 4);\n\t\tchunks.push(text.slice(index, index + charSize));\n\t\tindex += charSize;\n\t}\n\treturn chunks.length > 0 ? chunks : [\"\"];\n}\n\nfunction cloneMessage(message: AssistantMessage, api: string, provider: string, modelId: string): AssistantMessage {\n\tconst cloned = structuredClone(message);\n\treturn {\n\t\t...cloned,\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\ttimestamp: cloned.timestamp ?? Date.now(),\n\t\tusage: cloned.usage ?? DEFAULT_USAGE,\n\t};\n}\n\nfunction createErrorMessage(error: unknown, api: string, provider: string, modelId: string): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAbortedMessage(partial: AssistantMessage): AssistantMessage {\n\treturn {\n\t\t...partial,\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: \"Request was aborted\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction scheduleChunk(chunk: string, tokensPerSecond: number | undefined): Promise<void> {\n\tif (!tokensPerSecond || tokensPerSecond <= 0) {\n\t\treturn new Promise((resolve) => queueMicrotask(resolve));\n\t}\n\tconst delayMs = (estimateTokens(chunk) / tokensPerSecond) * 1000;\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\nasync function streamWithDeltas(\n\tstream: AssistantMessageEventStream,\n\tmessage: AssistantMessage,\n\tminTokenSize: number,\n\tmaxTokenSize: number,\n\ttokensPerSecond: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tconst partial: AssistantMessage = { ...message, content: [] };\n\tif (signal?.aborted) {\n\t\tconst aborted = createAbortedMessage(partial);\n\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\tstream.end(aborted);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"start\", partial: { ...partial } });\n\n\tfor (let index = 0; index < message.content.length; index++) {\n\t\tif (signal?.aborted) {\n\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\tstream.end(aborted);\n\t\t\treturn;\n\t\t}\n\n\t\tconst block = message.content[index];\n\n\t\tif (block.type === \"thinking\") {\n\t\t\tpartial.content = [...partial.content, { type: \"thinking\", thinking: \"\" }];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as ThinkingContent).thinking += chunk;\n\t\t\t\tstream.push({ type: \"thinking_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: index,\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: { ...partial },\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (block.type === \"text\") {\n\t\t\tpartial.content = [...partial.content, { type: \"text\", text: \"\" }];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as TextContent).text += chunk;\n\t\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } });\n\t\t\tcontinue;\n\t\t}\n\n\t\tpartial.content = [...partial.content, { type: \"toolCall\", id: block.id, name: block.name, arguments: {} }];\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } });\n\t\tfor (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {\n\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\tstream.end(aborted);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t}\n\t\t(partial.content[index] as ToolCall).arguments = block.arguments;\n\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } });\n\t}\n\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\tstream.push({ type: \"error\", reason: message.stopReason, error: message });\n\t\tstream.end(message);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"done\", reason: message.stopReason, message });\n\tstream.end(message);\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst api = options.api ?? randomId(DEFAULT_API);\n\tconst provider = options.provider ?? DEFAULT_PROVIDER;\n\tconst sourceId = randomId(\"faux-provider\");\n\tconst minTokenSize = Math.max(\n\t\t1,\n\t\tMath.min(options.tokenSize?.min ?? DEFAULT_MIN_TOKEN_SIZE, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE),\n\t);\n\tconst maxTokenSize = Math.max(minTokenSize, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE);\n\tlet pendingResponses: FauxResponseStep[] = [];\n\tconst tokensPerSecond = options.tokensPerSecond;\n\tconst state = { callCount: 0 };\n\tconst promptCache = new Map<string, string>();\n\n\tconst modelDefinitions = options.models?.length\n\t\t? options.models\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tid: DEFAULT_MODEL_ID,\n\t\t\t\t\tname: DEFAULT_MODEL_NAME,\n\t\t\t\t\treasoning: false,\n\t\t\t\t\tinput: [\"text\", \"image\"] as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: 128000,\n\t\t\t\t\tmaxTokens: 16384,\n\t\t\t\t},\n\t\t\t];\n\tconst models = modelDefinitions.map((definition) => ({\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi,\n\t\tprovider,\n\t\tbaseUrl: DEFAULT_BASE_URL,\n\t\treasoning: definition.reasoning ?? false,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t})) as [Model<string>, ...Model<string>[]];\n\n\tconst stream: StreamFunction<string, StreamOptions> = (requestModel, context, streamOptions) => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst step = pendingResponses.shift();\n\t\tstate.callCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tif (!step) {\n\t\t\t\t\tlet message = createErrorMessage(\n\t\t\t\t\t\tnew Error(\"No more faux responses queued\"),\n\t\t\t\t\t\tapi,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\trequestModel.id,\n\t\t\t\t\t);\n\t\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\t\touter.end(message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst resolved =\n\t\t\t\t\ttypeof step === \"function\" ? await step(context, streamOptions, state, requestModel) : step;\n\t\t\t\tlet message = cloneMessage(resolved, api, provider, requestModel.id);\n\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\tawait streamWithDeltas(outer, message, minTokenSize, maxTokenSize, tokensPerSecond, streamOptions?.signal);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst streamSimple: StreamFunction<string, SimpleStreamOptions> = (streamModel, context, streamOptions) =>\n\t\tstream(streamModel, context, streamOptions);\n\n\tregisterApiProvider({ api, stream, streamSimple }, sourceId);\n\n\tfunction getModel(): Model<string>;\n\tfunction getModel(requestedModelId: string): Model<string> | undefined;\n\tfunction getModel(requestedModelId?: string): Model<string> | undefined {\n\t\tif (!requestedModelId) {\n\t\t\treturn models[0];\n\t\t}\n\t\treturn models.find((candidate) => candidate.id === requestedModelId);\n\t}\n\n\treturn {\n\t\tapi,\n\t\tmodels,\n\t\tgetModel,\n\t\tstate,\n\t\tsetResponses(responses) {\n\t\t\tpendingResponses = [...responses];\n\t\t},\n\t\tappendResponses(responses) {\n\t\t\tpendingResponses.push(...responses);\n\t\t},\n\t\tgetPendingResponseCount() {\n\t\t\treturn pendingResponses.length;\n\t\t},\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"faux.js","sourceRoot":"","sources":["../../src/providers/faux.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAiBjF,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAE7E,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAClC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,gBAAgB,GAAG,oBAAoB,CAAC;AAC9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,EAAE;YACvB,gBAAgB,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC;QAAA,CAClC;QACD,eAAe,CAAC,SAAS,EAAE;YAC1B,gBAAgB,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC;QAAA,CACpC;QACD,uBAAuB,GAAG;YACzB,OAAO,gBAAgB,CAAC,MAAM,CAAC;QAAA,CAC/B;QACD,UAAU,GAAG;YACZ,sBAAsB,CAAC,QAAQ,CAAC,CAAC;QAAA,CACjC;KACD,CAAC;AAAA,CACF","sourcesContent":["import { registerApiProvider, unregisterApiProviders } from \"../api-registry.js\";\nimport type {\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tToolCall,\n\tToolResultMessage,\n\tUsage,\n} from \"../types.js\";\nimport { createAssistantMessageEventStream } from \"../utils/event-stream.js\";\n\nconst DEFAULT_API = \"faux\";\nconst DEFAULT_PROVIDER = \"faux\";\nconst DEFAULT_MODEL_ID = \"faux-1\";\nconst DEFAULT_MODEL_NAME = \"Faux Model\";\nconst DEFAULT_BASE_URL = \"http://localhost:0\";\nconst DEFAULT_MIN_TOKEN_SIZE = 3;\nconst DEFAULT_MAX_TOKEN_SIZE = 5;\n\nconst DEFAULT_USAGE: Usage = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FauxModelDefinition {\n\tid: string;\n\tname?: string;\n\treasoning?: boolean;\n\tinput?: (\"text\" | \"image\")[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n}\n\nexport type FauxContentBlock = TextContent | ThinkingContent | ToolCall;\n\nexport function fauxText(text: string): TextContent {\n\treturn { type: \"text\", text };\n}\n\nexport function fauxThinking(thinking: string): ThinkingContent {\n\treturn { type: \"thinking\", thinking };\n}\n\nexport function fauxToolCall(name: string, arguments_: ToolCall[\"arguments\"], options: { id?: string } = {}): ToolCall {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: options.id ?? randomId(\"tool\"),\n\t\tname,\n\t\targuments: arguments_,\n\t};\n}\n\nfunction normalizeFauxAssistantContent(content: string | FauxContentBlock | FauxContentBlock[]): FauxContentBlock[] {\n\tif (typeof content === \"string\") {\n\t\treturn [fauxText(content)];\n\t}\n\treturn Array.isArray(content) ? content : [content];\n}\n\nexport function fauxAssistantMessage(\n\tcontent: string | FauxContentBlock | FauxContentBlock[],\n\toptions: {\n\t\tstopReason?: AssistantMessage[\"stopReason\"];\n\t\terrorMessage?: string;\n\t\tresponseId?: string;\n\t\ttimestamp?: number;\n\t} = {},\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: normalizeFauxAssistantContent(content),\n\t\tapi: DEFAULT_API,\n\t\tprovider: DEFAULT_PROVIDER,\n\t\tmodel: DEFAULT_MODEL_ID,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: options.stopReason ?? \"stop\",\n\t\terrorMessage: options.errorMessage,\n\t\tresponseId: options.responseId,\n\t\ttimestamp: options.timestamp ?? Date.now(),\n\t};\n}\n\nexport type FauxResponseFactory = (\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tstate: { callCount: number },\n\tmodel: Model<string>,\n) => AssistantMessage | Promise<AssistantMessage>;\n\nexport type FauxResponseStep = AssistantMessage | FauxResponseFactory;\n\nexport interface RegisterFauxProviderOptions {\n\tapi?: string;\n\tprovider?: string;\n\tmodels?: FauxModelDefinition[];\n\ttokensPerSecond?: number;\n\ttokenSize?: {\n\t\tmin?: number;\n\t\tmax?: number;\n\t};\n}\n\nexport interface FauxProviderRegistration {\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: { callCount: number };\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n\tunregister: () => void;\n}\n\nfunction estimateTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction randomId(prefix: string): string {\n\treturn `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction contentToText(content: string | Array<TextContent | ImageContent>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\treturn `[image:${block.mimeType}:${block.data.length}]`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction assistantContentToText(content: Array<TextContent | ThinkingContent | ToolCall>): string {\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\treturn block.thinking;\n\t\t\t}\n\t\t\treturn `${block.name}:${JSON.stringify(block.arguments)}`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction toolResultToText(message: ToolResultMessage): string {\n\treturn [message.toolName, ...message.content.map((block) => contentToText([block]))].join(\"\\n\");\n}\n\nfunction messageToText(message: Message): string {\n\tif (message.role === \"user\") {\n\t\treturn contentToText(message.content);\n\t}\n\tif (message.role === \"assistant\") {\n\t\treturn assistantContentToText(message.content);\n\t}\n\treturn toolResultToText(message);\n}\n\nfunction serializeContext(context: Context): string {\n\tconst parts: string[] = [];\n\tif (context.systemPrompt) {\n\t\tparts.push(`system:${context.systemPrompt}`);\n\t}\n\tfor (const message of context.messages) {\n\t\tparts.push(`${message.role}:${messageToText(message)}`);\n\t}\n\tif (context.tools?.length) {\n\t\tparts.push(`tools:${JSON.stringify(context.tools)}`);\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\nfunction commonPrefixLength(a: string, b: string): number {\n\tconst length = Math.min(a.length, b.length);\n\tlet index = 0;\n\twhile (index < length && a[index] === b[index]) {\n\t\tindex++;\n\t}\n\treturn index;\n}\n\nfunction withUsageEstimate(\n\tmessage: AssistantMessage,\n\tcontext: Context,\n\toptions: StreamOptions | undefined,\n\tpromptCache: Map<string, string>,\n): AssistantMessage {\n\tconst promptText = serializeContext(context);\n\tconst promptTokens = estimateTokens(promptText);\n\tconst outputTokens = estimateTokens(assistantContentToText(message.content));\n\tlet input = promptTokens;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tconst sessionId = options?.sessionId;\n\n\tif (sessionId && options?.cacheRetention !== \"none\") {\n\t\tconst previousPrompt = promptCache.get(sessionId);\n\t\tif (previousPrompt) {\n\t\t\tconst cachedChars = commonPrefixLength(previousPrompt, promptText);\n\t\t\tcacheRead = estimateTokens(previousPrompt.slice(0, cachedChars));\n\t\t\tcacheWrite = estimateTokens(promptText.slice(cachedChars));\n\t\t\tinput = Math.max(0, promptTokens - cacheRead);\n\t\t} else {\n\t\t\tcacheWrite = promptTokens;\n\t\t}\n\t\tpromptCache.set(sessionId, promptText);\n\t}\n\n\treturn {\n\t\t...message,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput: outputTokens,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens: input + outputTokens + cacheRead + cacheWrite,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t};\n}\n\nfunction splitStringByTokenSize(text: string, minTokenSize: number, maxTokenSize: number): string[] {\n\tconst chunks: string[] = [];\n\tlet index = 0;\n\twhile (index < text.length) {\n\t\tconst tokenSize = minTokenSize + Math.floor(Math.random() * (maxTokenSize - minTokenSize + 1));\n\t\tconst charSize = Math.max(1, tokenSize * 4);\n\t\tchunks.push(text.slice(index, index + charSize));\n\t\tindex += charSize;\n\t}\n\treturn chunks.length > 0 ? chunks : [\"\"];\n}\n\nfunction cloneMessage(message: AssistantMessage, api: string, provider: string, modelId: string): AssistantMessage {\n\tconst cloned = structuredClone(message);\n\treturn {\n\t\t...cloned,\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\ttimestamp: cloned.timestamp ?? Date.now(),\n\t\tusage: cloned.usage ?? DEFAULT_USAGE,\n\t};\n}\n\nfunction createErrorMessage(error: unknown, api: string, provider: string, modelId: string): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAbortedMessage(partial: AssistantMessage): AssistantMessage {\n\treturn {\n\t\t...partial,\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: \"Request was aborted\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction scheduleChunk(chunk: string, tokensPerSecond: number | undefined): Promise<void> {\n\tif (!tokensPerSecond || tokensPerSecond <= 0) {\n\t\treturn new Promise((resolve) => queueMicrotask(resolve));\n\t}\n\tconst delayMs = (estimateTokens(chunk) / tokensPerSecond) * 1000;\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\nasync function streamWithDeltas(\n\tstream: AssistantMessageEventStream,\n\tmessage: AssistantMessage,\n\tminTokenSize: number,\n\tmaxTokenSize: number,\n\ttokensPerSecond: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tconst partial: AssistantMessage = { ...message, content: [] };\n\tif (signal?.aborted) {\n\t\tconst aborted = createAbortedMessage(partial);\n\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\tstream.end(aborted);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"start\", partial: { ...partial } });\n\n\tfor (let index = 0; index < message.content.length; index++) {\n\t\tif (signal?.aborted) {\n\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\tstream.end(aborted);\n\t\t\treturn;\n\t\t}\n\n\t\tconst block = message.content[index];\n\n\t\tif (block.type === \"thinking\") {\n\t\t\tpartial.content = [...partial.content, { type: \"thinking\", thinking: \"\" }];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as ThinkingContent).thinking += chunk;\n\t\t\t\tstream.push({ type: \"thinking_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: index,\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: { ...partial },\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (block.type === \"text\") {\n\t\t\tpartial.content = [...partial.content, { type: \"text\", text: \"\" }];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as TextContent).text += chunk;\n\t\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } });\n\t\t\tcontinue;\n\t\t}\n\n\t\tpartial.content = [...partial.content, { type: \"toolCall\", id: block.id, name: block.name, arguments: {} }];\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } });\n\t\tfor (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {\n\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\tstream.end(aborted);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t}\n\t\t(partial.content[index] as ToolCall).arguments = block.arguments;\n\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } });\n\t}\n\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\tstream.push({ type: \"error\", reason: message.stopReason, error: message });\n\t\tstream.end(message);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"done\", reason: message.stopReason, message });\n\tstream.end(message);\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst api = options.api ?? randomId(DEFAULT_API);\n\tconst provider = options.provider ?? DEFAULT_PROVIDER;\n\tconst sourceId = randomId(\"faux-provider\");\n\tconst minTokenSize = Math.max(\n\t\t1,\n\t\tMath.min(options.tokenSize?.min ?? DEFAULT_MIN_TOKEN_SIZE, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE),\n\t);\n\tconst maxTokenSize = Math.max(minTokenSize, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE);\n\tlet pendingResponses: FauxResponseStep[] = [];\n\tconst tokensPerSecond = options.tokensPerSecond;\n\tconst state = { callCount: 0 };\n\tconst promptCache = new Map<string, string>();\n\n\tconst modelDefinitions = options.models?.length\n\t\t? options.models\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tid: DEFAULT_MODEL_ID,\n\t\t\t\t\tname: DEFAULT_MODEL_NAME,\n\t\t\t\t\treasoning: false,\n\t\t\t\t\tinput: [\"text\", \"image\"] as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: 128000,\n\t\t\t\t\tmaxTokens: 16384,\n\t\t\t\t},\n\t\t\t];\n\tconst models = modelDefinitions.map((definition) => ({\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi,\n\t\tprovider,\n\t\tbaseUrl: DEFAULT_BASE_URL,\n\t\treasoning: definition.reasoning ?? false,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t})) as [Model<string>, ...Model<string>[]];\n\n\tconst stream: StreamFunction<string, StreamOptions> = (requestModel, context, streamOptions) => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst step = pendingResponses.shift();\n\t\tstate.callCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tawait streamOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t\t\t\tif (!step) {\n\t\t\t\t\tlet message = createErrorMessage(\n\t\t\t\t\t\tnew Error(\"No more faux responses queued\"),\n\t\t\t\t\t\tapi,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\trequestModel.id,\n\t\t\t\t\t);\n\t\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\t\touter.end(message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst resolved =\n\t\t\t\t\ttypeof step === \"function\" ? await step(context, streamOptions, state, requestModel) : step;\n\t\t\t\tlet message = cloneMessage(resolved, api, provider, requestModel.id);\n\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\tawait streamWithDeltas(outer, message, minTokenSize, maxTokenSize, tokensPerSecond, streamOptions?.signal);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst streamSimple: StreamFunction<string, SimpleStreamOptions> = (streamModel, context, streamOptions) =>\n\t\tstream(streamModel, context, streamOptions);\n\n\tregisterApiProvider({ api, stream, streamSimple }, sourceId);\n\n\tfunction getModel(): Model<string>;\n\tfunction getModel(requestedModelId: string): Model<string> | undefined;\n\tfunction getModel(requestedModelId?: string): Model<string> | undefined {\n\t\tif (!requestedModelId) {\n\t\t\treturn models[0];\n\t\t}\n\t\treturn models.find((candidate) => candidate.id === requestedModelId);\n\t}\n\n\treturn {\n\t\tapi,\n\t\tmodels,\n\t\tgetModel,\n\t\tstate,\n\t\tsetResponses(responses) {\n\t\t\tpendingResponses = [...responses];\n\t\t},\n\t\tappendResponses(responses) {\n\t\t\tpendingResponses.push(...responses);\n\t\t},\n\t\tgetPendingResponseCount() {\n\t\t\treturn pendingResponses.length;\n\t\t},\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"google-gemini-cli.d.ts","sourceRoot":"","sources":["../../src/providers/google-gemini-cli.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc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C,CAAC;QACF,KAAK,CAAC,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;QACxC,UAAU,CAAC,EAAE;YACZ,qBAAqB,EAAE;gBACtB,IAAI,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC;aACvC,CAAC;SACF,CAAC;KACF,CAAC;IACF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAiCD,eAAO,MAAM,qBAAqB,EAAE,cAAc,CAAC,mBAAmB,EAAE,sBAAsB,CAse7F,CAAC;AAEF,eAAO,MAAM,2BAA2B,EAAE,cAAc,CAAC,mBAAmB,EAAE,mBAAmB,CAqDhG,CAAC;AAEF,wBAAgB,YAAY,CAC3B,KAAK,EAAE,KAAK,CAAC,mBAAmB,CAAC,EACjC,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,sBAA2B,EACpC,aAAa,UAAQ,GACnB,sBAAsB,CA8ExB","sourcesContent":["/**\n * Google Gemini CLI / Antigravity provider.\n * Shared implementation for both google-gemini-cli and google-antigravity providers.\n * Uses the Cloud Code Assist API endpoint to access Gemini and Claude models.\n */\n\nimport type { Content, ThinkingConfig } from \"@google/genai\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tToolCall,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tisThinkingPart,\n\tmapStopReasonString,\n\tmapToolChoice,\n\tretainThoughtSignature,\n} from \"./google-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\n/**\n * Thinking level for Gemini 3 models.\n * Mirrors Google's ThinkingLevel enum values.\n */\nexport type GoogleThinkingLevel = \"THINKING_LEVEL_UNSPECIFIED\" | \"MINIMAL\" | \"LOW\" | \"MEDIUM\" | \"HIGH\";\n\nexport interface GoogleGeminiCliOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\";\n\t/**\n\t * Thinking/reasoning configuration.\n\t * - Gemini 2.x models: use `budgetTokens` to set the thinking budget\n\t * - Gemini 3 models (gemini-3-pro-*, gemini-3-flash-*): use `level` instead\n\t *\n\t * When using `streamSimple`, this is handled automatically based on the model.\n\t */\n\tthinking?: {\n\t\tenabled: boolean;\n\t\t/** Thinking budget in tokens. Use for Gemini 2.x models. */\n\t\tbudgetTokens?: number;\n\t\t/** Thinking level. Use for Gemini 3 models (LOW/HIGH for Pro, MINIMAL/LOW/MEDIUM/HIGH for Flash). */\n\t\tlevel?: GoogleThinkingLevel;\n\t};\n\tprojectId?: string;\n}\n\nconst DEFAULT_ENDPOINT = \"https://cloudcode-pa.googleapis.com\";\nconst ANTIGRAVITY_DAILY_ENDPOINT = \"https://daily-cloudcode-pa.sandbox.googleapis.com\";\nconst ANTIGRAVITY_AUTOPUSH_ENDPOINT = \"https://autopush-cloudcode-pa.sandbox.googleapis.com\";\nconst ANTIGRAVITY_ENDPOINT_FALLBACKS = [\n\tANTIGRAVITY_DAILY_ENDPOINT,\n\tANTIGRAVITY_AUTOPUSH_ENDPOINT,\n\tDEFAULT_ENDPOINT,\n] as const;\n// Headers for Gemini CLI (prod endpoint)\nconst GEMINI_CLI_HEADERS = {\n\t\"User-Agent\": \"google-cloud-sdk vscode_cloudshelleditor/0.1\",\n\t\"X-Goog-Api-Client\": \"gl-node/22.17.0\",\n\t\"Client-Metadata\": JSON.stringify({\n\t\tideType: \"IDE_UNSPECIFIED\",\n\t\tplatform: \"PLATFORM_UNSPECIFIED\",\n\t\tpluginType: \"GEMINI\",\n\t}),\n};\n\n// Headers for Antigravity (sandbox endpoint) - requires specific User-Agent\nconst DEFAULT_ANTIGRAVITY_VERSION = \"1.21.9\";\n\nfunction getAntigravityHeaders() {\n\tconst version = process.env.PI_AI_ANTIGRAVITY_VERSION || DEFAULT_ANTIGRAVITY_VERSION;\n\treturn {\n\t\t\"User-Agent\": `antigravity/${version} darwin/arm64`,\n\t};\n}\n\n// Antigravity system instruction (compact version from CLIProxyAPI).\nconst ANTIGRAVITY_SYSTEM_INSTRUCTION =\n\t\"You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\" +\n\t\"You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.\" +\n\t\"**Absolute paths only**\" +\n\t\"**Proactiveness**\";\n\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\n\n// Retry configuration\nconst MAX_RETRIES = 3;\nconst BASE_DELAY_MS = 1000;\nconst MAX_EMPTY_STREAM_RETRIES = 2;\nconst EMPTY_STREAM_BASE_DELAY_MS = 500;\nconst CLAUDE_THINKING_BETA_HEADER = \"interleaved-thinking-2025-05-14\";\n\n/**\n * Extract retry delay from Gemini error response (in milliseconds).\n * Checks headers first (Retry-After, x-ratelimit-reset, x-ratelimit-reset-after),\n * then parses body patterns like:\n * - \"Your quota will reset after 39s\"\n * - \"Your quota will reset after 18h31m10s\"\n * - \"Please retry in Xs\" or \"Please retry in Xms\"\n * - \"retryDelay\": \"34.074824224s\" (JSON field)\n */\nexport function extractRetryDelay(errorText: string, response?: Response | Headers): number | undefined {\n\tconst normalizeDelay = (ms: number): number | undefined => (ms > 0 ? Math.ceil(ms + 1000) : undefined);\n\n\tconst headers = response instanceof Headers ? response : response?.headers;\n\tif (headers) {\n\t\tconst retryAfter = headers.get(\"retry-after\");\n\t\tif (retryAfter) {\n\t\t\tconst retryAfterSeconds = Number(retryAfter);\n\t\t\tif (Number.isFinite(retryAfterSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(retryAfterSeconds * 1000);\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst retryAfterDate = new Date(retryAfter);\n\t\t\tconst retryAfterMs = retryAfterDate.getTime();\n\t\t\tif (!Number.isNaN(retryAfterMs)) {\n\t\t\t\tconst delay = normalizeDelay(retryAfterMs - Date.now());\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst rateLimitReset = headers.get(\"x-ratelimit-reset\");\n\t\tif (rateLimitReset) {\n\t\t\tconst resetSeconds = Number.parseInt(rateLimitReset, 10);\n\t\t\tif (!Number.isNaN(resetSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(resetSeconds * 1000 - Date.now());\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst rateLimitResetAfter = headers.get(\"x-ratelimit-reset-after\");\n\t\tif (rateLimitResetAfter) {\n\t\t\tconst resetAfterSeconds = Number(rateLimitResetAfter);\n\t\t\tif (Number.isFinite(resetAfterSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(resetAfterSeconds * 1000);\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 1: \"Your quota will reset after ...\" (formats: \"18h31m10s\", \"10m15s\", \"6s\", \"39s\")\n\tconst durationMatch = errorText.match(/reset after (?:(\\d+)h)?(?:(\\d+)m)?(\\d+(?:\\.\\d+)?)s/i);\n\tif (durationMatch) {\n\t\tconst hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0;\n\t\tconst minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;\n\t\tconst seconds = parseFloat(durationMatch[3]);\n\t\tif (!Number.isNaN(seconds)) {\n\t\t\tconst totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1000;\n\t\t\tconst delay = normalizeDelay(totalMs);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 2: \"Please retry in X[ms|s]\"\n\tconst retryInMatch = errorText.match(/Please retry in ([0-9.]+)(ms|s)/i);\n\tif (retryInMatch?.[1]) {\n\t\tconst value = parseFloat(retryInMatch[1]);\n\t\tif (!Number.isNaN(value) && value > 0) {\n\t\t\tconst ms = retryInMatch[2].toLowerCase() === \"ms\" ? value : value * 1000;\n\t\t\tconst delay = normalizeDelay(ms);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 3: \"retryDelay\": \"34.074824224s\" (JSON field in error details)\n\tconst retryDelayMatch = errorText.match(/\"retryDelay\":\\s*\"([0-9.]+)(ms|s)\"/i);\n\tif (retryDelayMatch?.[1]) {\n\t\tconst value = parseFloat(retryDelayMatch[1]);\n\t\tif (!Number.isNaN(value) && value > 0) {\n\t\t\tconst ms = retryDelayMatch[2].toLowerCase() === \"ms\" ? value : value * 1000;\n\t\t\tconst delay = normalizeDelay(ms);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction needsClaudeThinkingBetaHeader(model: Model<\"google-gemini-cli\">): boolean {\n\treturn model.provider === \"google-antigravity\" && model.id.startsWith(\"claude-\") && model.reasoning;\n}\n\nfunction isGemini3ProModel(modelId: string): boolean {\n\treturn /gemini-3(?:\\.1)?-pro/.test(modelId.toLowerCase());\n}\n\nfunction isGemini3FlashModel(modelId: string): boolean {\n\treturn /gemini-3(?:\\.1)?-flash/.test(modelId.toLowerCase());\n}\n\nfunction isGemini3Model(modelId: string): boolean {\n\treturn isGemini3ProModel(modelId) || isGemini3FlashModel(modelId);\n}\n\n/**\n * Check if an error is retryable (rate limit, server error, network error, etc.)\n */\nfunction isRetryableError(status: number, errorText: string): boolean {\n\tif (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {\n\t\treturn true;\n\t}\n\treturn /resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(errorText);\n}\n\n/**\n * Extract a clean, user-friendly error message from Google API error response.\n * Parses JSON error responses and returns just the message field.\n */\nfunction extractErrorMessage(errorText: string): string {\n\ttry {\n\t\tconst parsed = JSON.parse(errorText) as { error?: { message?: string } };\n\t\tif (parsed.error?.message) {\n\t\t\treturn parsed.error.message;\n\t\t}\n\t} catch {\n\t\t// Not JSON, return as-is\n\t}\n\treturn errorText;\n}\n\n/**\n * Sleep for a given number of milliseconds, respecting abort signal.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t});\n\t});\n}\n\ninterface CloudCodeAssistRequest {\n\tproject: string;\n\tmodel: string;\n\trequest: {\n\t\tcontents: Content[];\n\t\tsessionId?: string;\n\t\tsystemInstruction?: { role?: string; parts: { text: string }[] };\n\t\tgenerationConfig?: {\n\t\t\tmaxOutputTokens?: number;\n\t\t\ttemperature?: number;\n\t\t\tthinkingConfig?: ThinkingConfig;\n\t\t};\n\t\ttools?: ReturnType<typeof convertTools>;\n\t\ttoolConfig?: {\n\t\t\tfunctionCallingConfig: {\n\t\t\t\tmode: ReturnType<typeof mapToolChoice>;\n\t\t\t};\n\t\t};\n\t};\n\trequestType?: string;\n\tuserAgent?: string;\n\trequestId?: string;\n}\n\ninterface CloudCodeAssistResponseChunk {\n\tresponse?: {\n\t\tcandidates?: Array<{\n\t\t\tcontent?: {\n\t\t\t\trole: string;\n\t\t\t\tparts?: Array<{\n\t\t\t\t\ttext?: string;\n\t\t\t\t\tthought?: boolean;\n\t\t\t\t\tthoughtSignature?: string;\n\t\t\t\t\tfunctionCall?: {\n\t\t\t\t\t\tname: string;\n\t\t\t\t\t\targs: Record<string, unknown>;\n\t\t\t\t\t\tid?: string;\n\t\t\t\t\t};\n\t\t\t\t}>;\n\t\t\t};\n\t\t\tfinishReason?: string;\n\t\t}>;\n\t\tusageMetadata?: {\n\t\t\tpromptTokenCount?: number;\n\t\t\tcandidatesTokenCount?: number;\n\t\t\tthoughtsTokenCount?: number;\n\t\t\ttotalTokenCount?: number;\n\t\t\tcachedContentTokenCount?: number;\n\t\t};\n\t\tmodelVersion?: string;\n\t\tresponseId?: string;\n\t};\n\ttraceId?: string;\n}\n\nexport const streamGoogleGeminiCli: StreamFunction<\"google-gemini-cli\", GoogleGeminiCliOptions> = (\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\toptions?: GoogleGeminiCliOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"google-gemini-cli\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\t// apiKey is JSON-encoded: { token, projectId }\n\t\t\tconst apiKeyRaw = options?.apiKey;\n\t\t\tif (!apiKeyRaw) {\n\t\t\t\tthrow new Error(\"Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.\");\n\t\t\t}\n\n\t\t\tlet accessToken: string;\n\t\t\tlet projectId: string;\n\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(apiKeyRaw) as { token: string; projectId: string };\n\t\t\t\taccessToken = parsed.token;\n\t\t\t\tprojectId = parsed.projectId;\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.\");\n\t\t\t}\n\n\t\t\tif (!accessToken || !projectId) {\n\t\t\t\tthrow new Error(\"Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.\");\n\t\t\t}\n\n\t\t\tconst isAntigravity = model.provider === \"google-antigravity\";\n\t\t\tconst baseUrl = model.baseUrl?.trim();\n\t\t\tconst endpoints = baseUrl ? [baseUrl] : isAntigravity ? ANTIGRAVITY_ENDPOINT_FALLBACKS : [DEFAULT_ENDPOINT];\n\n\t\t\tlet requestBody = buildRequest(model, context, projectId, options, isAntigravity);\n\t\t\tconst nextRequestBody = await options?.onPayload?.(requestBody, model);\n\t\t\tif (nextRequestBody !== undefined) {\n\t\t\t\trequestBody = nextRequestBody as CloudCodeAssistRequest;\n\t\t\t}\n\t\t\tconst headers = isAntigravity ? getAntigravityHeaders() : GEMINI_CLI_HEADERS;\n\n\t\t\tconst requestHeaders = {\n\t\t\t\tAuthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\tAccept: \"text/event-stream\",\n\t\t\t\t...headers,\n\t\t\t\t...(needsClaudeThinkingBetaHeader(model) ? { \"anthropic-beta\": CLAUDE_THINKING_BETA_HEADER } : {}),\n\t\t\t\t...options?.headers,\n\t\t\t};\n\t\t\tconst requestBodyJson = JSON.stringify(requestBody);\n\n\t\t\t// Fetch with retry logic for rate limits, transient errors, and endpoint fallbacks.\n\t\t\t// On 403/404, immediately try the next endpoint (no delay).\n\t\t\t// On 429/5xx, retry with backoff on the same or next endpoint.\n\t\t\tlet response: Response | undefined;\n\t\t\tlet lastError: Error | undefined;\n\t\t\tlet requestUrl: string | undefined;\n\t\t\tlet endpointIndex = 0;\n\n\t\t\tfor (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconst endpoint = endpoints[endpointIndex];\n\t\t\t\t\trequestUrl = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;\n\t\t\t\t\tresponse = await fetch(requestUrl, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders,\n\t\t\t\t\t\tbody: requestBodyJson,\n\t\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tbreak; // Success, exit retry loop\n\t\t\t\t\t}\n\n\t\t\t\t\tconst errorText = await response.text();\n\n\t\t\t\t\t// On 403/404, cascade to the next endpoint immediately (no delay)\n\t\t\t\t\tif ((response.status === 403 || response.status === 404) && endpointIndex < endpoints.length - 1) {\n\t\t\t\t\t\tendpointIndex++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Check if retryable (429, 5xx, network patterns)\n\t\t\t\t\tif (attempt < MAX_RETRIES && isRetryableError(response.status, errorText)) {\n\t\t\t\t\t\t// Advance endpoint if possible\n\t\t\t\t\t\tif (endpointIndex < endpoints.length - 1) {\n\t\t\t\t\t\t\tendpointIndex++;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Use server-provided delay or exponential backoff\n\t\t\t\t\t\tconst serverDelay = extractRetryDelay(errorText, response);\n\t\t\t\t\t\tconst delayMs = serverDelay ?? BASE_DELAY_MS * 2 ** attempt;\n\n\t\t\t\t\t\t// Check if server delay exceeds max allowed (default: 60s)\n\t\t\t\t\t\tconst maxDelayMs = options?.maxRetryDelayMs ?? 60000;\n\t\t\t\t\t\tif (maxDelayMs > 0 && serverDelay && serverDelay > maxDelayMs) {\n\t\t\t\t\t\t\tconst delaySeconds = Math.ceil(serverDelay / 1000);\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Server requested ${delaySeconds}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${extractErrorMessage(errorText)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Not retryable or max retries exceeded\n\t\t\t\t\tthrow new Error(`Cloud Code Assist API error (${response.status}): ${extractErrorMessage(errorText)}`);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Check for abort - fetch throws AbortError, our code throws \"Request was aborted\"\n\t\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\t\tif (error.name === \"AbortError\" || error.message === \"Request was aborted\") {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Extract detailed error message from fetch errors (Node includes cause)\n\t\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\tif (lastError.message === \"fetch failed\" && lastError.cause instanceof Error) {\n\t\t\t\t\t\tlastError = new Error(`Network error: ${lastError.cause.message}`);\n\t\t\t\t\t}\n\t\t\t\t\t// Network errors are retryable\n\t\t\t\t\tif (attempt < MAX_RETRIES) {\n\t\t\t\t\t\tconst delayMs = BASE_DELAY_MS * 2 ** attempt;\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!response || !response.ok) {\n\t\t\t\tthrow lastError ?? new Error(\"Failed to get response after retries\");\n\t\t\t}\n\n\t\t\tlet started = false;\n\t\t\tconst ensureStarted = () => {\n\t\t\t\tif (!started) {\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\tstarted = true;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst resetOutput = () => {\n\t\t\t\toutput.content = [];\n\t\t\t\toutput.usage = {\n\t\t\t\t\tinput: 0,\n\t\t\t\t\toutput: 0,\n\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t\toutput.stopReason = \"stop\";\n\t\t\t\toutput.errorMessage = undefined;\n\t\t\t\toutput.timestamp = Date.now();\n\t\t\t\tstarted = false;\n\t\t\t};\n\n\t\t\tconst streamResponse = async (activeResponse: Response): Promise<boolean> => {\n\t\t\t\tif (!activeResponse.body) {\n\t\t\t\t\tthrow new Error(\"No response body\");\n\t\t\t\t}\n\n\t\t\t\tlet hasContent = false;\n\t\t\t\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\t\t\t\tconst blocks = output.content;\n\t\t\t\tconst blockIndex = () => blocks.length - 1;\n\n\t\t\t\t// Read SSE stream\n\t\t\t\tconst reader = activeResponse.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\n\t\t\t\t// Set up abort handler to cancel reader when signal fires\n\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\tvoid reader.cancel().catch(() => {});\n\t\t\t\t};\n\t\t\t\toptions?.signal?.addEventListener(\"abort\", abortHandler);\n\n\t\t\t\ttry {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t// Check abort signal before each read\n\t\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) break;\n\n\t\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\n\t\t\t\t\t\t\tconst jsonStr = line.slice(5).trim();\n\t\t\t\t\t\t\tif (!jsonStr) continue;\n\n\t\t\t\t\t\t\tlet chunk: CloudCodeAssistResponseChunk;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tchunk = JSON.parse(jsonStr);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Unwrap the response\n\t\t\t\t\t\t\tconst responseData = chunk.response;\n\t\t\t\t\t\t\tif (!responseData) continue;\n\t\t\t\t\t\t\t// Cloud Code Assist mirrors Gemini's responseId field. Keep the first non-empty one.\n\t\t\t\t\t\t\t// A single streamed response should retain the same ID across chunks.\n\t\t\t\t\t\t\toutput.responseId ||= responseData.responseId;\n\n\t\t\t\t\t\t\tconst candidate = responseData.candidates?.[0];\n\t\t\t\t\t\t\tif (candidate?.content?.parts) {\n\t\t\t\t\t\t\t\tfor (const part of candidate.content.parts) {\n\t\t\t\t\t\t\t\t\tif (part.text !== undefined) {\n\t\t\t\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t\t\t\t\tconst isThinking = isThinkingPart(part);\n\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t!currentBlock ||\n\t\t\t\t\t\t\t\t\t\t\t(isThinking && currentBlock.type !== \"thinking\") ||\n\t\t\t\t\t\t\t\t\t\t\t(!isThinking && currentBlock.type !== \"text\")\n\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blocks.length - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (isThinking) {\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n\t\t\t\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_start\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"thinking\") {\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinking += part.text;\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature,\n\t\t\t\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.text += part.text;\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature,\n\t\t\t\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = null;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst providedId = part.functionCall.id;\n\t\t\t\t\t\t\t\t\t\tconst needsNewId =\n\t\t\t\t\t\t\t\t\t\t\t!providedId ||\n\t\t\t\t\t\t\t\t\t\t\toutput.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n\t\t\t\t\t\t\t\t\t\tconst toolCallId = needsNewId\n\t\t\t\t\t\t\t\t\t\t\t? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n\t\t\t\t\t\t\t\t\t\t\t: providedId;\n\n\t\t\t\t\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\t\t\t\t\tid: toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tname: part.functionCall.name || \"\",\n\t\t\t\t\t\t\t\t\t\t\targuments: (part.functionCall.args as Record<string, unknown>) ?? {},\n\t\t\t\t\t\t\t\t\t\t\t...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\toutput.content.push(toolCall);\n\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\tdelta: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\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}\n\n\t\t\t\t\t\t\tif (candidate?.finishReason) {\n\t\t\t\t\t\t\t\toutput.stopReason = mapStopReasonString(candidate.finishReason);\n\t\t\t\t\t\t\t\tif (output.content.some((b) => b.type === \"toolCall\")) {\n\t\t\t\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (responseData.usageMetadata) {\n\t\t\t\t\t\t\t\t// promptTokenCount includes cachedContentTokenCount, so subtract to get fresh input\n\t\t\t\t\t\t\t\tconst promptTokens = responseData.usageMetadata.promptTokenCount || 0;\n\t\t\t\t\t\t\t\tconst cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;\n\t\t\t\t\t\t\t\toutput.usage = {\n\t\t\t\t\t\t\t\t\tinput: promptTokens - cacheReadTokens,\n\t\t\t\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\t\t\t\t(responseData.usageMetadata.candidatesTokenCount || 0) +\n\t\t\t\t\t\t\t\t\t\t(responseData.usageMetadata.thoughtsTokenCount || 0),\n\t\t\t\t\t\t\t\t\tcacheRead: cacheReadTokens,\n\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\ttotalTokens: responseData.usageMetadata.totalTokenCount || 0,\n\t\t\t\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\t\ttotal: 0,\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\tcalculateCost(model, output.usage);\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} finally {\n\t\t\t\t\toptions?.signal?.removeEventListener(\"abort\", abortHandler);\n\t\t\t\t}\n\n\t\t\t\tif (currentBlock) {\n\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn hasContent;\n\t\t\t};\n\n\t\t\tlet receivedContent = false;\n\t\t\tlet currentResponse = response;\n\n\t\t\tfor (let emptyAttempt = 0; emptyAttempt <= MAX_EMPTY_STREAM_RETRIES; emptyAttempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\tif (emptyAttempt > 0) {\n\t\t\t\t\tconst backoffMs = EMPTY_STREAM_BASE_DELAY_MS * 2 ** (emptyAttempt - 1);\n\t\t\t\t\tawait sleep(backoffMs, options?.signal);\n\n\t\t\t\t\tif (!requestUrl) {\n\t\t\t\t\t\tthrow new Error(\"Missing request URL\");\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentResponse = await fetch(requestUrl, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders,\n\t\t\t\t\t\tbody: requestBodyJson,\n\t\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!currentResponse.ok) {\n\t\t\t\t\t\tconst retryErrorText = await currentResponse.text();\n\t\t\t\t\t\tthrow new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst streamed = await streamResponse(currentResponse);\n\t\t\t\tif (streamed) {\n\t\t\t\t\treceivedContent = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (emptyAttempt < MAX_EMPTY_STREAM_RETRIES) {\n\t\t\t\t\tresetOutput();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!receivedContent) {\n\t\t\t\tthrow new Error(\"Cloud Code Assist API returned an empty response\");\n\t\t\t}\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tif (\"index\" in block) {\n\t\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleGoogleGeminiCli: StreamFunction<\"google-gemini-cli\", SimpleStreamOptions> = (\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(\"Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.\");\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tif (!options?.reasoning) {\n\t\treturn streamGoogleGeminiCli(model, context, {\n\t\t\t...base,\n\t\t\tthinking: { enabled: false },\n\t\t} satisfies GoogleGeminiCliOptions);\n\t}\n\n\tconst effort = clampReasoning(options.reasoning)!;\n\tif (isGemini3Model(model.id)) {\n\t\treturn streamGoogleGeminiCli(model, context, {\n\t\t\t...base,\n\t\t\tthinking: {\n\t\t\t\tenabled: true,\n\t\t\t\tlevel: getGeminiCliThinkingLevel(effort, model.id),\n\t\t\t},\n\t\t} satisfies GoogleGeminiCliOptions);\n\t}\n\n\tconst defaultBudgets: ThinkingBudgets = {\n\t\tminimal: 1024,\n\t\tlow: 2048,\n\t\tmedium: 8192,\n\t\thigh: 16384,\n\t};\n\tconst budgets = { ...defaultBudgets, ...options.thinkingBudgets };\n\n\tconst minOutputTokens = 1024;\n\tlet thinkingBudget = budgets[effort]!;\n\tconst maxTokens = Math.min((base.maxTokens || 0) + thinkingBudget, model.maxTokens);\n\n\tif (maxTokens <= thinkingBudget) {\n\t\tthinkingBudget = Math.max(0, maxTokens - minOutputTokens);\n\t}\n\n\treturn streamGoogleGeminiCli(model, context, {\n\t\t...base,\n\t\tmaxTokens,\n\t\tthinking: {\n\t\t\tenabled: true,\n\t\t\tbudgetTokens: thinkingBudget,\n\t\t},\n\t} satisfies GoogleGeminiCliOptions);\n};\n\nexport function buildRequest(\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\tprojectId: string,\n\toptions: GoogleGeminiCliOptions = {},\n\tisAntigravity = false,\n): CloudCodeAssistRequest {\n\tconst contents = convertMessages(model, context);\n\n\tconst generationConfig: CloudCodeAssistRequest[\"request\"][\"generationConfig\"] = {};\n\tif (options.temperature !== undefined) {\n\t\tgenerationConfig.temperature = options.temperature;\n\t}\n\tif (options.maxTokens !== undefined) {\n\t\tgenerationConfig.maxOutputTokens = options.maxTokens;\n\t}\n\n\t// Thinking config\n\tif (options.thinking?.enabled && model.reasoning) {\n\t\tgenerationConfig.thinkingConfig = {\n\t\t\tincludeThoughts: true,\n\t\t};\n\t\t// Gemini 3 models use thinkingLevel, older models use thinkingBudget\n\t\tif (options.thinking.level !== undefined) {\n\t\t\t// Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values\n\t\t\tgenerationConfig.thinkingConfig.thinkingLevel = options.thinking.level as any;\n\t\t} else if (options.thinking.budgetTokens !== undefined) {\n\t\t\tgenerationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n\t\t}\n\t} else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n\t\tgenerationConfig.thinkingConfig = getDisabledThinkingConfig(model.id);\n\t}\n\n\tconst request: CloudCodeAssistRequest[\"request\"] = {\n\t\tcontents,\n\t};\n\n\trequest.sessionId = options.sessionId;\n\n\t// System instruction must be object with parts, not plain string\n\tif (context.systemPrompt) {\n\t\trequest.systemInstruction = {\n\t\t\tparts: [{ text: sanitizeSurrogates(context.systemPrompt) }],\n\t\t};\n\t}\n\n\tif (Object.keys(generationConfig).length > 0) {\n\t\trequest.generationConfig = generationConfig;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\t// Claude models on Cloud Code Assist need the legacy `parameters` field;\n\t\t// the API translates it into Anthropic's `input_schema`.\n\t\tconst useParameters = model.id.startsWith(\"claude-\");\n\t\trequest.tools = convertTools(context.tools, useParameters);\n\t\tif (options.toolChoice) {\n\t\t\trequest.toolConfig = {\n\t\t\t\tfunctionCallingConfig: {\n\t\t\t\t\tmode: mapToolChoice(options.toolChoice),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\tif (isAntigravity) {\n\t\tconst existingParts = request.systemInstruction?.parts ?? [];\n\t\trequest.systemInstruction = {\n\t\t\trole: \"user\",\n\t\t\tparts: [\n\t\t\t\t{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION },\n\t\t\t\t{ text: `Please ignore following [ignore]${ANTIGRAVITY_SYSTEM_INSTRUCTION}[/ignore]` },\n\t\t\t\t...existingParts,\n\t\t\t],\n\t\t};\n\t}\n\n\treturn {\n\t\tproject: projectId,\n\t\tmodel: model.id,\n\t\trequest,\n\t\t...(isAntigravity ? { requestType: \"agent\" } : {}),\n\t\tuserAgent: isAntigravity ? \"antigravity\" : \"pi-coding-agent\",\n\t\trequestId: `${isAntigravity ? \"agent\" : \"pi\"}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,\n\t};\n}\n\ntype ClampedThinkingLevel = Exclude<ThinkingLevel, \"xhigh\">;\n\nfunction getDisabledThinkingConfig(modelId: string): ThinkingConfig {\n\t// Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n\t// do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n\t// thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n\tif (isGemini3ProModel(modelId)) {\n\t\treturn { thinkingLevel: \"LOW\" as any };\n\t}\n\tif (isGemini3FlashModel(modelId)) {\n\t\treturn { thinkingLevel: \"MINIMAL\" as any };\n\t}\n\n\t// Gemini 2.x supports disabling via thinkingBudget = 0.\n\treturn { thinkingBudget: 0 };\n}\n\nfunction getGeminiCliThinkingLevel(effort: ClampedThinkingLevel, modelId: string): GoogleThinkingLevel {\n\tif (isGemini3ProModel(modelId)) {\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn \"LOW\";\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn \"HIGH\";\n\t\t}\n\t}\n\tswitch (effort) {\n\t\tcase \"minimal\":\n\t\t\treturn \"MINIMAL\";\n\t\tcase \"low\":\n\t\t\treturn \"LOW\";\n\t\tcase \"medium\":\n\t\t\treturn \"MEDIUM\";\n\t\tcase \"high\":\n\t\t\treturn \"HIGH\";\n\t}\n}\n"]}
1
+ {"version":3,"file":"google-gemini-cli.d.ts","sourceRoot":"","sources":["../../src/providers/google-gemini-cli.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE7D,OAAO,KAAK,EAGX,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,cAAc,EACd,aAAa,EAMb,MAAM,aAAa,CAAC;AAIrB,OAAO,EAEN,YAAY,EAGZ,aAAa,EAEb,MAAM,oBAAoB,CAAC;AAG5B;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,4BAA4B,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEvG,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;IACrC;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE;QACV,OAAO,EAAE,OAAO,CAAC;QACjB,4DAA4D;QAC5D,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB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AAmB,CAAC,EACjC,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,sBAA2B,EACpC,aAAa,UAAQ,GACnB,sBAAsB,CA8ExB","sourcesContent":["/**\n * Google Gemini CLI / Antigravity provider.\n * Shared implementation for both google-gemini-cli and google-antigravity providers.\n * Uses the Cloud Code Assist API endpoint to access Gemini and Claude models.\n */\n\nimport type { Content, ThinkingConfig } from \"@google/genai\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tToolCall,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { headersToRecord } from \"../utils/headers.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tisThinkingPart,\n\tmapStopReasonString,\n\tmapToolChoice,\n\tretainThoughtSignature,\n} from \"./google-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\n/**\n * Thinking level for Gemini 3 models.\n * Mirrors Google's ThinkingLevel enum values.\n */\nexport type GoogleThinkingLevel = \"THINKING_LEVEL_UNSPECIFIED\" | \"MINIMAL\" | \"LOW\" | \"MEDIUM\" | \"HIGH\";\n\nexport interface GoogleGeminiCliOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\";\n\t/**\n\t * Thinking/reasoning configuration.\n\t * - Gemini 2.x models: use `budgetTokens` to set the thinking budget\n\t * - Gemini 3 models (gemini-3-pro-*, gemini-3-flash-*): use `level` instead\n\t *\n\t * When using `streamSimple`, this is handled automatically based on the model.\n\t */\n\tthinking?: {\n\t\tenabled: boolean;\n\t\t/** Thinking budget in tokens. Use for Gemini 2.x models. */\n\t\tbudgetTokens?: number;\n\t\t/** Thinking level. Use for Gemini 3 models (LOW/HIGH for Pro, MINIMAL/LOW/MEDIUM/HIGH for Flash). */\n\t\tlevel?: GoogleThinkingLevel;\n\t};\n\tprojectId?: string;\n}\n\nconst DEFAULT_ENDPOINT = \"https://cloudcode-pa.googleapis.com\";\nconst ANTIGRAVITY_DAILY_ENDPOINT = \"https://daily-cloudcode-pa.sandbox.googleapis.com\";\nconst ANTIGRAVITY_AUTOPUSH_ENDPOINT = \"https://autopush-cloudcode-pa.sandbox.googleapis.com\";\nconst ANTIGRAVITY_ENDPOINT_FALLBACKS = [\n\tANTIGRAVITY_DAILY_ENDPOINT,\n\tANTIGRAVITY_AUTOPUSH_ENDPOINT,\n\tDEFAULT_ENDPOINT,\n] as const;\n// Headers for Gemini CLI (prod endpoint)\nconst GEMINI_CLI_HEADERS = {\n\t\"User-Agent\": \"google-cloud-sdk vscode_cloudshelleditor/0.1\",\n\t\"X-Goog-Api-Client\": \"gl-node/22.17.0\",\n\t\"Client-Metadata\": JSON.stringify({\n\t\tideType: \"IDE_UNSPECIFIED\",\n\t\tplatform: \"PLATFORM_UNSPECIFIED\",\n\t\tpluginType: \"GEMINI\",\n\t}),\n};\n\n// Headers for Antigravity (sandbox endpoint) - requires specific User-Agent\nconst DEFAULT_ANTIGRAVITY_VERSION = \"1.21.9\";\n\nfunction getAntigravityHeaders() {\n\tconst version = process.env.PI_AI_ANTIGRAVITY_VERSION || DEFAULT_ANTIGRAVITY_VERSION;\n\treturn {\n\t\t\"User-Agent\": `antigravity/${version} darwin/arm64`,\n\t};\n}\n\n// Antigravity system instruction (compact version from CLIProxyAPI).\nconst ANTIGRAVITY_SYSTEM_INSTRUCTION =\n\t\"You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\" +\n\t\"You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.\" +\n\t\"**Absolute paths only**\" +\n\t\"**Proactiveness**\";\n\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\n\n// Retry configuration\nconst MAX_RETRIES = 3;\nconst BASE_DELAY_MS = 1000;\nconst MAX_EMPTY_STREAM_RETRIES = 2;\nconst EMPTY_STREAM_BASE_DELAY_MS = 500;\nconst CLAUDE_THINKING_BETA_HEADER = \"interleaved-thinking-2025-05-14\";\n\n/**\n * Extract retry delay from Gemini error response (in milliseconds).\n * Checks headers first (Retry-After, x-ratelimit-reset, x-ratelimit-reset-after),\n * then parses body patterns like:\n * - \"Your quota will reset after 39s\"\n * - \"Your quota will reset after 18h31m10s\"\n * - \"Please retry in Xs\" or \"Please retry in Xms\"\n * - \"retryDelay\": \"34.074824224s\" (JSON field)\n */\nexport function extractRetryDelay(errorText: string, response?: Response | Headers): number | undefined {\n\tconst normalizeDelay = (ms: number): number | undefined => (ms > 0 ? Math.ceil(ms + 1000) : undefined);\n\n\tconst headers = response instanceof Headers ? response : response?.headers;\n\tif (headers) {\n\t\tconst retryAfter = headers.get(\"retry-after\");\n\t\tif (retryAfter) {\n\t\t\tconst retryAfterSeconds = Number(retryAfter);\n\t\t\tif (Number.isFinite(retryAfterSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(retryAfterSeconds * 1000);\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst retryAfterDate = new Date(retryAfter);\n\t\t\tconst retryAfterMs = retryAfterDate.getTime();\n\t\t\tif (!Number.isNaN(retryAfterMs)) {\n\t\t\t\tconst delay = normalizeDelay(retryAfterMs - Date.now());\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst rateLimitReset = headers.get(\"x-ratelimit-reset\");\n\t\tif (rateLimitReset) {\n\t\t\tconst resetSeconds = Number.parseInt(rateLimitReset, 10);\n\t\t\tif (!Number.isNaN(resetSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(resetSeconds * 1000 - Date.now());\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst rateLimitResetAfter = headers.get(\"x-ratelimit-reset-after\");\n\t\tif (rateLimitResetAfter) {\n\t\t\tconst resetAfterSeconds = Number(rateLimitResetAfter);\n\t\t\tif (Number.isFinite(resetAfterSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(resetAfterSeconds * 1000);\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 1: \"Your quota will reset after ...\" (formats: \"18h31m10s\", \"10m15s\", \"6s\", \"39s\")\n\tconst durationMatch = errorText.match(/reset after (?:(\\d+)h)?(?:(\\d+)m)?(\\d+(?:\\.\\d+)?)s/i);\n\tif (durationMatch) {\n\t\tconst hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0;\n\t\tconst minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;\n\t\tconst seconds = parseFloat(durationMatch[3]);\n\t\tif (!Number.isNaN(seconds)) {\n\t\t\tconst totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1000;\n\t\t\tconst delay = normalizeDelay(totalMs);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 2: \"Please retry in X[ms|s]\"\n\tconst retryInMatch = errorText.match(/Please retry in ([0-9.]+)(ms|s)/i);\n\tif (retryInMatch?.[1]) {\n\t\tconst value = parseFloat(retryInMatch[1]);\n\t\tif (!Number.isNaN(value) && value > 0) {\n\t\t\tconst ms = retryInMatch[2].toLowerCase() === \"ms\" ? value : value * 1000;\n\t\t\tconst delay = normalizeDelay(ms);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 3: \"retryDelay\": \"34.074824224s\" (JSON field in error details)\n\tconst retryDelayMatch = errorText.match(/\"retryDelay\":\\s*\"([0-9.]+)(ms|s)\"/i);\n\tif (retryDelayMatch?.[1]) {\n\t\tconst value = parseFloat(retryDelayMatch[1]);\n\t\tif (!Number.isNaN(value) && value > 0) {\n\t\t\tconst ms = retryDelayMatch[2].toLowerCase() === \"ms\" ? value : value * 1000;\n\t\t\tconst delay = normalizeDelay(ms);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction needsClaudeThinkingBetaHeader(model: Model<\"google-gemini-cli\">): boolean {\n\treturn model.provider === \"google-antigravity\" && model.id.startsWith(\"claude-\") && model.reasoning;\n}\n\nfunction isGemini3ProModel(modelId: string): boolean {\n\treturn /gemini-3(?:\\.1)?-pro/.test(modelId.toLowerCase());\n}\n\nfunction isGemini3FlashModel(modelId: string): boolean {\n\treturn /gemini-3(?:\\.1)?-flash/.test(modelId.toLowerCase());\n}\n\nfunction isGemini3Model(modelId: string): boolean {\n\treturn isGemini3ProModel(modelId) || isGemini3FlashModel(modelId);\n}\n\n/**\n * Check if an error is retryable (rate limit, server error, network error, etc.)\n */\nfunction isRetryableError(status: number, errorText: string): boolean {\n\tif (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {\n\t\treturn true;\n\t}\n\treturn /resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(errorText);\n}\n\n/**\n * Extract a clean, user-friendly error message from Google API error response.\n * Parses JSON error responses and returns just the message field.\n */\nfunction extractErrorMessage(errorText: string): string {\n\ttry {\n\t\tconst parsed = JSON.parse(errorText) as { error?: { message?: string } };\n\t\tif (parsed.error?.message) {\n\t\t\treturn parsed.error.message;\n\t\t}\n\t} catch {\n\t\t// Not JSON, return as-is\n\t}\n\treturn errorText;\n}\n\n/**\n * Sleep for a given number of milliseconds, respecting abort signal.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t});\n\t});\n}\n\ninterface CloudCodeAssistRequest {\n\tproject: string;\n\tmodel: string;\n\trequest: {\n\t\tcontents: Content[];\n\t\tsessionId?: string;\n\t\tsystemInstruction?: { role?: string; parts: { text: string }[] };\n\t\tgenerationConfig?: {\n\t\t\tmaxOutputTokens?: number;\n\t\t\ttemperature?: number;\n\t\t\tthinkingConfig?: ThinkingConfig;\n\t\t};\n\t\ttools?: ReturnType<typeof convertTools>;\n\t\ttoolConfig?: {\n\t\t\tfunctionCallingConfig: {\n\t\t\t\tmode: ReturnType<typeof mapToolChoice>;\n\t\t\t};\n\t\t};\n\t};\n\trequestType?: string;\n\tuserAgent?: string;\n\trequestId?: string;\n}\n\ninterface CloudCodeAssistResponseChunk {\n\tresponse?: {\n\t\tcandidates?: Array<{\n\t\t\tcontent?: {\n\t\t\t\trole: string;\n\t\t\t\tparts?: Array<{\n\t\t\t\t\ttext?: string;\n\t\t\t\t\tthought?: boolean;\n\t\t\t\t\tthoughtSignature?: string;\n\t\t\t\t\tfunctionCall?: {\n\t\t\t\t\t\tname: string;\n\t\t\t\t\t\targs: Record<string, unknown>;\n\t\t\t\t\t\tid?: string;\n\t\t\t\t\t};\n\t\t\t\t}>;\n\t\t\t};\n\t\t\tfinishReason?: string;\n\t\t}>;\n\t\tusageMetadata?: {\n\t\t\tpromptTokenCount?: number;\n\t\t\tcandidatesTokenCount?: number;\n\t\t\tthoughtsTokenCount?: number;\n\t\t\ttotalTokenCount?: number;\n\t\t\tcachedContentTokenCount?: number;\n\t\t};\n\t\tmodelVersion?: string;\n\t\tresponseId?: string;\n\t};\n\ttraceId?: string;\n}\n\nexport const streamGoogleGeminiCli: StreamFunction<\"google-gemini-cli\", GoogleGeminiCliOptions> = (\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\toptions?: GoogleGeminiCliOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"google-gemini-cli\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\t// apiKey is JSON-encoded: { token, projectId }\n\t\t\tconst apiKeyRaw = options?.apiKey;\n\t\t\tif (!apiKeyRaw) {\n\t\t\t\tthrow new Error(\"Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.\");\n\t\t\t}\n\n\t\t\tlet accessToken: string;\n\t\t\tlet projectId: string;\n\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(apiKeyRaw) as { token: string; projectId: string };\n\t\t\t\taccessToken = parsed.token;\n\t\t\t\tprojectId = parsed.projectId;\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.\");\n\t\t\t}\n\n\t\t\tif (!accessToken || !projectId) {\n\t\t\t\tthrow new Error(\"Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.\");\n\t\t\t}\n\n\t\t\tconst isAntigravity = model.provider === \"google-antigravity\";\n\t\t\tconst baseUrl = model.baseUrl?.trim();\n\t\t\tconst endpoints = baseUrl ? [baseUrl] : isAntigravity ? ANTIGRAVITY_ENDPOINT_FALLBACKS : [DEFAULT_ENDPOINT];\n\n\t\t\tlet requestBody = buildRequest(model, context, projectId, options, isAntigravity);\n\t\t\tconst nextRequestBody = await options?.onPayload?.(requestBody, model);\n\t\t\tif (nextRequestBody !== undefined) {\n\t\t\t\trequestBody = nextRequestBody as CloudCodeAssistRequest;\n\t\t\t}\n\t\t\tconst headers = isAntigravity ? getAntigravityHeaders() : GEMINI_CLI_HEADERS;\n\n\t\t\tconst requestHeaders = {\n\t\t\t\tAuthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\tAccept: \"text/event-stream\",\n\t\t\t\t...headers,\n\t\t\t\t...(needsClaudeThinkingBetaHeader(model) ? { \"anthropic-beta\": CLAUDE_THINKING_BETA_HEADER } : {}),\n\t\t\t\t...options?.headers,\n\t\t\t};\n\t\t\tconst requestBodyJson = JSON.stringify(requestBody);\n\n\t\t\t// Fetch with retry logic for rate limits, transient errors, and endpoint fallbacks.\n\t\t\t// On 403/404, immediately try the next endpoint (no delay).\n\t\t\t// On 429/5xx, retry with backoff on the same or next endpoint.\n\t\t\tlet response: Response | undefined;\n\t\t\tlet lastError: Error | undefined;\n\t\t\tlet requestUrl: string | undefined;\n\t\t\tlet endpointIndex = 0;\n\n\t\t\tfor (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconst endpoint = endpoints[endpointIndex];\n\t\t\t\t\trequestUrl = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;\n\t\t\t\t\tresponse = await fetch(requestUrl, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders,\n\t\t\t\t\t\tbody: requestBodyJson,\n\t\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t\t});\n\t\t\t\t\tawait options?.onResponse?.(\n\t\t\t\t\t\t{ status: response.status, headers: headersToRecord(response.headers) },\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tbreak; // Success, exit retry loop\n\t\t\t\t\t}\n\n\t\t\t\t\tconst errorText = await response.text();\n\n\t\t\t\t\t// On 403/404, cascade to the next endpoint immediately (no delay)\n\t\t\t\t\tif ((response.status === 403 || response.status === 404) && endpointIndex < endpoints.length - 1) {\n\t\t\t\t\t\tendpointIndex++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Check if retryable (429, 5xx, network patterns)\n\t\t\t\t\tif (attempt < MAX_RETRIES && isRetryableError(response.status, errorText)) {\n\t\t\t\t\t\t// Advance endpoint if possible\n\t\t\t\t\t\tif (endpointIndex < endpoints.length - 1) {\n\t\t\t\t\t\t\tendpointIndex++;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Use server-provided delay or exponential backoff\n\t\t\t\t\t\tconst serverDelay = extractRetryDelay(errorText, response);\n\t\t\t\t\t\tconst delayMs = serverDelay ?? BASE_DELAY_MS * 2 ** attempt;\n\n\t\t\t\t\t\t// Check if server delay exceeds max allowed (default: 60s)\n\t\t\t\t\t\tconst maxDelayMs = options?.maxRetryDelayMs ?? 60000;\n\t\t\t\t\t\tif (maxDelayMs > 0 && serverDelay && serverDelay > maxDelayMs) {\n\t\t\t\t\t\t\tconst delaySeconds = Math.ceil(serverDelay / 1000);\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Server requested ${delaySeconds}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${extractErrorMessage(errorText)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Not retryable or max retries exceeded\n\t\t\t\t\tthrow new Error(`Cloud Code Assist API error (${response.status}): ${extractErrorMessage(errorText)}`);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Check for abort - fetch throws AbortError, our code throws \"Request was aborted\"\n\t\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\t\tif (error.name === \"AbortError\" || error.message === \"Request was aborted\") {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Extract detailed error message from fetch errors (Node includes cause)\n\t\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\tif (lastError.message === \"fetch failed\" && lastError.cause instanceof Error) {\n\t\t\t\t\t\tlastError = new Error(`Network error: ${lastError.cause.message}`);\n\t\t\t\t\t}\n\t\t\t\t\t// Network errors are retryable\n\t\t\t\t\tif (attempt < MAX_RETRIES) {\n\t\t\t\t\t\tconst delayMs = BASE_DELAY_MS * 2 ** attempt;\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!response || !response.ok) {\n\t\t\t\tthrow lastError ?? new Error(\"Failed to get response after retries\");\n\t\t\t}\n\n\t\t\tlet started = false;\n\t\t\tconst ensureStarted = () => {\n\t\t\t\tif (!started) {\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\tstarted = true;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst resetOutput = () => {\n\t\t\t\toutput.content = [];\n\t\t\t\toutput.usage = {\n\t\t\t\t\tinput: 0,\n\t\t\t\t\toutput: 0,\n\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t\toutput.stopReason = \"stop\";\n\t\t\t\toutput.errorMessage = undefined;\n\t\t\t\toutput.timestamp = Date.now();\n\t\t\t\tstarted = false;\n\t\t\t};\n\n\t\t\tconst streamResponse = async (activeResponse: Response): Promise<boolean> => {\n\t\t\t\tif (!activeResponse.body) {\n\t\t\t\t\tthrow new Error(\"No response body\");\n\t\t\t\t}\n\n\t\t\t\tlet hasContent = false;\n\t\t\t\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\t\t\t\tconst blocks = output.content;\n\t\t\t\tconst blockIndex = () => blocks.length - 1;\n\n\t\t\t\t// Read SSE stream\n\t\t\t\tconst reader = activeResponse.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\n\t\t\t\t// Set up abort handler to cancel reader when signal fires\n\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\tvoid reader.cancel().catch(() => {});\n\t\t\t\t};\n\t\t\t\toptions?.signal?.addEventListener(\"abort\", abortHandler);\n\n\t\t\t\ttry {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t// Check abort signal before each read\n\t\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) break;\n\n\t\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\n\t\t\t\t\t\t\tconst jsonStr = line.slice(5).trim();\n\t\t\t\t\t\t\tif (!jsonStr) continue;\n\n\t\t\t\t\t\t\tlet chunk: CloudCodeAssistResponseChunk;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tchunk = JSON.parse(jsonStr);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Unwrap the response\n\t\t\t\t\t\t\tconst responseData = chunk.response;\n\t\t\t\t\t\t\tif (!responseData) continue;\n\t\t\t\t\t\t\t// Cloud Code Assist mirrors Gemini's responseId field. Keep the first non-empty one.\n\t\t\t\t\t\t\t// A single streamed response should retain the same ID across chunks.\n\t\t\t\t\t\t\toutput.responseId ||= responseData.responseId;\n\n\t\t\t\t\t\t\tconst candidate = responseData.candidates?.[0];\n\t\t\t\t\t\t\tif (candidate?.content?.parts) {\n\t\t\t\t\t\t\t\tfor (const part of candidate.content.parts) {\n\t\t\t\t\t\t\t\t\tif (part.text !== undefined) {\n\t\t\t\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t\t\t\t\tconst isThinking = isThinkingPart(part);\n\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t!currentBlock ||\n\t\t\t\t\t\t\t\t\t\t\t(isThinking && currentBlock.type !== \"thinking\") ||\n\t\t\t\t\t\t\t\t\t\t\t(!isThinking && currentBlock.type !== \"text\")\n\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blocks.length - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (isThinking) {\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n\t\t\t\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_start\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"thinking\") {\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinking += part.text;\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature,\n\t\t\t\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.text += part.text;\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature,\n\t\t\t\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = null;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst providedId = part.functionCall.id;\n\t\t\t\t\t\t\t\t\t\tconst needsNewId =\n\t\t\t\t\t\t\t\t\t\t\t!providedId ||\n\t\t\t\t\t\t\t\t\t\t\toutput.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n\t\t\t\t\t\t\t\t\t\tconst toolCallId = needsNewId\n\t\t\t\t\t\t\t\t\t\t\t? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n\t\t\t\t\t\t\t\t\t\t\t: providedId;\n\n\t\t\t\t\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\t\t\t\t\tid: toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tname: part.functionCall.name || \"\",\n\t\t\t\t\t\t\t\t\t\t\targuments: (part.functionCall.args as Record<string, unknown>) ?? {},\n\t\t\t\t\t\t\t\t\t\t\t...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\toutput.content.push(toolCall);\n\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\tdelta: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\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}\n\n\t\t\t\t\t\t\tif (candidate?.finishReason) {\n\t\t\t\t\t\t\t\toutput.stopReason = mapStopReasonString(candidate.finishReason);\n\t\t\t\t\t\t\t\tif (output.content.some((b) => b.type === \"toolCall\")) {\n\t\t\t\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (responseData.usageMetadata) {\n\t\t\t\t\t\t\t\t// promptTokenCount includes cachedContentTokenCount, so subtract to get fresh input\n\t\t\t\t\t\t\t\tconst promptTokens = responseData.usageMetadata.promptTokenCount || 0;\n\t\t\t\t\t\t\t\tconst cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;\n\t\t\t\t\t\t\t\toutput.usage = {\n\t\t\t\t\t\t\t\t\tinput: promptTokens - cacheReadTokens,\n\t\t\t\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\t\t\t\t(responseData.usageMetadata.candidatesTokenCount || 0) +\n\t\t\t\t\t\t\t\t\t\t(responseData.usageMetadata.thoughtsTokenCount || 0),\n\t\t\t\t\t\t\t\t\tcacheRead: cacheReadTokens,\n\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\ttotalTokens: responseData.usageMetadata.totalTokenCount || 0,\n\t\t\t\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\t\ttotal: 0,\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\tcalculateCost(model, output.usage);\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} finally {\n\t\t\t\t\toptions?.signal?.removeEventListener(\"abort\", abortHandler);\n\t\t\t\t}\n\n\t\t\t\tif (currentBlock) {\n\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn hasContent;\n\t\t\t};\n\n\t\t\tlet receivedContent = false;\n\t\t\tlet currentResponse = response;\n\n\t\t\tfor (let emptyAttempt = 0; emptyAttempt <= MAX_EMPTY_STREAM_RETRIES; emptyAttempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\tif (emptyAttempt > 0) {\n\t\t\t\t\tconst backoffMs = EMPTY_STREAM_BASE_DELAY_MS * 2 ** (emptyAttempt - 1);\n\t\t\t\t\tawait sleep(backoffMs, options?.signal);\n\n\t\t\t\t\tif (!requestUrl) {\n\t\t\t\t\t\tthrow new Error(\"Missing request URL\");\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentResponse = await fetch(requestUrl, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders,\n\t\t\t\t\t\tbody: requestBodyJson,\n\t\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t\t});\n\t\t\t\t\tawait options?.onResponse?.(\n\t\t\t\t\t\t{ status: currentResponse.status, headers: headersToRecord(currentResponse.headers) },\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (!currentResponse.ok) {\n\t\t\t\t\t\tconst retryErrorText = await currentResponse.text();\n\t\t\t\t\t\tthrow new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst streamed = await streamResponse(currentResponse);\n\t\t\t\tif (streamed) {\n\t\t\t\t\treceivedContent = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (emptyAttempt < MAX_EMPTY_STREAM_RETRIES) {\n\t\t\t\t\tresetOutput();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!receivedContent) {\n\t\t\t\tthrow new Error(\"Cloud Code Assist API returned an empty response\");\n\t\t\t}\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tif (\"index\" in block) {\n\t\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleGoogleGeminiCli: StreamFunction<\"google-gemini-cli\", SimpleStreamOptions> = (\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(\"Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.\");\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tif (!options?.reasoning) {\n\t\treturn streamGoogleGeminiCli(model, context, {\n\t\t\t...base,\n\t\t\tthinking: { enabled: false },\n\t\t} satisfies GoogleGeminiCliOptions);\n\t}\n\n\tconst effort = clampReasoning(options.reasoning)!;\n\tif (isGemini3Model(model.id)) {\n\t\treturn streamGoogleGeminiCli(model, context, {\n\t\t\t...base,\n\t\t\tthinking: {\n\t\t\t\tenabled: true,\n\t\t\t\tlevel: getGeminiCliThinkingLevel(effort, model.id),\n\t\t\t},\n\t\t} satisfies GoogleGeminiCliOptions);\n\t}\n\n\tconst defaultBudgets: ThinkingBudgets = {\n\t\tminimal: 1024,\n\t\tlow: 2048,\n\t\tmedium: 8192,\n\t\thigh: 16384,\n\t};\n\tconst budgets = { ...defaultBudgets, ...options.thinkingBudgets };\n\n\tconst minOutputTokens = 1024;\n\tlet thinkingBudget = budgets[effort]!;\n\tconst maxTokens = Math.min((base.maxTokens || 0) + thinkingBudget, model.maxTokens);\n\n\tif (maxTokens <= thinkingBudget) {\n\t\tthinkingBudget = Math.max(0, maxTokens - minOutputTokens);\n\t}\n\n\treturn streamGoogleGeminiCli(model, context, {\n\t\t...base,\n\t\tmaxTokens,\n\t\tthinking: {\n\t\t\tenabled: true,\n\t\t\tbudgetTokens: thinkingBudget,\n\t\t},\n\t} satisfies GoogleGeminiCliOptions);\n};\n\nexport function buildRequest(\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\tprojectId: string,\n\toptions: GoogleGeminiCliOptions = {},\n\tisAntigravity = false,\n): CloudCodeAssistRequest {\n\tconst contents = convertMessages(model, context);\n\n\tconst generationConfig: CloudCodeAssistRequest[\"request\"][\"generationConfig\"] = {};\n\tif (options.temperature !== undefined) {\n\t\tgenerationConfig.temperature = options.temperature;\n\t}\n\tif (options.maxTokens !== undefined) {\n\t\tgenerationConfig.maxOutputTokens = options.maxTokens;\n\t}\n\n\t// Thinking config\n\tif (options.thinking?.enabled && model.reasoning) {\n\t\tgenerationConfig.thinkingConfig = {\n\t\t\tincludeThoughts: true,\n\t\t};\n\t\t// Gemini 3 models use thinkingLevel, older models use thinkingBudget\n\t\tif (options.thinking.level !== undefined) {\n\t\t\t// Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values\n\t\t\tgenerationConfig.thinkingConfig.thinkingLevel = options.thinking.level as any;\n\t\t} else if (options.thinking.budgetTokens !== undefined) {\n\t\t\tgenerationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n\t\t}\n\t} else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n\t\tgenerationConfig.thinkingConfig = getDisabledThinkingConfig(model.id);\n\t}\n\n\tconst request: CloudCodeAssistRequest[\"request\"] = {\n\t\tcontents,\n\t};\n\n\trequest.sessionId = options.sessionId;\n\n\t// System instruction must be object with parts, not plain string\n\tif (context.systemPrompt) {\n\t\trequest.systemInstruction = {\n\t\t\tparts: [{ text: sanitizeSurrogates(context.systemPrompt) }],\n\t\t};\n\t}\n\n\tif (Object.keys(generationConfig).length > 0) {\n\t\trequest.generationConfig = generationConfig;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\t// Claude models on Cloud Code Assist need the legacy `parameters` field;\n\t\t// the API translates it into Anthropic's `input_schema`.\n\t\tconst useParameters = model.id.startsWith(\"claude-\");\n\t\trequest.tools = convertTools(context.tools, useParameters);\n\t\tif (options.toolChoice) {\n\t\t\trequest.toolConfig = {\n\t\t\t\tfunctionCallingConfig: {\n\t\t\t\t\tmode: mapToolChoice(options.toolChoice),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\tif (isAntigravity) {\n\t\tconst existingParts = request.systemInstruction?.parts ?? [];\n\t\trequest.systemInstruction = {\n\t\t\trole: \"user\",\n\t\t\tparts: [\n\t\t\t\t{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION },\n\t\t\t\t{ text: `Please ignore following [ignore]${ANTIGRAVITY_SYSTEM_INSTRUCTION}[/ignore]` },\n\t\t\t\t...existingParts,\n\t\t\t],\n\t\t};\n\t}\n\n\treturn {\n\t\tproject: projectId,\n\t\tmodel: model.id,\n\t\trequest,\n\t\t...(isAntigravity ? { requestType: \"agent\" } : {}),\n\t\tuserAgent: isAntigravity ? \"antigravity\" : \"pi-coding-agent\",\n\t\trequestId: `${isAntigravity ? \"agent\" : \"pi\"}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,\n\t};\n}\n\ntype ClampedThinkingLevel = Exclude<ThinkingLevel, \"xhigh\">;\n\nfunction getDisabledThinkingConfig(modelId: string): ThinkingConfig {\n\t// Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n\t// do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n\t// thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n\tif (isGemini3ProModel(modelId)) {\n\t\treturn { thinkingLevel: \"LOW\" as any };\n\t}\n\tif (isGemini3FlashModel(modelId)) {\n\t\treturn { thinkingLevel: \"MINIMAL\" as any };\n\t}\n\n\t// Gemini 2.x supports disabling via thinkingBudget = 0.\n\treturn { thinkingBudget: 0 };\n}\n\nfunction getGeminiCliThinkingLevel(effort: ClampedThinkingLevel, modelId: string): GoogleThinkingLevel {\n\tif (isGemini3ProModel(modelId)) {\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn \"LOW\";\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn \"HIGH\";\n\t\t}\n\t}\n\tswitch (effort) {\n\t\tcase \"minimal\":\n\t\t\treturn \"MINIMAL\";\n\t\tcase \"low\":\n\t\t\treturn \"LOW\";\n\t\tcase \"medium\":\n\t\t\treturn \"MEDIUM\";\n\t\tcase \"high\":\n\t\t\treturn \"HIGH\";\n\t}\n}\n"]}
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { calculateCost } from "../models.js";
7
7
  import { AssistantMessageEventStream } from "../utils/event-stream.js";
8
+ import { headersToRecord } from "../utils/headers.js";
8
9
  import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
9
10
  import { convertMessages, convertTools, isThinkingPart, mapStopReasonString, mapToolChoice, retainThoughtSignature, } from "./google-shared.js";
10
11
  import { buildBaseOptions, clampReasoning } from "./simple-options.js";
@@ -269,6 +270,7 @@ export const streamGoogleGeminiCli = (model, context, options) => {
269
270
  body: requestBodyJson,
270
271
  signal: options?.signal,
271
272
  });
273
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
272
274
  if (response.ok) {
273
275
  break; // Success, exit retry loop
274
276
  }
@@ -582,6 +584,7 @@ export const streamGoogleGeminiCli = (model, context, options) => {
582
584
  body: requestBodyJson,
583
585
  signal: options?.signal,
584
586
  });
587
+ await options?.onResponse?.({ status: currentResponse.status, headers: headersToRecord(currentResponse.headers) }, model);
585
588
  if (!currentResponse.ok) {
586
589
  const retryErrorText = await currentResponse.text();
587
590
  throw new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`);