@code-yeongyu/senpi-ai 2026.9.12 → 2026.9.13

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 (110) hide show
  1. package/README.md +39 -4
  2. package/dist/api/anthropic-messages.d.ts.map +1 -1
  3. package/dist/api/anthropic-messages.js +8 -1
  4. package/dist/api/anthropic-messages.js.map +1 -1
  5. package/dist/api/cloudflare-ai-binding.d.ts +77 -0
  6. package/dist/api/cloudflare-ai-binding.d.ts.map +1 -0
  7. package/dist/api/cloudflare-ai-binding.js +72 -0
  8. package/dist/api/cloudflare-ai-binding.js.map +1 -0
  9. package/dist/api/cursor-agent/measure.d.ts +11 -0
  10. package/dist/api/cursor-agent/measure.d.ts.map +1 -1
  11. package/dist/api/cursor-agent/measure.js +18 -0
  12. package/dist/api/cursor-agent/measure.js.map +1 -1
  13. package/dist/api/cursor-agent.d.ts +1 -1
  14. package/dist/api/cursor-agent.d.ts.map +1 -1
  15. package/dist/api/cursor-agent.js +5 -1
  16. package/dist/api/cursor-agent.js.map +1 -1
  17. package/dist/api/mistral-conversations.js +4 -1
  18. package/dist/api/mistral-conversations.js.map +1 -1
  19. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  20. package/dist/api/openai-codex-responses.js +6 -3
  21. package/dist/api/openai-codex-responses.js.map +1 -1
  22. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  23. package/dist/api/openai-responses-shared.js +4 -1
  24. package/dist/api/openai-responses-shared.js.map +1 -1
  25. package/dist/api/openai-responses.d.ts.map +1 -1
  26. package/dist/api/openai-responses.js +13 -3
  27. package/dist/api/openai-responses.js.map +1 -1
  28. package/dist/cursor/context-limit-store.d.ts +32 -0
  29. package/dist/cursor/context-limit-store.d.ts.map +1 -0
  30. package/dist/cursor/context-limit-store.js +62 -0
  31. package/dist/cursor/context-limit-store.js.map +1 -0
  32. package/dist/cursor/store-migration.d.ts.map +1 -1
  33. package/dist/cursor/store-migration.js +2 -1
  34. package/dist/cursor/store-migration.js.map +1 -1
  35. package/dist/index.d.ts +2 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +2 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/models.d.ts +1 -0
  40. package/dist/models.d.ts.map +1 -1
  41. package/dist/models.js +5 -2
  42. package/dist/models.js.map +1 -1
  43. package/dist/openai-responses-compat.d.ts +1 -1
  44. package/dist/openai-responses-compat.d.ts.map +1 -1
  45. package/dist/openai-responses-compat.js.map +1 -1
  46. package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
  47. package/dist/providers/cloudflare-ai-gateway.js +4 -0
  48. package/dist/providers/cloudflare-ai-gateway.js.map +1 -1
  49. package/dist/providers/cursor.d.ts.map +1 -1
  50. package/dist/providers/cursor.js +2 -1
  51. package/dist/providers/cursor.js.map +1 -1
  52. package/dist/providers/data/.manifest.json +1 -1
  53. package/dist/providers/data/azure-openai-responses.json +1 -1
  54. package/dist/providers/data/baseten.json +1 -1
  55. package/dist/providers/data/deepseek.json +1 -1
  56. package/dist/providers/data/fireworks.json +1 -1
  57. package/dist/providers/data/github-copilot.json +1 -1
  58. package/dist/providers/data/openai-codex.json +1 -1
  59. package/dist/providers/data/openrouter.json +1 -1
  60. package/dist/providers/data/qwen-token-plan-cn.json +1 -1
  61. package/dist/providers/data/qwen-token-plan-individual.json +1 -1
  62. package/dist/providers/data/qwen-token-plan.json +1 -1
  63. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  64. package/dist/providers/data/xai.json +1 -1
  65. package/dist/providers/faux.js +5 -5
  66. package/dist/providers/faux.js.map +1 -1
  67. package/dist/providers/opencode-go.d.ts.map +1 -1
  68. package/dist/providers/opencode-go.js +4 -3
  69. package/dist/providers/opencode-go.js.map +1 -1
  70. package/dist/providers/opencode-headers.d.ts +4 -0
  71. package/dist/providers/opencode-headers.d.ts.map +1 -0
  72. package/dist/providers/opencode-headers.js +22 -0
  73. package/dist/providers/opencode-headers.js.map +1 -0
  74. package/dist/providers/opencode.d.ts.map +1 -1
  75. package/dist/providers/opencode.js +5 -4
  76. package/dist/providers/opencode.js.map +1 -1
  77. package/dist/types.d.ts +16 -6
  78. package/dist/types.d.ts.map +1 -1
  79. package/dist/types.js.map +1 -1
  80. package/dist/utils/assistant-message-frame.d.ts +77 -0
  81. package/dist/utils/assistant-message-frame.d.ts.map +1 -0
  82. package/dist/utils/assistant-message-frame.js +427 -0
  83. package/dist/utils/assistant-message-frame.js.map +1 -0
  84. package/dist/utils/cursor-context-limit.d.ts +12 -0
  85. package/dist/utils/cursor-context-limit.d.ts.map +1 -0
  86. package/dist/utils/cursor-context-limit.js +93 -0
  87. package/dist/utils/cursor-context-limit.js.map +1 -0
  88. package/dist/utils/event-stream.d.ts.map +1 -1
  89. package/dist/utils/event-stream.js +25 -5
  90. package/dist/utils/event-stream.js.map +1 -1
  91. package/dist/utils/prompt-cache-ttl.d.ts +1 -1
  92. package/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
  93. package/dist/utils/prompt-cache-ttl.js +5 -1
  94. package/dist/utils/prompt-cache-ttl.js.map +1 -1
  95. package/dist/utils/retry-profile/types.d.ts +10 -1
  96. package/dist/utils/retry-profile/types.d.ts.map +1 -1
  97. package/dist/utils/retry-profile/types.js.map +1 -1
  98. package/dist/utils/retry.d.ts +13 -2
  99. package/dist/utils/retry.d.ts.map +1 -1
  100. package/dist/utils/retry.js +18 -7
  101. package/dist/utils/retry.js.map +1 -1
  102. package/dist/utils/uuid.d.ts +2 -2
  103. package/dist/utils/uuid.d.ts.map +1 -1
  104. package/dist/utils/uuid.js +36 -31
  105. package/dist/utils/uuid.js.map +1 -1
  106. package/package.json +6 -6
  107. package/dist/api/cloudflare-gateway-binding.d.ts +0 -69
  108. package/dist/api/cloudflare-gateway-binding.d.ts.map +0 -1
  109. package/dist/api/cloudflare-gateway-binding.js +0 -159
  110. package/dist/api/cloudflare-gateway-binding.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses.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AAY,EACZ,WAA+E,EAC/E,KAA4C;IAE5C,MAAM,UAAU,GAAG,4BAA4B,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IACpE,IAAI,UAAU,KAAK,CAAC;QAAE,OAAO;IAE7B,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,UAAU,CAAC;IAC/B,KAAK,CAAC,IAAI,CAAC,MAAM,IAAI,UAAU,CAAC;IAChC,KAAK,CAAC,IAAI,CAAC,SAAS,IAAI,UAAU,CAAC;IACnC,KAAK,CAAC,IAAI,CAAC,UAAU,IAAI,UAAU,CAAC;IACpC,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC;AACxG,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport type { ResponseCreateParamsStreaming, ResponseStreamEvent } from \"openai/resources/responses/responses.js\";\nimport { clampThinkingLevel, inferOpenAIThinkingLevelMap, supportsMax, supportsXhigh } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tOpenAIResponsesCompat,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.ts\";\nimport { splitDeferredTools } from \"../utils/deferred-tools.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { createGrammarToolInputProperties } from \"./constrained-sampling.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { resolveOpenAIClientAuth } from \"./openai-client-auth.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions, clampMaxForOpenAI, OPENAI_RESPONSES_RESERVED_BODY_KEYS } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\nconst OPENAI_BETA_RESPONSES_WEBSOCKETS = \"responses_websockets=2026-02-06\";\nconst OPENAI_WEB_SEARCH_SOURCES_INCLUDE = \"web_search_call.action.sources\";\nconst SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1000;\n// OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265\nconst OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;\n\ntype WebSocketEventType = \"open\" | \"message\" | \"error\" | \"close\";\ntype WebSocketListener = (event: unknown) => void;\n\ninterface WebSocketLike {\n\tclose(code?: number, reason?: string): void;\n\tsend(data: string): void;\n\taddEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n\tremoveEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n}\n\nexport interface CachedWebSocketConnection {\n\tsocket: WebSocketLike;\n\tbusy: boolean;\n\tidleTimer?: ReturnType<typeof setTimeout>;\n}\n\ntype WebSocketConstructor = new (\n\turl: string,\n\tprotocols?: string | string[] | { headers?: Record<string, string> },\n) => WebSocketLike;\n\ntype MutableResponsesPayload = ResponseCreateParamsStreaming & {\n\tprompt_cache_options?: { mode?: \"explicit\" | \"implicit\" };\n};\n\nconst websocketSessionCache = new Map<string, CachedWebSocketConnection>();\n\nfunction detectSessionAffinityFormat(model: Pick<Model<\"openai-responses\">, \"provider\" | \"baseUrl\">) {\n\treturn model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\") ? \"openrouter\" : \"openai\";\n}\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCompat(model: Model<\"openai-responses\">, env?: ProviderEnv): Required<OpenAIResponsesCompat> {\n\tconst isNativeEndpoint = isOpenAIResponsesNativeEndpoint(model, env);\n\treturn {\n\t\tsupportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true,\n\t\tsessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model),\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n\t\tsupportsWebSocket: model.compat?.supportsWebSocket ?? isNativeEndpoint,\n\t\tsupportsRemoteCompactionV2: model.compat?.supportsRemoteCompactionV2 ?? isNativeEndpoint,\n\t\tsupportsWebSearchPreview: model.compat?.supportsWebSearchPreview ?? isNativeEndpoint,\n\t\tsupportsImageGeneration: model.compat?.supportsImageGeneration ?? isNativeEndpoint,\n\t\tsupportsStrictMode: model.compat?.supportsStrictMode ?? false,\n\t\tsupportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false,\n\t\tsupportsAdditionalTools: model.compat?.supportsAdditionalTools ?? false,\n\t\tsupportsToolSearch: model.compat?.supportsToolSearch ?? false,\n\t\tsupportsExplicitPromptCacheMode: model.compat?.supportsExplicitPromptCacheMode ?? false,\n\t\tsupportsMaxOutputTokens: model.compat?.supportsMaxOutputTokens ?? true,\n\t};\n}\n\nfunction isOpenAIResponsesNativeEndpoint(model: Model<\"openai-responses\">, env?: ProviderEnv): boolean {\n\tconst baseUrl = isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model, env) : model.baseUrl;\n\ttry {\n\t\treturn new URL(baseUrl || \"https://api.openai.com/v1\").hostname === \"api.openai.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getPromptCacheRetention(\n\tcompat: Required<OpenAIResponsesCompat>,\n\tcacheRetention: CacheRetention,\n): \"24h\" | undefined {\n\treturn cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isOpenAiWebSearchPreviewTool(value: unknown): boolean {\n\treturn isRecord(value) && (value.type === \"web_search_preview\" || value.type === \"web_search_preview_2025_03_11\");\n}\n\nfunction sanitizeUnsupportedNativeTools(\n\tparams: MutableResponsesPayload,\n\tcompat: Required<OpenAIResponsesCompat>,\n): MutableResponsesPayload {\n\tif (compat.supportsWebSearchPreview) {\n\t\treturn params;\n\t}\n\n\tconst payload = params as MutableResponsesPayload;\n\tlet sanitized: MutableResponsesPayload | undefined;\n\tconst nextPayload = (): MutableResponsesPayload => {\n\t\tsanitized ??= { ...payload };\n\t\treturn sanitized;\n\t};\n\n\tif (Array.isArray(payload.tools)) {\n\t\tconst tools = payload.tools.filter((tool) => !isOpenAiWebSearchPreviewTool(tool));\n\t\tif (tools.length !== payload.tools.length) {\n\t\t\tconst next = nextPayload();\n\t\t\tif (tools.length > 0) {\n\t\t\t\tnext.tools = tools;\n\t\t\t} else {\n\t\t\t\tdelete next.tools;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Array.isArray(payload.include)) {\n\t\tconst include = payload.include.filter((value) => value !== OPENAI_WEB_SEARCH_SOURCES_INCLUDE);\n\t\tif (include.length !== payload.include.length) {\n\t\t\tconst next = nextPayload();\n\t\t\tif (include.length > 0) {\n\t\t\t\tnext.include = include;\n\t\t\t} else {\n\t\t\t\tdelete next.include;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (isOpenAiWebSearchPreviewTool(payload.tool_choice)) {\n\t\tdelete nextPayload().tool_choice;\n\t}\n\n\treturn sanitized ? (sanitized as ResponseCreateParamsStreaming) : params;\n}\n\nfunction formatOpenAIResponsesError(error: unknown): string {\n\treturn formatProviderError(normalizeProviderError(error), \"OpenAI API error\");\n}\n\n// OpenAI Responses-specific options\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"] | \"fast\";\n\ttoolChoice?: ResponseCreateParamsStreaming[\"tool_choice\"];\n}\n\n/**\n * Generate function for OpenAI Responses API\n */\nexport const stream: StreamFunction<\"openai-responses\", OpenAIResponsesOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api 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: \"pending\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst clientAuth = resolveOpenAIClientAuth(model.provider, options?.apiKey, options?.headers);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst compat = getCompat(model, options?.env);\n\t\t\tconst grammarToolInputProperties = createGrammarToolInputProperties(\n\t\t\t\tcontext.tools,\n\t\t\t\tcompat.supportsOpenAIGrammarTools,\n\t\t\t);\n\t\t\tconst client = createClient(\n\t\t\t\tmodel,\n\t\t\t\tcontext,\n\t\t\t\tclientAuth.apiKey,\n\t\t\t\tclientAuth.headers,\n\t\t\t\toptions?.fetch,\n\t\t\t\tcacheSessionId,\n\t\t\t\toptions?.env,\n\t\t\t);\n\t\t\tlet params = buildParams(model, context, options, compat, grammarToolInputProperties);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as MutableResponsesPayload;\n\t\t\t}\n\n\t\t\tparams = sanitizeUnsupportedNativeTools(params, compat);\n\t\t\tconst transport = options?.transport ?? \"sse\";\n\t\t\tif (transport !== \"sse\" && compat.supportsWebSocket) {\n\t\t\t\tlet websocketStarted = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait processWebSocketStream(\n\t\t\t\t\t\tresolveOpenAIResponsesWebSocketUrl(model, options?.env),\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tbuildWebSocketHeaders(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\tclientAuth.apiKey,\n\t\t\t\t\t\t\tclientAuth.headers,\n\t\t\t\t\t\t\tcacheSessionId,\n\t\t\t\t\t\t\toptions?.env,\n\t\t\t\t\t\t),\n\t\t\t\t\t\toutput,\n\t\t\t\t\t\tstream,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\twebsocketStarted = true;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcacheSessionId,\n\t\t\t\t\t\tgrammarToolInputProperties,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t}\n\n\t\t\t\t\tstream.push({ type: \"done\", reason: getDoneReason(output.stopReason), message: output });\n\t\t\t\t\tstream.end();\n\t\t\t\t\treturn;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (transport === \"websocket\" || websocketStarted) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: 0,\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await retryProviderRequest(\n\t\t\t\t() => client.responses.create(params, requestOptions).withResponse(),\n\t\t\t\t{\n\t\t\t\t\tmaxRetries: options?.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t},\n\t\t\t);\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\t\t\t\tserviceTier: options?.serviceTier,\n\t\t\t\tgrammarToolInputProperties,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\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 === \"pending\") {\n\t\t\t\tthrow new Error(\"OpenAI Responses stream ended without a stop reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// Streaming scratch buffers are only used during parsing; never persist them.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t\tdelete (block as { customInput?: unknown }).customInput;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatOpenAIResponsesError(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 streamSimple: StreamFunction<\"openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tresolveOpenAIClientAuth(model.provider, options?.apiKey, options?.headers);\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, options?.apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t\tserviceTier: options?.serviceTier,\n\t} satisfies OpenAIResponsesOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort =\n\t\tclampedReasoning === \"off\"\n\t\t\t? undefined\n\t\t\t: clampedReasoning === \"max\" && supportsMax(model)\n\t\t\t\t? \"max\"\n\t\t\t\t: clampMaxForOpenAI(clampedReasoning, supportsXhigh(model));\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAIResponsesOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n\tsessionId?: string,\n\tenv?: ProviderEnv,\n) {\n\tconst compat = getCompat(model, env);\n\tconst headers: ProviderHeaders = { \"User-Agent\": getPiUserAgent(), ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId) {\n\t\tif (compat.sessionAffinityFormat === \"openrouter\") {\n\t\t\theaders[\"x-session-id\"] = sessionId;\n\t\t} else {\n\t\t\tif (compat.sessionAffinityFormat === \"openai\") {\n\t\t\t\theaders.session_id = sessionId;\n\t\t\t}\n\t\t\theaders[\"x-client-request-id\"] = sessionId;\n\t\t}\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model, env) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tfetch,\n\t\tdefaultHeaders: headers,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat> = getCompat(model, options?.env),\n\tgrammarToolInputProperties: ReadonlyMap<string, string> = createGrammarToolInputProperties(\n\t\tcontext.tools,\n\t\tcompat.supportsOpenAIGrammarTools,\n\t),\n) {\n\tconst deferredToolsMode = compat.supportsAdditionalTools\n\t\t? \"additional-tools\"\n\t\t: compat.supportsToolSearch\n\t\t\t? \"tool-search\"\n\t\t\t: undefined;\n\tconst toolPlacement = splitDeferredTools(context, deferredToolsMode !== undefined);\n\tconst requestedReasoningEffort = options?.reasoningEffort ?? (options?.reasoningSummary ? \"medium\" : undefined);\n\tconst thinkingLevelMap = inferOpenAIThinkingLevelMap(model);\n\tconst mappedReasoningEffort =\n\t\trequestedReasoningEffort === undefined ? undefined : thinkingLevelMap?.[requestedReasoningEffort];\n\tconst reasoningEffort = mappedReasoningEffort === undefined ? requestedReasoningEffort : mappedReasoningEffort;\n\tconst reasoningRequested = reasoningEffort !== undefined && reasoningEffort !== null;\n\tconst reasoningUnavailable = reasoningEffort === null;\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {\n\t\tpreserveThinking: reasoningRequested,\n\t\tgrammarToolInputProperties,\n\t\tdeferredTools: toolPlacement.deferred,\n\t\tdeferredToolsMode,\n\t\ttoolOptions: {\n\t\t\tsupportsStrictMode: compat.supportsStrictMode,\n\t\t\tsupportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,\n\t\t},\n\t});\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention ?? model.cacheRetention, options?.env);\n\tconst disableImplicitPromptCache = cacheRetention === \"none\" && compat.supportsExplicitPromptCacheMode;\n\tconst params: MutableResponsesPayload = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: cacheRetention === \"none\" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),\n\t\tprompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),\n\t\tprompt_cache_options: disableImplicitPromptCache ? { mode: \"explicit\" } : undefined,\n\t\tstore: false,\n\t};\n\n\tif (options?.maxTokens && compat.supportsMaxOutputTokens) {\n\t\tparams.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tparams.service_tier = options.serviceTier as ResponseCreateParamsStreaming[\"service_tier\"];\n\t}\n\n\tif (toolPlacement.immediate.length > 0) {\n\t\tparams.tools = convertResponsesTools(toolPlacement.immediate, {\n\t\t\tsupportsStrictMode: compat.supportsStrictMode,\n\t\t\tsupportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,\n\t\t});\n\t}\n\n\tif (options?.toolChoice !== undefined) {\n\t\tparams.tool_choice = options.toolChoice;\n\t}\n\n\tif (model.reasoning) {\n\t\tif (reasoningRequested) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: reasoningEffort as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t\t...(options?.reasoningSummary === null ? {} : { summary: options?.reasoningSummary || \"auto\" }),\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else if (!reasoningUnavailable && model.provider !== \"github-copilot\" && thinkingLevelMap?.off !== null) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: (thinkingLevelMap?.off ?? \"none\") as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t};\n\t\t}\n\t\tif (model.provider === \"xai\") params.include = [\"reasoning.encrypted_content\"];\n\t}\n\n\tapplyExtraBodyToResponsesParams(params, options?.extraBody);\n\n\t// Last so custom keys override the named request fields.\n\tif (options?.samplingParams) {\n\t\tObject.assign(params, options.samplingParams);\n\t}\n\n\treturn params;\n}\n\nfunction applyExtraBodyToResponsesParams(\n\tparams: ResponseCreateParamsStreaming,\n\textraBody: Record<string, unknown> | undefined,\n): void {\n\tif (!extraBody) return;\n\tfor (const [key, value] of Object.entries(extraBody)) {\n\t\tif (OPENAI_RESPONSES_RESERVED_BODY_KEYS.has(key)) continue;\n\t\tObject.defineProperty(params, key, { value, writable: true, enumerable: true, configurable: true });\n\t}\n}\n\nfunction getDoneReason(stopReason: AssistantMessage[\"stopReason\"]): \"stop\" | \"length\" | \"toolUse\" {\n\tif (stopReason === \"length\" || stopReason === \"toolUse\") return stopReason;\n\treturn \"stop\";\n}\n\nfunction getWebSocketConstructor(): WebSocketConstructor | null {\n\tconst wsConstructor = (globalThis as { WebSocket?: WebSocketConstructor }).WebSocket;\n\treturn typeof wsConstructor === \"function\" ? wsConstructor : null;\n}\n\nfunction getWebSocketReadyState(socket: WebSocketLike): number | undefined {\n\tconst readyState = (socket as { readyState?: number }).readyState;\n\treturn typeof readyState === \"number\" ? readyState : undefined;\n}\n\nfunction isWebSocketReusable(socket: WebSocketLike): boolean {\n\tconst readyState = getWebSocketReadyState(socket);\n\treturn readyState === undefined || readyState === 1;\n}\n\nfunction closeWebSocketSilently(socket: WebSocketLike, code = 1000, reason = \"done\"): void {\n\ttry {\n\t\tsocket.close(code, reason);\n\t} catch {}\n}\n\n/**\n * Arms the idle-expiry for a cached session socket. A fire while the entry is\n * busy must not strand the entry: the holder may never run the release path\n * that schedules a fresh timer, and a cached-but-forgotten entry would pin its\n * socket for process lifetime. A live busy socket is re-checked on the next\n * tick; a dead one is dropped immediately because nothing can release it.\n */\nexport function scheduleSessionWebSocketExpiry(sessionId: string, entry: CachedWebSocketConnection): void {\n\tif (entry.idleTimer) {\n\t\tclearTimeout(entry.idleTimer);\n\t}\n\tentry.idleTimer = setTimeout(() => {\n\t\tif (entry.busy) {\n\t\t\tif (!isWebSocketReusable(entry.socket)) {\n\t\t\t\tcloseWebSocketSilently(entry.socket, 1000, \"idle_timeout_dead\");\n\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tscheduleSessionWebSocketExpiry(sessionId, entry);\n\t\t\treturn;\n\t\t}\n\t\tcloseWebSocketSilently(entry.socket, 1000, \"idle_timeout\");\n\t\twebsocketSessionCache.delete(sessionId);\n\t}, SESSION_WEBSOCKET_CACHE_TTL_MS);\n\tconst unref = (entry.idleTimer as { unref?: () => void }).unref;\n\tif (unref) unref.call(entry.idleTimer);\n}\n\n/** Number of sessions holding a cached websocket (diagnostics). */\nexport function getOpenAIResponsesWebSocketCacheSize(): number {\n\treturn websocketSessionCache.size;\n}\n\nasync function connectWebSocket(url: string, headers: Headers, signal?: AbortSignal): Promise<WebSocketLike> {\n\tconst WebSocketConstructorValue = getWebSocketConstructor();\n\tif (!WebSocketConstructorValue) {\n\t\tthrow new Error(\"WebSocket transport is not available in this runtime\");\n\t}\n\n\tconst websocketHeaders = headersToRecord(headers);\n\n\treturn new Promise<WebSocketLike>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet socket: WebSocketLike;\n\n\t\tconst cleanup = () => {\n\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst settleReject = (error: Error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t};\n\t\tconst onOpen: WebSocketListener = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(socket);\n\t\t};\n\t\tconst onError: WebSocketListener = (event) => {\n\t\t\tsettleReject(extractWebSocketError(event));\n\t\t};\n\t\tconst onClose: WebSocketListener = (event) => {\n\t\t\tsettleReject(extractWebSocketCloseError(event));\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tcloseWebSocketSilently(socket, 1000, \"aborted\");\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t};\n\n\t\ttry {\n\t\t\tsocket = new WebSocketConstructorValue(url, { headers: websocketHeaders });\n\t\t} catch (error) {\n\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\n\t\tsocket.addEventListener(\"open\", onOpen);\n\t\tsocket.addEventListener(\"error\", onError);\n\t\tsocket.addEventListener(\"close\", onClose);\n\t\tsignal?.addEventListener(\"abort\", onAbort);\n\t});\n}\n\nasync function acquireWebSocket(\n\turl: string,\n\theaders: Headers,\n\tsessionId: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<{ socket: WebSocketLike; release: (options?: { keep?: boolean }) => void }> {\n\tif (!sessionId) {\n\t\tconst socket = await connectWebSocket(url, headers, signal);\n\t\treturn { socket, release: () => closeWebSocketSilently(socket) };\n\t}\n\n\tconst cached = websocketSessionCache.get(sessionId);\n\tif (cached) {\n\t\tif (cached.idleTimer) {\n\t\t\tclearTimeout(cached.idleTimer);\n\t\t\tcached.idleTimer = undefined;\n\t\t}\n\t\tif (!cached.busy && isWebSocketReusable(cached.socket)) {\n\t\t\tcached.busy = true;\n\t\t\treturn {\n\t\t\t\tsocket: cached.socket,\n\t\t\t\trelease: ({ keep } = {}) => {\n\t\t\t\t\tif (!keep || !isWebSocketReusable(cached.socket)) {\n\t\t\t\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcached.busy = false;\n\t\t\t\t\tscheduleSessionWebSocketExpiry(sessionId, cached);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (!cached.busy) {\n\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t}\n\t}\n\n\tconst socket = await connectWebSocket(url, headers, signal);\n\tconst entry: CachedWebSocketConnection = { socket, busy: true };\n\twebsocketSessionCache.set(sessionId, entry);\n\treturn {\n\t\tsocket,\n\t\trelease: ({ keep } = {}) => {\n\t\t\tif (!keep || !isWebSocketReusable(entry.socket)) {\n\t\t\t\tcloseWebSocketSilently(entry.socket);\n\t\t\t\tif (entry.idleTimer) clearTimeout(entry.idleTimer);\n\t\t\t\tif (websocketSessionCache.get(sessionId) === entry) {\n\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.busy = false;\n\t\t\tscheduleSessionWebSocketExpiry(sessionId, entry);\n\t\t},\n\t};\n}\n\nfunction extractWebSocketError(event: unknown): Error {\n\tif (event && typeof event === \"object\" && \"message\" in event) {\n\t\tconst message = (event as { message?: string }).message;\n\t\tif (typeof message === \"string\" && message.length > 0) {\n\t\t\treturn new Error(message);\n\t\t}\n\t}\n\treturn new Error(\"WebSocket error\");\n}\n\nfunction extractWebSocketCloseError(event: unknown): Error {\n\tif (event && typeof event === \"object\") {\n\t\tconst code = \"code\" in event ? (event as { code?: number }).code : undefined;\n\t\tconst reason = \"reason\" in event ? (event as { reason?: string }).reason : undefined;\n\t\tconst codeText = typeof code === \"number\" ? ` ${code}` : \"\";\n\t\tconst reasonText = typeof reason === \"string\" && reason.length > 0 ? ` ${reason}` : \"\";\n\t\treturn new Error(`WebSocket closed${codeText}${reasonText}`.trim());\n\t}\n\treturn new Error(\"WebSocket closed\");\n}\n\nasync function decodeWebSocketData(data: unknown): Promise<string | null> {\n\tif (typeof data === \"string\") return data;\n\tif (data instanceof ArrayBuffer) {\n\t\treturn new TextDecoder().decode(new Uint8Array(data));\n\t}\n\tif (ArrayBuffer.isView(data)) {\n\t\treturn new TextDecoder().decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n\t}\n\tif (data && typeof data === \"object\" && \"arrayBuffer\" in data) {\n\t\tconst arrayBuffer = await (data as { arrayBuffer: () => Promise<ArrayBuffer> }).arrayBuffer();\n\t\treturn new TextDecoder().decode(new Uint8Array(arrayBuffer));\n\t}\n\treturn null;\n}\n\nasync function* parseWebSocket(socket: WebSocketLike, signal?: AbortSignal): AsyncGenerator<ResponseStreamEvent> {\n\tconst queue: ResponseStreamEvent[] = [];\n\tlet pending: (() => void) | null = null;\n\tlet done = false;\n\tlet failed: Error | null = null;\n\tlet sawCompletion = false;\n\n\tconst wake = () => {\n\t\tif (!pending) return;\n\t\tconst resolve = pending;\n\t\tpending = null;\n\t\tresolve();\n\t};\n\tconst onMessage: WebSocketListener = (event) => {\n\t\tvoid (async () => {\n\t\t\tif (!event || typeof event !== \"object\" || !(\"data\" in event)) return;\n\t\t\tconst text = await decodeWebSocketData((event as { data?: unknown }).data);\n\t\t\tif (!text) return;\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(text) as ResponseStreamEvent;\n\t\t\t\tif (parsed.type === \"response.completed\" || parsed.type === \"response.incomplete\") {\n\t\t\t\t\tsawCompletion = true;\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t\tqueue.push(parsed);\n\t\t\t\twake();\n\t\t\t} catch {}\n\t\t})();\n\t};\n\tconst onError: WebSocketListener = (event) => {\n\t\tfailed = extractWebSocketError(event);\n\t\tdone = true;\n\t\twake();\n\t};\n\tconst onClose: WebSocketListener = (event) => {\n\t\tif (!sawCompletion && !failed) {\n\t\t\tfailed = extractWebSocketCloseError(event);\n\t\t}\n\t\tdone = true;\n\t\twake();\n\t};\n\tconst onAbort = () => {\n\t\tfailed = new Error(\"Request was aborted\");\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tsocket.addEventListener(\"message\", onMessage);\n\tsocket.addEventListener(\"error\", onError);\n\tsocket.addEventListener(\"close\", onClose);\n\tsignal?.addEventListener(\"abort\", onAbort);\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) throw new Error(\"Request was aborted\");\n\t\t\tif (queue.length > 0) {\n\t\t\t\tconst event = queue.shift();\n\t\t\t\tif (event) yield event;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (done) break;\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tpending = resolve;\n\t\t\t});\n\t\t}\n\t\tif (failed) throw failed;\n\t\tif (!sawCompletion) throw new Error(\"WebSocket stream closed before response.completed\");\n\t} finally {\n\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\tsocket.removeEventListener(\"error\", onError);\n\t\tsocket.removeEventListener(\"close\", onClose);\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function processWebSocketStream(\n\turl: string,\n\tparams: ResponseCreateParamsStreaming,\n\theaders: Headers,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<\"openai-responses\">,\n\tonStart: () => void,\n\tcacheSessionId: string | undefined,\n\tgrammarToolInputProperties: ReadonlyMap<string, string>,\n\toptions?: OpenAIResponsesOptions,\n): Promise<void> {\n\tconst { socket, release } = await acquireWebSocket(url, headers, cacheSessionId, options?.signal);\n\ttry {\n\t\tsocket.send(JSON.stringify({ type: \"response.create\", ...params }));\n\t\tonStart();\n\t\tawait options?.onResponse?.({ status: 101, headers: {} }, model);\n\t\tstream.push({ type: \"start\", partial: output });\n\t\tawait processResponsesStream(parseWebSocket(socket, options?.signal), output, stream, model, {\n\t\t\tserviceTier: options?.serviceTier,\n\t\t\tgrammarToolInputProperties,\n\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t});\n\t} finally {\n\t\trelease({ keep: false });\n\t}\n}\n\nfunction resolveOpenAIResponsesWebSocketUrl(model: Model<\"openai-responses\">, env?: ProviderEnv): string {\n\tconst baseUrl = isCloudflareProvider(model.provider)\n\t\t? resolveCloudflareBaseUrl(model, env)\n\t\t: model.baseUrl || \"https://api.openai.com/v1\";\n\tconst url = new URL(baseUrl);\n\tif (!url.pathname.endsWith(\"/responses\")) {\n\t\turl.pathname = `${url.pathname.replace(/\\/$/, \"\")}/responses`;\n\t}\n\tif (url.protocol === \"https:\") url.protocol = \"wss:\";\n\telse if (url.protocol === \"http:\") url.protocol = \"ws:\";\n\treturn url.toString();\n}\n\nfunction buildWebSocketHeaders(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tsessionId?: string,\n\tenv?: ProviderEnv,\n): Headers {\n\tconst headers = new Headers(model.headers);\n\tlet suppressDefaultAuthorization = false;\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({ messages: context.messages, hasImages });\n\t\tfor (const [key, value] of Object.entries(copilotHeaders)) {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\tfor (const [key, value] of Object.entries(optionsHeaders || {})) {\n\t\tif (value === null) {\n\t\t\tif (key.toLowerCase() === \"authorization\") suppressDefaultAuthorization = true;\n\t\t\theaders.delete(key);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\tif (!suppressDefaultAuthorization && !headers.has(\"Authorization\")) {\n\t\theaders.set(\"Authorization\", `Bearer ${apiKey}`);\n\t}\n\tif (sessionId) {\n\t\tconst compat = getCompat(model, env);\n\t\tif (compat.sessionAffinityFormat === \"openai\") {\n\t\t\theaders.set(\"session_id\", sessionId);\n\t\t}\n\t\tif (compat.sessionAffinityFormat === \"openai\" || compat.sessionAffinityFormat === \"openai-nosession\") {\n\t\t\theaders.set(\"x-client-request-id\", sessionId);\n\t\t} else if (compat.sessionAffinityFormat === \"openrouter\") {\n\t\t\theaders.set(\"x-session-id\", sessionId);\n\t\t}\n\t}\n\theaders.delete(\"accept\");\n\theaders.delete(\"content-type\");\n\theaders.delete(\"OpenAI-Beta\");\n\theaders.delete(\"openai-beta\");\n\theaders.set(\"OpenAI-Beta\", OPENAI_BETA_RESPONSES_WEBSOCKETS);\n\treturn headers;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | \"fast\" | undefined,\n): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\tcase \"fast\":\n\t\t\treturn model.id === \"gpt-5.5\" ? 2.5 : 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | \"fast\" | undefined,\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n) {\n\tconst multiplier = getServiceTierCostMultiplier(model, serviceTier);\n\tif (multiplier === 1) return;\n\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n"]}
1
+ {"version":3,"file":"openai-responses.js","sourceRoot":"","sources":["../../src/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CAAC;QACZ,KAAK,UAAU,CAAC;QAChB,KAAK,MAAM;YACV,OAAO,KAAK,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACzC;YACC,OAAO,CAAC,CAAC;IACX,CAAC;AACF,CAAC;AAED,SAAS,uBAAuB,CAC/B,KAAY,EACZ,WAA+E,EAC/E,KAA4C;IAE5C,MAAM,UAAU,GAAG,4BAA4B,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IACpE,IAAI,UAAU,KAAK,CAAC;QAAE,OAAO;IAE7B,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,UAAU,CAAC;IAC/B,KAAK,CAAC,IAAI,CAAC,MAAM,IAAI,UAAU,CAAC;IAChC,KAAK,CAAC,IAAI,CAAC,SAAS,IAAI,UAAU,CAAC;IACnC,KAAK,CAAC,IAAI,CAAC,UAAU,IAAI,UAAU,CAAC;IACpC,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC;AACxG,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport type { ResponseCreateParamsStreaming, ResponseStreamEvent } from \"openai/resources/responses/responses.js\";\nimport { clampThinkingLevel, inferOpenAIThinkingLevelMap, supportsMax, supportsXhigh } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tOpenAIResponsesCompat,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.ts\";\nimport { splitDeferredTools } from \"../utils/deferred-tools.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { createGrammarToolInputProperties } from \"./constrained-sampling.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { resolveOpenAIClientAuth } from \"./openai-client-auth.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions, clampMaxForOpenAI, OPENAI_RESPONSES_RESERVED_BODY_KEYS } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\nconst OPENAI_BETA_RESPONSES_WEBSOCKETS = \"responses_websockets=2026-02-06\";\nconst OPENAI_WEB_SEARCH_SOURCES_INCLUDE = \"web_search_call.action.sources\";\nconst SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1000;\n// OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265\nconst OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;\n\ntype WebSocketEventType = \"open\" | \"message\" | \"error\" | \"close\";\ntype WebSocketListener = (event: unknown) => void;\n\ninterface WebSocketLike {\n\tclose(code?: number, reason?: string): void;\n\tsend(data: string): void;\n\taddEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n\tremoveEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n}\n\nexport interface CachedWebSocketConnection {\n\tsocket: WebSocketLike;\n\tbusy: boolean;\n\tidleTimer?: ReturnType<typeof setTimeout>;\n}\n\ntype WebSocketConstructor = new (\n\turl: string,\n\tprotocols?: string | string[] | { headers?: Record<string, string> },\n) => WebSocketLike;\n\ntype MutableResponsesPayload = ResponseCreateParamsStreaming & {\n\tprompt_cache_options?: { mode?: \"explicit\" | \"implicit\"; ttl?: \"30m\" };\n};\n\nconst websocketSessionCache = new Map<string, CachedWebSocketConnection>();\n\nfunction detectSessionAffinityFormat(model: Pick<Model<\"openai-responses\">, \"provider\" | \"baseUrl\">) {\n\treturn model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\") ? \"openrouter\" : \"openai\";\n}\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCompat(model: Model<\"openai-responses\">, env?: ProviderEnv): Required<OpenAIResponsesCompat> {\n\tconst isNativeEndpoint = isOpenAIResponsesNativeEndpoint(model, env);\n\treturn {\n\t\tsupportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true,\n\t\tsessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model),\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n\t\tsupportsWebSocket: model.compat?.supportsWebSocket ?? isNativeEndpoint,\n\t\tsupportsRemoteCompactionV2: model.compat?.supportsRemoteCompactionV2 ?? isNativeEndpoint,\n\t\tsupportsWebSearchPreview: model.compat?.supportsWebSearchPreview ?? isNativeEndpoint,\n\t\tsupportsImageGeneration: model.compat?.supportsImageGeneration ?? isNativeEndpoint,\n\t\tsupportsStrictMode: model.compat?.supportsStrictMode ?? false,\n\t\tsupportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false,\n\t\tsupportsAdditionalTools: model.compat?.supportsAdditionalTools ?? false,\n\t\tsupportsToolSearch: model.compat?.supportsToolSearch ?? false,\n\t\tsupportsExplicitPromptCacheMode: model.compat?.supportsExplicitPromptCacheMode ?? false,\n\t\tsupportsMaxOutputTokens: model.compat?.supportsMaxOutputTokens ?? true,\n\t};\n}\n\nfunction isOpenAIResponsesNativeEndpoint(model: Model<\"openai-responses\">, env?: ProviderEnv): boolean {\n\tconst baseUrl = isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model, env) : model.baseUrl;\n\ttry {\n\t\treturn new URL(baseUrl || \"https://api.openai.com/v1\").hostname === \"api.openai.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getPromptCacheRetention(\n\tcompat: Required<OpenAIResponsesCompat>,\n\tcacheRetention: CacheRetention,\n): \"24h\" | undefined {\n\treturn cacheRetention === \"long\" && compat.supportsLongCacheRetention && !compat.supportsExplicitPromptCacheMode\n\t\t? \"24h\"\n\t\t: undefined;\n}\n\nfunction getPromptCacheOptions(\n\tcompat: Required<OpenAIResponsesCompat>,\n\tcacheRetention: CacheRetention,\n): { mode?: \"explicit\"; ttl?: \"30m\" } | undefined {\n\tif (!compat.supportsExplicitPromptCacheMode) return undefined;\n\tif (cacheRetention === \"none\") return { mode: \"explicit\" };\n\tif (cacheRetention === \"long\" && compat.supportsLongCacheRetention) return { ttl: \"30m\" };\n\treturn undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isOpenAiWebSearchPreviewTool(value: unknown): boolean {\n\treturn isRecord(value) && (value.type === \"web_search_preview\" || value.type === \"web_search_preview_2025_03_11\");\n}\n\nfunction sanitizeUnsupportedNativeTools(\n\tparams: MutableResponsesPayload,\n\tcompat: Required<OpenAIResponsesCompat>,\n): MutableResponsesPayload {\n\tif (compat.supportsWebSearchPreview) {\n\t\treturn params;\n\t}\n\n\tconst payload = params as MutableResponsesPayload;\n\tlet sanitized: MutableResponsesPayload | undefined;\n\tconst nextPayload = (): MutableResponsesPayload => {\n\t\tsanitized ??= { ...payload };\n\t\treturn sanitized;\n\t};\n\n\tif (Array.isArray(payload.tools)) {\n\t\tconst tools = payload.tools.filter((tool) => !isOpenAiWebSearchPreviewTool(tool));\n\t\tif (tools.length !== payload.tools.length) {\n\t\t\tconst next = nextPayload();\n\t\t\tif (tools.length > 0) {\n\t\t\t\tnext.tools = tools;\n\t\t\t} else {\n\t\t\t\tdelete next.tools;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Array.isArray(payload.include)) {\n\t\tconst include = payload.include.filter((value) => value !== OPENAI_WEB_SEARCH_SOURCES_INCLUDE);\n\t\tif (include.length !== payload.include.length) {\n\t\t\tconst next = nextPayload();\n\t\t\tif (include.length > 0) {\n\t\t\t\tnext.include = include;\n\t\t\t} else {\n\t\t\t\tdelete next.include;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (isOpenAiWebSearchPreviewTool(payload.tool_choice)) {\n\t\tdelete nextPayload().tool_choice;\n\t}\n\n\treturn sanitized ? (sanitized as ResponseCreateParamsStreaming) : params;\n}\n\nfunction formatOpenAIResponsesError(error: unknown): string {\n\treturn formatProviderError(normalizeProviderError(error), \"OpenAI API error\");\n}\n\n// OpenAI Responses-specific options\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"] | \"fast\";\n\ttoolChoice?: ResponseCreateParamsStreaming[\"tool_choice\"];\n}\n\n/**\n * Generate function for OpenAI Responses API\n */\nexport const stream: StreamFunction<\"openai-responses\", OpenAIResponsesOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api 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: \"pending\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst clientAuth = resolveOpenAIClientAuth(model.provider, options?.apiKey, options?.headers);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst compat = getCompat(model, options?.env);\n\t\t\tconst grammarToolInputProperties = createGrammarToolInputProperties(\n\t\t\t\tcontext.tools,\n\t\t\t\tcompat.supportsOpenAIGrammarTools,\n\t\t\t);\n\t\t\tconst client = createClient(\n\t\t\t\tmodel,\n\t\t\t\tcontext,\n\t\t\t\tclientAuth.apiKey,\n\t\t\t\tclientAuth.headers,\n\t\t\t\toptions?.fetch,\n\t\t\t\tcacheSessionId,\n\t\t\t\toptions?.env,\n\t\t\t);\n\t\t\tlet params = buildParams(model, context, options, compat, grammarToolInputProperties);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as MutableResponsesPayload;\n\t\t\t}\n\n\t\t\tparams = sanitizeUnsupportedNativeTools(params, compat);\n\t\t\tconst transport = options?.transport ?? \"sse\";\n\t\t\tif (transport !== \"sse\" && compat.supportsWebSocket) {\n\t\t\t\tlet websocketStarted = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait processWebSocketStream(\n\t\t\t\t\t\tresolveOpenAIResponsesWebSocketUrl(model, options?.env),\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tbuildWebSocketHeaders(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\tclientAuth.apiKey,\n\t\t\t\t\t\t\tclientAuth.headers,\n\t\t\t\t\t\t\tcacheSessionId,\n\t\t\t\t\t\t\toptions?.env,\n\t\t\t\t\t\t),\n\t\t\t\t\t\toutput,\n\t\t\t\t\t\tstream,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\twebsocketStarted = true;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcacheSessionId,\n\t\t\t\t\t\tgrammarToolInputProperties,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t}\n\n\t\t\t\t\tstream.push({ type: \"done\", reason: getDoneReason(output.stopReason), message: output });\n\t\t\t\t\tstream.end();\n\t\t\t\t\treturn;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (transport === \"websocket\" || websocketStarted) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: 0,\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await retryProviderRequest(\n\t\t\t\t() => client.responses.create(params, requestOptions).withResponse(),\n\t\t\t\t{\n\t\t\t\t\tmaxRetries: options?.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t},\n\t\t\t);\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\t\t\t\tserviceTier: options?.serviceTier,\n\t\t\t\tgrammarToolInputProperties,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\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 === \"pending\") {\n\t\t\t\tthrow new Error(\"OpenAI Responses stream ended without a stop reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// Streaming scratch buffers are only used during parsing; never persist them.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t\tdelete (block as { customInput?: unknown }).customInput;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatOpenAIResponsesError(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 streamSimple: StreamFunction<\"openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tresolveOpenAIClientAuth(model.provider, options?.apiKey, options?.headers);\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, options?.apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t\tserviceTier: options?.serviceTier,\n\t} satisfies OpenAIResponsesOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort =\n\t\tclampedReasoning === \"off\"\n\t\t\t? undefined\n\t\t\t: clampedReasoning === \"max\" && supportsMax(model)\n\t\t\t\t? \"max\"\n\t\t\t\t: clampMaxForOpenAI(clampedReasoning, supportsXhigh(model));\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAIResponsesOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n\tsessionId?: string,\n\tenv?: ProviderEnv,\n) {\n\tconst compat = getCompat(model, env);\n\tconst headers: ProviderHeaders = { \"User-Agent\": getPiUserAgent(), ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId) {\n\t\tif (compat.sessionAffinityFormat === \"openrouter\") {\n\t\t\theaders[\"x-session-id\"] = sessionId;\n\t\t} else {\n\t\t\tif (compat.sessionAffinityFormat === \"openai\") {\n\t\t\t\theaders.session_id = sessionId;\n\t\t\t}\n\t\t\theaders[\"x-client-request-id\"] = sessionId;\n\t\t}\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model, env) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tfetch,\n\t\tdefaultHeaders: headers,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat> = getCompat(model, options?.env),\n\tgrammarToolInputProperties: ReadonlyMap<string, string> = createGrammarToolInputProperties(\n\t\tcontext.tools,\n\t\tcompat.supportsOpenAIGrammarTools,\n\t),\n) {\n\tconst deferredToolsMode = compat.supportsAdditionalTools\n\t\t? \"additional-tools\"\n\t\t: compat.supportsToolSearch\n\t\t\t? \"tool-search\"\n\t\t\t: undefined;\n\tconst toolPlacement = splitDeferredTools(context, deferredToolsMode !== undefined);\n\tconst requestedReasoningEffort = options?.reasoningEffort ?? (options?.reasoningSummary ? \"medium\" : undefined);\n\tconst thinkingLevelMap = inferOpenAIThinkingLevelMap(model);\n\tconst mappedReasoningEffort =\n\t\trequestedReasoningEffort === undefined ? undefined : thinkingLevelMap?.[requestedReasoningEffort];\n\tconst reasoningEffort = mappedReasoningEffort === undefined ? requestedReasoningEffort : mappedReasoningEffort;\n\tconst reasoningRequested = reasoningEffort !== undefined && reasoningEffort !== null;\n\tconst reasoningUnavailable = reasoningEffort === null;\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {\n\t\tpreserveThinking: reasoningRequested,\n\t\tgrammarToolInputProperties,\n\t\tdeferredTools: toolPlacement.deferred,\n\t\tdeferredToolsMode,\n\t\ttoolOptions: {\n\t\t\tsupportsStrictMode: compat.supportsStrictMode,\n\t\t\tsupportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,\n\t\t},\n\t});\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention ?? model.cacheRetention, options?.env);\n\tconst params: MutableResponsesPayload = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: cacheRetention === \"none\" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),\n\t\tprompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),\n\t\tprompt_cache_options: getPromptCacheOptions(compat, cacheRetention),\n\t\tstore: false,\n\t};\n\n\tif (options?.maxTokens && compat.supportsMaxOutputTokens) {\n\t\tparams.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tparams.service_tier = options.serviceTier as ResponseCreateParamsStreaming[\"service_tier\"];\n\t}\n\n\tif (toolPlacement.immediate.length > 0) {\n\t\tparams.tools = convertResponsesTools(toolPlacement.immediate, {\n\t\t\tsupportsStrictMode: compat.supportsStrictMode,\n\t\t\tsupportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,\n\t\t});\n\t}\n\n\tif (options?.toolChoice !== undefined) {\n\t\tparams.tool_choice = options.toolChoice;\n\t}\n\n\tif (model.reasoning) {\n\t\tif (reasoningRequested) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: reasoningEffort as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t\t...(options?.reasoningSummary === null ? {} : { summary: options?.reasoningSummary || \"auto\" }),\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else if (!reasoningUnavailable && model.provider !== \"github-copilot\" && thinkingLevelMap?.off !== null) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: (thinkingLevelMap?.off ?? \"none\") as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t};\n\t\t}\n\t\tif (model.provider === \"xai\") params.include = [\"reasoning.encrypted_content\"];\n\t}\n\n\tapplyExtraBodyToResponsesParams(params, options?.extraBody);\n\n\t// Last so custom keys override the named request fields.\n\tif (options?.samplingParams) {\n\t\tObject.assign(params, options.samplingParams);\n\t}\n\n\treturn params;\n}\n\nfunction applyExtraBodyToResponsesParams(\n\tparams: ResponseCreateParamsStreaming,\n\textraBody: Record<string, unknown> | undefined,\n): void {\n\tif (!extraBody) return;\n\tfor (const [key, value] of Object.entries(extraBody)) {\n\t\tif (OPENAI_RESPONSES_RESERVED_BODY_KEYS.has(key)) continue;\n\t\tObject.defineProperty(params, key, { value, writable: true, enumerable: true, configurable: true });\n\t}\n}\n\nfunction getDoneReason(stopReason: AssistantMessage[\"stopReason\"]): \"stop\" | \"length\" | \"toolUse\" {\n\tif (stopReason === \"length\" || stopReason === \"toolUse\") return stopReason;\n\treturn \"stop\";\n}\n\nfunction getWebSocketConstructor(): WebSocketConstructor | null {\n\tconst wsConstructor = (globalThis as { WebSocket?: WebSocketConstructor }).WebSocket;\n\treturn typeof wsConstructor === \"function\" ? wsConstructor : null;\n}\n\nfunction getWebSocketReadyState(socket: WebSocketLike): number | undefined {\n\tconst readyState = (socket as { readyState?: number }).readyState;\n\treturn typeof readyState === \"number\" ? readyState : undefined;\n}\n\nfunction isWebSocketReusable(socket: WebSocketLike): boolean {\n\tconst readyState = getWebSocketReadyState(socket);\n\treturn readyState === undefined || readyState === 1;\n}\n\nfunction closeWebSocketSilently(socket: WebSocketLike, code = 1000, reason = \"done\"): void {\n\ttry {\n\t\tsocket.close(code, reason);\n\t} catch {}\n}\n\n/**\n * Arms the idle-expiry for a cached session socket. A fire while the entry is\n * busy must not strand the entry: the holder may never run the release path\n * that schedules a fresh timer, and a cached-but-forgotten entry would pin its\n * socket for process lifetime. A live busy socket is re-checked on the next\n * tick; a dead one is dropped immediately because nothing can release it.\n */\nexport function scheduleSessionWebSocketExpiry(sessionId: string, entry: CachedWebSocketConnection): void {\n\tif (entry.idleTimer) {\n\t\tclearTimeout(entry.idleTimer);\n\t}\n\tentry.idleTimer = setTimeout(() => {\n\t\tif (entry.busy) {\n\t\t\tif (!isWebSocketReusable(entry.socket)) {\n\t\t\t\tcloseWebSocketSilently(entry.socket, 1000, \"idle_timeout_dead\");\n\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tscheduleSessionWebSocketExpiry(sessionId, entry);\n\t\t\treturn;\n\t\t}\n\t\tcloseWebSocketSilently(entry.socket, 1000, \"idle_timeout\");\n\t\twebsocketSessionCache.delete(sessionId);\n\t}, SESSION_WEBSOCKET_CACHE_TTL_MS);\n\tconst unref = (entry.idleTimer as { unref?: () => void }).unref;\n\tif (unref) unref.call(entry.idleTimer);\n}\n\n/** Number of sessions holding a cached websocket (diagnostics). */\nexport function getOpenAIResponsesWebSocketCacheSize(): number {\n\treturn websocketSessionCache.size;\n}\n\nasync function connectWebSocket(url: string, headers: Headers, signal?: AbortSignal): Promise<WebSocketLike> {\n\tconst WebSocketConstructorValue = getWebSocketConstructor();\n\tif (!WebSocketConstructorValue) {\n\t\tthrow new Error(\"WebSocket transport is not available in this runtime\");\n\t}\n\n\tconst websocketHeaders = headersToRecord(headers);\n\n\treturn new Promise<WebSocketLike>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet socket: WebSocketLike;\n\n\t\tconst cleanup = () => {\n\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst settleReject = (error: Error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t};\n\t\tconst onOpen: WebSocketListener = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(socket);\n\t\t};\n\t\tconst onError: WebSocketListener = (event) => {\n\t\t\tsettleReject(extractWebSocketError(event));\n\t\t};\n\t\tconst onClose: WebSocketListener = (event) => {\n\t\t\tsettleReject(extractWebSocketCloseError(event));\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tcloseWebSocketSilently(socket, 1000, \"aborted\");\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t};\n\n\t\ttry {\n\t\t\tsocket = new WebSocketConstructorValue(url, { headers: websocketHeaders });\n\t\t} catch (error) {\n\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\n\t\tsocket.addEventListener(\"open\", onOpen);\n\t\tsocket.addEventListener(\"error\", onError);\n\t\tsocket.addEventListener(\"close\", onClose);\n\t\tsignal?.addEventListener(\"abort\", onAbort);\n\t});\n}\n\nasync function acquireWebSocket(\n\turl: string,\n\theaders: Headers,\n\tsessionId: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<{ socket: WebSocketLike; release: (options?: { keep?: boolean }) => void }> {\n\tif (!sessionId) {\n\t\tconst socket = await connectWebSocket(url, headers, signal);\n\t\treturn { socket, release: () => closeWebSocketSilently(socket) };\n\t}\n\n\tconst cached = websocketSessionCache.get(sessionId);\n\tif (cached) {\n\t\tif (cached.idleTimer) {\n\t\t\tclearTimeout(cached.idleTimer);\n\t\t\tcached.idleTimer = undefined;\n\t\t}\n\t\tif (!cached.busy && isWebSocketReusable(cached.socket)) {\n\t\t\tcached.busy = true;\n\t\t\treturn {\n\t\t\t\tsocket: cached.socket,\n\t\t\t\trelease: ({ keep } = {}) => {\n\t\t\t\t\tif (!keep || !isWebSocketReusable(cached.socket)) {\n\t\t\t\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcached.busy = false;\n\t\t\t\t\tscheduleSessionWebSocketExpiry(sessionId, cached);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (!cached.busy) {\n\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t}\n\t}\n\n\tconst socket = await connectWebSocket(url, headers, signal);\n\tconst entry: CachedWebSocketConnection = { socket, busy: true };\n\twebsocketSessionCache.set(sessionId, entry);\n\treturn {\n\t\tsocket,\n\t\trelease: ({ keep } = {}) => {\n\t\t\tif (!keep || !isWebSocketReusable(entry.socket)) {\n\t\t\t\tcloseWebSocketSilently(entry.socket);\n\t\t\t\tif (entry.idleTimer) clearTimeout(entry.idleTimer);\n\t\t\t\tif (websocketSessionCache.get(sessionId) === entry) {\n\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.busy = false;\n\t\t\tscheduleSessionWebSocketExpiry(sessionId, entry);\n\t\t},\n\t};\n}\n\nfunction extractWebSocketError(event: unknown): Error {\n\tif (event && typeof event === \"object\" && \"message\" in event) {\n\t\tconst message = (event as { message?: string }).message;\n\t\tif (typeof message === \"string\" && message.length > 0) {\n\t\t\treturn new Error(message);\n\t\t}\n\t}\n\treturn new Error(\"WebSocket error\");\n}\n\nfunction extractWebSocketCloseError(event: unknown): Error {\n\tif (event && typeof event === \"object\") {\n\t\tconst code = \"code\" in event ? (event as { code?: number }).code : undefined;\n\t\tconst reason = \"reason\" in event ? (event as { reason?: string }).reason : undefined;\n\t\tconst codeText = typeof code === \"number\" ? ` ${code}` : \"\";\n\t\tconst reasonText = typeof reason === \"string\" && reason.length > 0 ? ` ${reason}` : \"\";\n\t\treturn new Error(`WebSocket closed${codeText}${reasonText}`.trim());\n\t}\n\treturn new Error(\"WebSocket closed\");\n}\n\nasync function decodeWebSocketData(data: unknown): Promise<string | null> {\n\tif (typeof data === \"string\") return data;\n\tif (data instanceof ArrayBuffer) {\n\t\treturn new TextDecoder().decode(new Uint8Array(data));\n\t}\n\tif (ArrayBuffer.isView(data)) {\n\t\treturn new TextDecoder().decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n\t}\n\tif (data && typeof data === \"object\" && \"arrayBuffer\" in data) {\n\t\tconst arrayBuffer = await (data as { arrayBuffer: () => Promise<ArrayBuffer> }).arrayBuffer();\n\t\treturn new TextDecoder().decode(new Uint8Array(arrayBuffer));\n\t}\n\treturn null;\n}\n\nasync function* parseWebSocket(socket: WebSocketLike, signal?: AbortSignal): AsyncGenerator<ResponseStreamEvent> {\n\tconst queue: ResponseStreamEvent[] = [];\n\tlet pending: (() => void) | null = null;\n\tlet done = false;\n\tlet failed: Error | null = null;\n\tlet sawCompletion = false;\n\n\tconst wake = () => {\n\t\tif (!pending) return;\n\t\tconst resolve = pending;\n\t\tpending = null;\n\t\tresolve();\n\t};\n\tconst onMessage: WebSocketListener = (event) => {\n\t\tvoid (async () => {\n\t\t\tif (!event || typeof event !== \"object\" || !(\"data\" in event)) return;\n\t\t\tconst text = await decodeWebSocketData((event as { data?: unknown }).data);\n\t\t\tif (!text) return;\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(text) as ResponseStreamEvent;\n\t\t\t\tif (parsed.type === \"response.completed\" || parsed.type === \"response.incomplete\") {\n\t\t\t\t\tsawCompletion = true;\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t\tqueue.push(parsed);\n\t\t\t\twake();\n\t\t\t} catch {}\n\t\t})();\n\t};\n\tconst onError: WebSocketListener = (event) => {\n\t\tfailed = extractWebSocketError(event);\n\t\tdone = true;\n\t\twake();\n\t};\n\tconst onClose: WebSocketListener = (event) => {\n\t\tif (!sawCompletion && !failed) {\n\t\t\tfailed = extractWebSocketCloseError(event);\n\t\t}\n\t\tdone = true;\n\t\twake();\n\t};\n\tconst onAbort = () => {\n\t\tfailed = new Error(\"Request was aborted\");\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tsocket.addEventListener(\"message\", onMessage);\n\tsocket.addEventListener(\"error\", onError);\n\tsocket.addEventListener(\"close\", onClose);\n\tsignal?.addEventListener(\"abort\", onAbort);\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) throw new Error(\"Request was aborted\");\n\t\t\tif (queue.length > 0) {\n\t\t\t\tconst event = queue.shift();\n\t\t\t\tif (event) yield event;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (done) break;\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tpending = resolve;\n\t\t\t});\n\t\t}\n\t\tif (failed) throw failed;\n\t\tif (!sawCompletion) throw new Error(\"WebSocket stream closed before response.completed\");\n\t} finally {\n\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\tsocket.removeEventListener(\"error\", onError);\n\t\tsocket.removeEventListener(\"close\", onClose);\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function processWebSocketStream(\n\turl: string,\n\tparams: ResponseCreateParamsStreaming,\n\theaders: Headers,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<\"openai-responses\">,\n\tonStart: () => void,\n\tcacheSessionId: string | undefined,\n\tgrammarToolInputProperties: ReadonlyMap<string, string>,\n\toptions?: OpenAIResponsesOptions,\n): Promise<void> {\n\tconst { socket, release } = await acquireWebSocket(url, headers, cacheSessionId, options?.signal);\n\ttry {\n\t\tsocket.send(JSON.stringify({ type: \"response.create\", ...params }));\n\t\tonStart();\n\t\tawait options?.onResponse?.({ status: 101, headers: {} }, model);\n\t\tstream.push({ type: \"start\", partial: output });\n\t\tawait processResponsesStream(parseWebSocket(socket, options?.signal), output, stream, model, {\n\t\t\tserviceTier: options?.serviceTier,\n\t\t\tgrammarToolInputProperties,\n\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t});\n\t} finally {\n\t\trelease({ keep: false });\n\t}\n}\n\nfunction resolveOpenAIResponsesWebSocketUrl(model: Model<\"openai-responses\">, env?: ProviderEnv): string {\n\tconst baseUrl = isCloudflareProvider(model.provider)\n\t\t? resolveCloudflareBaseUrl(model, env)\n\t\t: model.baseUrl || \"https://api.openai.com/v1\";\n\tconst url = new URL(baseUrl);\n\tif (!url.pathname.endsWith(\"/responses\")) {\n\t\turl.pathname = `${url.pathname.replace(/\\/$/, \"\")}/responses`;\n\t}\n\tif (url.protocol === \"https:\") url.protocol = \"wss:\";\n\telse if (url.protocol === \"http:\") url.protocol = \"ws:\";\n\treturn url.toString();\n}\n\nfunction buildWebSocketHeaders(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tsessionId?: string,\n\tenv?: ProviderEnv,\n): Headers {\n\tconst headers = new Headers(model.headers);\n\tlet suppressDefaultAuthorization = false;\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({ messages: context.messages, hasImages });\n\t\tfor (const [key, value] of Object.entries(copilotHeaders)) {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\tfor (const [key, value] of Object.entries(optionsHeaders || {})) {\n\t\tif (value === null) {\n\t\t\tif (key.toLowerCase() === \"authorization\") suppressDefaultAuthorization = true;\n\t\t\theaders.delete(key);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\tif (!suppressDefaultAuthorization && !headers.has(\"Authorization\")) {\n\t\theaders.set(\"Authorization\", `Bearer ${apiKey}`);\n\t}\n\tif (sessionId) {\n\t\tconst compat = getCompat(model, env);\n\t\tif (compat.sessionAffinityFormat === \"openai\") {\n\t\t\theaders.set(\"session_id\", sessionId);\n\t\t}\n\t\tif (compat.sessionAffinityFormat === \"openai\" || compat.sessionAffinityFormat === \"openai-nosession\") {\n\t\t\theaders.set(\"x-client-request-id\", sessionId);\n\t\t} else if (compat.sessionAffinityFormat === \"openrouter\") {\n\t\t\theaders.set(\"x-session-id\", sessionId);\n\t\t}\n\t}\n\theaders.delete(\"accept\");\n\theaders.delete(\"content-type\");\n\theaders.delete(\"OpenAI-Beta\");\n\theaders.delete(\"openai-beta\");\n\theaders.set(\"OpenAI-Beta\", OPENAI_BETA_RESPONSES_WEBSOCKETS);\n\treturn headers;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | \"fast\" | undefined,\n): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\tcase \"fast\":\n\t\t\treturn model.id === \"gpt-5.5\" ? 2.5 : 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | \"fast\" | undefined,\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n) {\n\tconst multiplier = getServiceTierCostMultiplier(model, serviceTier);\n\tif (multiplier === 1) return;\n\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n"]}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Context ceilings Cursor itself reported, keyed by model id.
3
+ *
4
+ * `GetUsableModels` carries no window, so `CURSOR_MODEL_CAPABILITIES` is a
5
+ * committed guess at what each family accepts. The server states the truth on
6
+ * every conversation checkpoint (`tokenDetails.maxTokens`), so once a model has
7
+ * been observed, that value outranks the catalog for every later request.
8
+ *
9
+ * This module stays browser-safe: `providers/cursor.ts` and
10
+ * `cursor/store-migration.ts` materialize catalog windows and are bundled for
11
+ * the browser. Node processes install file persistence through
12
+ * `installCursorContextLimitPersistence` - see `utils/cursor-context-limit.ts`.
13
+ */
14
+ export type CursorContextLimitPersistence = {
15
+ /** Limits observed by earlier processes. Called at most once per install. */
16
+ readonly load: () => ReadonlyMap<string, number>;
17
+ /** Called only when a recorded limit actually changed the store. */
18
+ readonly save: (limits: ReadonlyMap<string, number>) => void;
19
+ };
20
+ /** Installs the process-wide persistence port. Idempotent per port identity. */
21
+ export declare function installCursorContextLimitPersistence(port: CursorContextLimitPersistence): void;
22
+ /**
23
+ * Records the server-reported ceiling for `modelId`. The first checkpoint of a
24
+ * conversation reports 0, so non-positive and non-finite values are ignored.
25
+ */
26
+ export declare function recordCursorContextLimit(modelId: string, maxTokens: number | undefined): void;
27
+ export declare function getCursorContextLimit(modelId: string): number | undefined;
28
+ /** The window to trust for `modelId`: what the server reported, else the catalog. */
29
+ export declare function resolveCursorContextWindow(modelId: string, catalogWindow: number): number;
30
+ /** Drops in-memory state so the next read re-hydrates from the installed port. */
31
+ export declare function resetCursorContextLimitStoreForTest(): void;
32
+ //# sourceMappingURL=context-limit-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-limit-store.d.ts","sourceRoot":"","sources":["../../src/cursor/context-limit-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,MAAM,6BAA6B,GAAG;IAC3C,6EAA6E;IAC7E,QAAQ,CAAC,IAAI,EAAE,MAAM,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjD,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,IAAI,CAAC;CAC7D,CAAC;AAMF,gFAAgF;AAChF,wBAAgB,oCAAoC,CAAC,IAAI,EAAE,6BAA6B,GAAG,IAAI,CAI9F;AAYD;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAM7F;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGzE;AAED,qFAAqF;AACrF,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,MAAM,CAEzF;AAED,kFAAkF;AAClF,wBAAgB,mCAAmC,IAAI,IAAI,CAG1D"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Context ceilings Cursor itself reported, keyed by model id.
3
+ *
4
+ * `GetUsableModels` carries no window, so `CURSOR_MODEL_CAPABILITIES` is a
5
+ * committed guess at what each family accepts. The server states the truth on
6
+ * every conversation checkpoint (`tokenDetails.maxTokens`), so once a model has
7
+ * been observed, that value outranks the catalog for every later request.
8
+ *
9
+ * This module stays browser-safe: `providers/cursor.ts` and
10
+ * `cursor/store-migration.ts` materialize catalog windows and are bundled for
11
+ * the browser. Node processes install file persistence through
12
+ * `installCursorContextLimitPersistence` - see `utils/cursor-context-limit.ts`.
13
+ */
14
+ const observedLimits = new Map();
15
+ let persistence;
16
+ let hydrated = false;
17
+ /** Installs the process-wide persistence port. Idempotent per port identity. */
18
+ export function installCursorContextLimitPersistence(port) {
19
+ if (persistence === port)
20
+ return;
21
+ persistence = port;
22
+ hydrated = false;
23
+ }
24
+ function hydrate() {
25
+ if (hydrated)
26
+ return;
27
+ // Set before loading: a load that observes nothing must not retry per read.
28
+ hydrated = true;
29
+ if (!persistence)
30
+ return;
31
+ for (const [modelId, maxTokens] of persistence.load()) {
32
+ if (!observedLimits.has(modelId))
33
+ observedLimits.set(modelId, maxTokens);
34
+ }
35
+ }
36
+ /**
37
+ * Records the server-reported ceiling for `modelId`. The first checkpoint of a
38
+ * conversation reports 0, so non-positive and non-finite values are ignored.
39
+ */
40
+ export function recordCursorContextLimit(modelId, maxTokens) {
41
+ if (maxTokens === undefined || !Number.isFinite(maxTokens) || maxTokens <= 0)
42
+ return;
43
+ hydrate();
44
+ if (observedLimits.get(modelId) === maxTokens)
45
+ return;
46
+ observedLimits.set(modelId, maxTokens);
47
+ persistence?.save(observedLimits);
48
+ }
49
+ export function getCursorContextLimit(modelId) {
50
+ hydrate();
51
+ return observedLimits.get(modelId);
52
+ }
53
+ /** The window to trust for `modelId`: what the server reported, else the catalog. */
54
+ export function resolveCursorContextWindow(modelId, catalogWindow) {
55
+ return getCursorContextLimit(modelId) ?? catalogWindow;
56
+ }
57
+ /** Drops in-memory state so the next read re-hydrates from the installed port. */
58
+ export function resetCursorContextLimitStoreForTest() {
59
+ observedLimits.clear();
60
+ hydrated = false;
61
+ }
62
+ //# sourceMappingURL=context-limit-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-limit-store.js","sourceRoot":"","sources":["../../src/cursor/context-lim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M,UAAU,0BAA0B,CAAC,OAAe,EAAE,aAAqB;IAChF,OAAO,qBAAqB,CAAC,OAAO,CAAC,IAAI,aAAa,CAAC;AACxD,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,mCAAmC;IAClD,cAAc,CAAC,KAAK,EAAE,CAAC;IACvB,QAAQ,GAAG,KAAK,CAAC;AAClB,CAAC","sourcesContent":["/**\n * Context ceilings Cursor itself reported, keyed by model id.\n *\n * `GetUsableModels` carries no window, so `CURSOR_MODEL_CAPABILITIES` is a\n * committed guess at what each family accepts. The server states the truth on\n * every conversation checkpoint (`tokenDetails.maxTokens`), so once a model has\n * been observed, that value outranks the catalog for every later request.\n *\n * This module stays browser-safe: `providers/cursor.ts` and\n * `cursor/store-migration.ts` materialize catalog windows and are bundled for\n * the browser. Node processes install file persistence through\n * `installCursorContextLimitPersistence` - see `utils/cursor-context-limit.ts`.\n */\n\nexport type CursorContextLimitPersistence = {\n\t/** Limits observed by earlier processes. Called at most once per install. */\n\treadonly load: () => ReadonlyMap<string, number>;\n\t/** Called only when a recorded limit actually changed the store. */\n\treadonly save: (limits: ReadonlyMap<string, number>) => void;\n};\n\nconst observedLimits = new Map<string, number>();\nlet persistence: CursorContextLimitPersistence | undefined;\nlet hydrated = false;\n\n/** Installs the process-wide persistence port. Idempotent per port identity. */\nexport function installCursorContextLimitPersistence(port: CursorContextLimitPersistence): void {\n\tif (persistence === port) return;\n\tpersistence = port;\n\thydrated = false;\n}\n\nfunction hydrate(): void {\n\tif (hydrated) return;\n\t// Set before loading: a load that observes nothing must not retry per read.\n\thydrated = true;\n\tif (!persistence) return;\n\tfor (const [modelId, maxTokens] of persistence.load()) {\n\t\tif (!observedLimits.has(modelId)) observedLimits.set(modelId, maxTokens);\n\t}\n}\n\n/**\n * Records the server-reported ceiling for `modelId`. The first checkpoint of a\n * conversation reports 0, so non-positive and non-finite values are ignored.\n */\nexport function recordCursorContextLimit(modelId: string, maxTokens: number | undefined): void {\n\tif (maxTokens === undefined || !Number.isFinite(maxTokens) || maxTokens <= 0) return;\n\thydrate();\n\tif (observedLimits.get(modelId) === maxTokens) return;\n\tobservedLimits.set(modelId, maxTokens);\n\tpersistence?.save(observedLimits);\n}\n\nexport function getCursorContextLimit(modelId: string): number | undefined {\n\thydrate();\n\treturn observedLimits.get(modelId);\n}\n\n/** The window to trust for `modelId`: what the server reported, else the catalog. */\nexport function resolveCursorContextWindow(modelId: string, catalogWindow: number): number {\n\treturn getCursorContextLimit(modelId) ?? catalogWindow;\n}\n\n/** Drops in-memory state so the next read re-hydrates from the installed port. */\nexport function resetCursorContextLimitStoreForTest(): void {\n\tobservedLimits.clear();\n\thydrated = false;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"store-migration.d.ts","sourceRoot":"","sources":["../../src/cursor/store-migration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAyCzC;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC,cAAc,CAAC,EAAE,GAAG,KAAK,CAAC,cAAc,CAAC,EAAE,CAiC3G"}
1
+ {"version":3,"file":"store-migration.d.ts","sourceRoot":"","sources":["../../src/cursor/store-migration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AA0CzC;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC,cAAc,CAAC,EAAE,GAAG,KAAK,CAAC,cAAc,CAAC,EAAE,CAiC3G"}
@@ -1,4 +1,5 @@
1
1
  import { normalizeCursorCatalog } from "./catalog-grouping.js";
2
+ import { resolveCursorContextWindow } from "./context-limit-store.js";
2
3
  import { getCursorVariantAlias } from "./model-capabilities.js";
3
4
  function isGroupedShape(model) {
4
5
  return model.compat?.cursorReasoning !== undefined || getCursorVariantAlias(model.id) === undefined;
@@ -16,7 +17,7 @@ function entryToModel(entry, maxTokensById) {
16
17
  ...(entry.thinkingLevelMap ? { thinkingLevelMap: entry.thinkingLevelMap } : {}),
17
18
  input: entry.input,
18
19
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
19
- contextWindow: entry.window,
20
+ contextWindow: resolveCursorContextWindow(entry.id, entry.window),
20
21
  maxTokens,
21
22
  ...(entry.representativeVariantId !== undefined && entry.representativeVariantId !== entry.id
22
23
  ? { upstreamModelId: entry.representativeVariantId }
@@ -1 +1 @@
1
- {"version":3,"file":"store-migration.js","sourceRoot":"","sources":["../../src/cursor/store-migration.ts"],"names":[],"mappings":"AACA,OAAO,EAA2B,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACxF,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,SAAS,cAAc,CAAC,KAA4B;IACnD,OAAO,KAAK,CAAC,MAAM,EAAE,eAAe,KAAK,SAAS,IAAI,qBAAqB,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,SAAS,CAAC;AACrG,CAAC;AAED,SAAS,YAAY,CAAC,KAAyB,EAAE,aAA0C;IAC1F,MAAM,cAAc,GAAG,KAAK,CAAC,uBAAuB,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;IAC3F,MAAM,SAAS,GAAG,aAAa,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,KAAK,CAAC;IAC5F,OAAO;QACN,EAAE,EAAE,KAAK,CAAC,EAAE;QACZ,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,GAAG,EAAE,cAAc;QACnB,QAAQ,EAAE,QAAQ;QAClB,OAAO,EAAE,wBAAwB;QACjC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,GAAG,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,KAAK,CAAC,gBAAgB,EAA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AS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC5C,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;YAC/B,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvB,CAAC;aAAM,CAAC;YACP,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACjB,CAAC;IACF,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC","sourcesContent":["import type { Model } from \"../types.ts\";\nimport { type CursorCatalogEntry, normalizeCursorCatalog } from \"./catalog-grouping.ts\";\nimport { getCursorVariantAlias } from \"./model-capabilities.ts\";\n\nfunction isGroupedShape(model: Model<\"cursor-agent\">): boolean {\n\treturn model.compat?.cursorReasoning !== undefined || getCursorVariantAlias(model.id) === undefined;\n}\n\nfunction entryToModel(entry: CursorCatalogEntry, maxTokensById: ReadonlyMap<string, number>): Model<\"cursor-agent\"> {\n\tconst representative = entry.representativeVariantId ?? entry.legacyAliases[0] ?? entry.id;\n\tconst maxTokens = maxTokensById.get(representative) ?? maxTokensById.get(entry.id) ?? 64000;\n\treturn {\n\t\tid: entry.id,\n\t\tname: entry.name,\n\t\tapi: \"cursor-agent\",\n\t\tprovider: \"cursor\",\n\t\tbaseUrl: \"https://api2.cursor.sh\",\n\t\treasoning: entry.reasoning,\n\t\t...(entry.thinkingLevelMap ? { thinkingLevelMap: entry.thinkingLevelMap } : {}),\n\t\tinput: entry.input,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: entry.window,\n\t\tmaxTokens,\n\t\t...(entry.representativeVariantId !== undefined && entry.representativeVariantId !== entry.id\n\t\t\t? { upstreamModelId: entry.representativeVariantId }\n\t\t\t: {}),\n\t\tcompat: {\n\t\t\t...(entry.cursorMaxMode ? { cursorMaxMode: true } : {}),\n\t\t\t...(entry.capabilityId !== undefined && entry.representativeVariantId !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tcursorReasoning: {\n\t\t\t\t\t\t\tcapabilityId: entry.capabilityId,\n\t\t\t\t\t\t\t...(entry.thinkingMode !== undefined ? { thinkingMode: entry.thinkingMode } : {}),\n\t\t\t\t\t\t\trepresentativeVariantId: entry.representativeVariantId,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t},\n\t};\n}\n\n/**\n * Idempotent stored-catalog transform: pre-grouping 204-variant cursor entries\n * are regrouped into selectable identities; already-grouped, unknown, and\n * malformed entries pass through unchanged in stable input order.\n */\nexport function regroupStoredCursorModels(models: readonly Model<\"cursor-agent\">[]): Model<\"cursor-agent\">[] {\n\tconst legacy = models.filter((model) => !isGroupedShape(model));\n\tif (legacy.length === 0) return [...models];\n\tconst maxTokensById = new Map(models.map((model) => [model.id, model.maxTokens]));\n\tconst regrouped = new Map(\n\t\tnormalizeCursorCatalog(\n\t\t\tlegacy.map((model) => ({\n\t\t\t\tid: model.id,\n\t\t\t\tname: model.name,\n\t\t\t\tinput: model.input.filter((modality): modality is \"text\" | \"image\" => modality !== \"video\"),\n\t\t\t\tcursorMaxMode: model.compat?.cursorMaxMode === true,\n\t\t\t})),\n\t\t).map((entry) => [entry.id, entryToModel(entry, maxTokensById)] as const),\n\t);\n\tconst seen = new Set<string>();\n\tconst out: Model<\"cursor-agent\">[] = [];\n\tfor (const model of models) {\n\t\tif (isGroupedShape(model)) {\n\t\t\tout.push(model);\n\t\t\tcontinue;\n\t\t}\n\t\tconst alias = getCursorVariantAlias(model.id);\n\t\tconst targetId = alias?.targetId ?? model.id;\n\t\tif (seen.has(targetId)) continue;\n\t\tseen.add(targetId);\n\t\tconst transformed = regrouped.get(targetId);\n\t\tif (transformed !== undefined) {\n\t\t\tout.push(transformed);\n\t\t} else {\n\t\t\tout.push(model);\n\t\t}\n\t}\n\treturn out;\n}\n"]}
1
+ {"version":3,"file":"store-migration.js","sourceRoot":"","sources":["../../src/cursor/store-migration.ts"],"names":[],"mappings":"AACA,OAAO,EAA2B,sBAAsB,EAAE,MAAM,uBA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CursorCatalog } from \"./catalog-grouping.ts\";\nimport { resolveCursorContextWindow } from \"./context-limit-store.ts\";\nimport { getCursorVariantAlias } from \"./model-capabilities.ts\";\n\nfunction isGroupedShape(model: Model<\"cursor-agent\">): boolean {\n\treturn model.compat?.cursorReasoning !== undefined || getCursorVariantAlias(model.id) === undefined;\n}\n\nfunction entryToModel(entry: CursorCatalogEntry, maxTokensById: ReadonlyMap<string, number>): Model<\"cursor-agent\"> {\n\tconst representative = entry.representativeVariantId ?? entry.legacyAliases[0] ?? entry.id;\n\tconst maxTokens = maxTokensById.get(representative) ?? maxTokensById.get(entry.id) ?? 64000;\n\treturn {\n\t\tid: entry.id,\n\t\tname: entry.name,\n\t\tapi: \"cursor-agent\",\n\t\tprovider: \"cursor\",\n\t\tbaseUrl: \"https://api2.cursor.sh\",\n\t\treasoning: entry.reasoning,\n\t\t...(entry.thinkingLevelMap ? { thinkingLevelMap: entry.thinkingLevelMap } : {}),\n\t\tinput: entry.input,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: resolveCursorContextWindow(entry.id, entry.window),\n\t\tmaxTokens,\n\t\t...(entry.representativeVariantId !== undefined && entry.representativeVariantId !== entry.id\n\t\t\t? { upstreamModelId: entry.representativeVariantId }\n\t\t\t: {}),\n\t\tcompat: {\n\t\t\t...(entry.cursorMaxMode ? { cursorMaxMode: true } : {}),\n\t\t\t...(entry.capabilityId !== undefined && entry.representativeVariantId !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tcursorReasoning: {\n\t\t\t\t\t\t\tcapabilityId: entry.capabilityId,\n\t\t\t\t\t\t\t...(entry.thinkingMode !== undefined ? { thinkingMode: entry.thinkingMode } : {}),\n\t\t\t\t\t\t\trepresentativeVariantId: entry.representativeVariantId,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t},\n\t};\n}\n\n/**\n * Idempotent stored-catalog transform: pre-grouping 204-variant cursor entries\n * are regrouped into selectable identities; already-grouped, unknown, and\n * malformed entries pass through unchanged in stable input order.\n */\nexport function regroupStoredCursorModels(models: readonly Model<\"cursor-agent\">[]): Model<\"cursor-agent\">[] {\n\tconst legacy = models.filter((model) => !isGroupedShape(model));\n\tif (legacy.length === 0) return [...models];\n\tconst maxTokensById = new Map(models.map((model) => [model.id, model.maxTokens]));\n\tconst regrouped = new Map(\n\t\tnormalizeCursorCatalog(\n\t\t\tlegacy.map((model) => ({\n\t\t\t\tid: model.id,\n\t\t\t\tname: model.name,\n\t\t\t\tinput: model.input.filter((modality): modality is \"text\" | \"image\" => modality !== \"video\"),\n\t\t\t\tcursorMaxMode: model.compat?.cursorMaxMode === true,\n\t\t\t})),\n\t\t).map((entry) => [entry.id, entryToModel(entry, maxTokensById)] as const),\n\t);\n\tconst seen = new Set<string>();\n\tconst out: Model<\"cursor-agent\">[] = [];\n\tfor (const model of models) {\n\t\tif (isGroupedShape(model)) {\n\t\t\tout.push(model);\n\t\t\tcontinue;\n\t\t}\n\t\tconst alias = getCursorVariantAlias(model.id);\n\t\tconst targetId = alias?.targetId ?? model.id;\n\t\tif (seen.has(targetId)) continue;\n\t\tseen.add(targetId);\n\t\tconst transformed = regrouped.get(targetId);\n\t\tif (transformed !== undefined) {\n\t\t\tout.push(transformed);\n\t\t} else {\n\t\t\tout.push(model);\n\t\t}\n\t}\n\treturn out;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export type { AnthropicEffort, AnthropicOptions, AnthropicThinkingDisplay } from
4
4
  export { sanitizeAnthropicToolPairs } from "./api/anthropic-tool-pairs.ts";
5
5
  export type { AzureOpenAIResponsesOptions } from "./api/azure-openai-responses.ts";
6
6
  export type { BedrockOptions, BedrockThinkingDisplay } from "./api/bedrock-converse-stream.ts";
7
- export { measureCursorHistorySerializedBytes } from "./api/cursor-agent/measure.ts";
7
+ export { measureCursorHistorySerializedBytes, measureCursorModelInputSerializedBytes, } from "./api/cursor-agent/measure.ts";
8
8
  export { composeShellCommand as composeCursorShellCommand, omitUndefinedArgs as omitUndefinedCursorArgs, piLimit as cursorPiLimit, piLsPath as cursorPiLsPath, piReadArgs as cursorPiReadArgs, piTimeout as cursorPiTimeout, } from "./api/cursor-agent/pi-args.ts";
9
9
  export type { CursorAgentOptions, CursorExecHandlerResult, CursorExecHandlers, CursorExecPairing, CursorMcpCall, CursorPiCall, CursorShellStreamCallbacks, CursorToolResultHandler, } from "./api/cursor-agent/types.ts";
10
10
  export type { GoogleOptions } from "./api/google-generative-ai.ts";
@@ -39,6 +39,7 @@ export { getProtocol, getToolCallFormat, hasKimiTextToolCallRecovery, shouldReco
39
39
  export { createXtmlRecoveryStreamParser } from "./tool-call-middleware/protocols/kimi-xtml/recovery-stream.ts";
40
40
  export { wrapStreamWithInvokeRecovery } from "./tool-call-middleware/recovery-stream-wrapper.ts";
41
41
  export * from "./types.ts";
42
+ export * from "./utils/assistant-message-frame.ts";
42
43
  export { type CursorExecResolvedCarrier, copyCursorExecResolved, isCursorExecResolved, kCursorExecResolved, } from "./utils/block-symbols.ts";
43
44
  export * from "./utils/diagnostics.ts";
44
45
  export { dropFailedAssistantTurns } from "./utils/drop-failed-assistant-turns.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAM/B,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC/G,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,YAAY,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AACnF,YAAY,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC/F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CA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c,qBAAqB,CAAC;AACpC,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,8BAA8B,EAC9B,4BAA4B,GAC5B,MAAM,6BAA6B,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,oCAAoC,CAAC;AACnD,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,4BAA4B,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { Type } from "typebox";
2
2
  export { sanitizeAnthropicToolPairs } from "./api/anthropic-tool-pairs.js";
3
- export { measureCursorHistorySerializedBytes } from "./api/cursor-agent/measure.js";
3
+ export { measureCursorHistorySerializedBytes, measureCursorModelInputSerializedBytes, } from "./api/cursor-agent/measure.js";
4
4
  export { composeShellCommand as composeCursorShellCommand, omitUndefinedArgs as omitUndefinedCursorArgs, piLimit as cursorPiLimit, piLsPath as cursorPiLsPath, piReadArgs as cursorPiReadArgs, piTimeout as cursorPiTimeout, } from "./api/cursor-agent/pi-args.js";
5
5
  export * from "./api/lazy.js";
6
6
  export { convertResponsesMessages } from "./api/openai-responses-shared.js";
@@ -25,6 +25,7 @@ export { getProtocol, getToolCallFormat, hasKimiTextToolCallRecovery, shouldReco
25
25
  export { createXtmlRecoveryStreamParser } from "./tool-call-middleware/protocols/kimi-xtml/recovery-stream.js";
26
26
  export { wrapStreamWithInvokeRecovery } from "./tool-call-middleware/recovery-stream-wrapper.js";
27
27
  export * from "./types.js";
28
+ export * from "./utils/assistant-message-frame.js";
28
29
  export { copyCursorExecResolved, isCursorExecResolved, kCursorExecResolved, } from "./utils/block-symbols.js";
29
30
  export * from "./utils/diagnostics.js";
30
31
  export { dropFailedAssistantTurns } from "./utils/drop-failed-assistant-turns.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAO/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAG3E,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AACpF,OAAO,EACN,mBAAmB,IAAI,yBAAyB,EAChD,iBAAiB,IAAI,uBAAuB,EAC5C,OAAO,IAAI,aAAa,EACxB,QAAQ,IAAI,cAAc,EAC1B,UAAU,IAAI,gBAAgB,EAC9B,SAAS,IAAI,eAAe,GAC5B,MAAM,+BAA+B,CAAC;AAcvC,cAAc,eAAe,CAAC;AAK9B,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,OAAO,EAIN,eAAe,GACf,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,cAAc,mBAAmB,CAAC;AAClC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAUhC,OAAO,EACN,wBAAwB,EAExB,4BAA4B,EAC5B,qBAAqB,EACrB,oBAAoB,GACpB,MAAM,yBAAyB,CAAC;AACjC,cAAc,8BAA8B,CAAC;AAC7C,OAAO,EACN,yBAAyB,EAQzB,yBAAyB,EACzB,0BAA0B,EAC1B,qBAAqB,GACrB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAEN,0BAA0B,EAC1B,gCAAgC,GAChC,MAAM,kCAAkC,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,OAAO,EACN,WAAW,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,gBAAgB,EAChB,2BAA2B,EAC3B,gCAAgC,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,8BAA8B,EAAE,MAAM,+DAA+D,CAAC;AAC/G,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AACjG,cAAc,YAAY,CAAC;AAC3B,OAAO,EAEN,sBAAsB,EACtB,oBAAoB,EACpB,mBAAmB,GACnB,MAAM,0BAA0B,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAC;AAClF,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,cAAc,qBAAqB,CAAC;AACpC,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,8BAA8B,EAC9B,4BAA4B,GAC5B,MAAM,6BAA6B,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,oCAAoC,CAAC;AACnD,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,4BAA4B,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export type { Static, TSchema } from \"typebox\";\nexport { Type } from \"typebox\";\n// Core only, side-effect free: no generated catalogs, no provider factories,\n// no api-registry, no OAuth implementations, no compat. Provider factories\n// live under \"@earendil-works/pi-ai/providers/*\", API implementations under\n// \"@earendil-works/pi-ai/api/*\", the old global API under\n// \"@earendil-works/pi-ai/compat\".\nexport type { AnthropicEffort, AnthropicOptions, AnthropicThinkingDisplay } from \"./api/anthropic-messages.ts\";\nexport { sanitizeAnthropicToolPairs } from \"./api/anthropic-tool-pairs.ts\";\nexport type { AzureOpenAIResponsesOptions } from \"./api/azure-openai-responses.ts\";\nexport type { BedrockOptions, BedrockThinkingDisplay } from \"./api/bedrock-converse-stream.ts\";\nexport { measureCursorHistorySerializedBytes } from \"./api/cursor-agent/measure.ts\";\nexport {\n\tcomposeShellCommand as composeCursorShellCommand,\n\tomitUndefinedArgs as omitUndefinedCursorArgs,\n\tpiLimit as cursorPiLimit,\n\tpiLsPath as cursorPiLsPath,\n\tpiReadArgs as cursorPiReadArgs,\n\tpiTimeout as cursorPiTimeout,\n} from \"./api/cursor-agent/pi-args.ts\";\nexport type {\n\tCursorAgentOptions,\n\tCursorExecHandlerResult,\n\tCursorExecHandlers,\n\tCursorExecPairing,\n\tCursorMcpCall,\n\tCursorPiCall,\n\tCursorShellStreamCallbacks,\n\tCursorToolResultHandler,\n} from \"./api/cursor-agent/types.ts\";\nexport type { GoogleOptions } from \"./api/google-generative-ai.ts\";\nexport type { GoogleApiThinkingLevel, ResolvedGoogleThinkingLevel } from \"./api/google-shared.ts\";\nexport type { GoogleVertexOptions } from \"./api/google-vertex.ts\";\nexport * from \"./api/lazy.ts\";\nexport type { MistralOptions } from \"./api/mistral-conversations.ts\";\nexport type { OpenAICodexResponsesOptions, OpenAICodexWebSocketDebugStats } from \"./api/openai-codex-responses.ts\";\nexport type { OpenAICompletionsOptions } from \"./api/openai-completions.ts\";\nexport type { OpenAIResponsesOptions } from \"./api/openai-responses.ts\";\nexport { convertResponsesMessages } from \"./api/openai-responses-shared.ts\";\nexport type { PiMessagesEvent, PiMessagesOptions, PiMessagesRewriteImpact } from \"./api/pi-messages.ts\";\nexport {\n\ttype WarmPromptCacheOptions,\n\ttype WarmPromptCacheResult,\n\ttype WarmPromptCacheUsage,\n\twarmPromptCache,\n} from \"./api/warm-prompt-cache.ts\";\nexport { getApiProvider } from \"./api-registry.ts\";\nexport * from \"./auth/context.ts\";\nexport * from \"./auth/credential-store.ts\";\nexport * from \"./auth/headers.ts\";\nexport * from \"./auth/helpers.ts\";\nexport * from \"./auth/types.ts\";\nexport type {\n\tOAuthAuthInfo,\n\tOAuthDeviceCodeInfo,\n\tOAuthLoginCallbacks,\n\tOAuthPrompt,\n\tOAuthProviderId,\n\tOAuthSelectOption,\n\tOAuthSelectPrompt,\n} from \"./compat/extension-oauth-types.ts\";\nexport {\n\tCONTEXT_PROVENANCE_FIELD,\n\ttype ContextProvenance,\n\tcontextProvenanceFingerprint,\n\tcopyContextProvenance,\n\tgetContextProvenance,\n} from \"./context-provenance.ts\";\nexport * from \"./cursor/catalog-grouping.ts\";\nexport {\n\tCURSOR_MODEL_CAPABILITIES,\n\ttype CursorCapabilityEvidence,\n\ttype CursorLevelEncoding,\n\ttype CursorLevelSpec,\n\ttype CursorModelCapability,\n\ttype CursorParameterId,\n\ttype CursorVariantAlias,\n\ttype CursorVariantParse,\n\tgetCursorBaseIdForVariant,\n\tgetCursorCapabilityForBase,\n\tgetCursorVariantAlias,\n} from \"./cursor/model-capabilities.ts\";\nexport {\n\ttype CursorResolvedSelection,\n\trenderCursorCliModelString,\n\tresolveCursorSelectionDescriptor,\n} from \"./cursor/selection-descriptor.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./images-models.ts\";\nexport * from \"./models.ts\";\nexport * from \"./models-store.ts\";\nexport * from \"./providers/faux.ts\";\nexport * from \"./session-resources.ts\";\nexport {\n\tgetProtocol,\n\tgetToolCallFormat,\n\thasKimiTextToolCallRecovery,\n\tshouldRecoverTextToolCalls,\n\ttransformContext,\n\twrapStreamWithModelRecovery,\n\twrapStreamWithToolCallMiddleware,\n} from \"./tool-call-middleware/index.ts\";\nexport { createXtmlRecoveryStreamParser } from \"./tool-call-middleware/protocols/kimi-xtml/recovery-stream.ts\";\nexport { wrapStreamWithInvokeRecovery } from \"./tool-call-middleware/recovery-stream-wrapper.ts\";\nexport * from \"./types.ts\";\nexport {\n\ttype CursorExecResolvedCarrier,\n\tcopyCursorExecResolved,\n\tisCursorExecResolved,\n\tkCursorExecResolved,\n} from \"./utils/block-symbols.ts\";\nexport * from \"./utils/diagnostics.ts\";\nexport { dropFailedAssistantTurns } from \"./utils/drop-failed-assistant-turns.ts\";\nexport { estimateContextTokens } from \"./utils/estimate.ts\";\nexport * from \"./utils/event-stream.ts\";\nexport * from \"./utils/json-parse.ts\";\nexport { extractOpenAiCodexAccountId } from \"./utils/openai-codex-auth.ts\";\nexport * from \"./utils/overflow.ts\";\nexport {\n\tisAnthropicApiBaseUrl,\n\tPROMPT_CACHE_TTL_LONG_SECONDS,\n\tPROMPT_CACHE_TTL_SHORT_SECONDS,\n\tresolvePromptCacheTtlSeconds,\n} from \"./utils/prompt-cache-ttl.ts\";\nexport * from \"./utils/retry.ts\";\nexport * from \"./utils/server-fallback-receipt.ts\";\nexport * from \"./utils/stop-details.ts\";\nexport { contentText } from \"./utils/text.ts\";\nexport * from \"./utils/tool-pair-repair.ts\";\nexport * from \"./utils/typebox-helpers.ts\";\nexport { uuidv7 } from \"./utils/uuid.ts\";\nexport * from \"./utils/validation.ts\";\nexport * from \"./utils/visible-text.ts\";\nexport { getWireIdentity, setWireIdentity } from \"./wire-identity.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAO/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAG3E,OAAO,EACN,mCAAmC,EACnC,sCAAsC,GACtC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,mBAAmB,IAAI,yBAAyB,EAChD,iBAAiB,IAAI,uBAAuB,EAC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pB,mBAAmB,GACnB,MAAM,0BAA0B,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAC;AAClF,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,cAAc,qBAAqB,CAAC;AACpC,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,8BAA8B,EAC9B,4BAA4B,GAC5B,MAAM,6BAA6B,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,oCAAoC,CAAC;AACnD,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,4BAA4B,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export type { Static, TSchema } from \"typebox\";\nexport { Type } from \"typebox\";\n// Core only, side-effect free: no generated catalogs, no provider factories,\n// no api-registry, no OAuth implementations, no compat. Provider factories\n// live under \"@earendil-works/pi-ai/providers/*\", API implementations under\n// \"@earendil-works/pi-ai/api/*\", the old global API under\n// \"@earendil-works/pi-ai/compat\".\nexport type { AnthropicEffort, AnthropicOptions, AnthropicThinkingDisplay } from \"./api/anthropic-messages.ts\";\nexport { sanitizeAnthropicToolPairs } from \"./api/anthropic-tool-pairs.ts\";\nexport type { AzureOpenAIResponsesOptions } from \"./api/azure-openai-responses.ts\";\nexport type { BedrockOptions, BedrockThinkingDisplay } from \"./api/bedrock-converse-stream.ts\";\nexport {\n\tmeasureCursorHistorySerializedBytes,\n\tmeasureCursorModelInputSerializedBytes,\n} from \"./api/cursor-agent/measure.ts\";\nexport {\n\tcomposeShellCommand as composeCursorShellCommand,\n\tomitUndefinedArgs as omitUndefinedCursorArgs,\n\tpiLimit as cursorPiLimit,\n\tpiLsPath as cursorPiLsPath,\n\tpiReadArgs as cursorPiReadArgs,\n\tpiTimeout as cursorPiTimeout,\n} from \"./api/cursor-agent/pi-args.ts\";\nexport type {\n\tCursorAgentOptions,\n\tCursorExecHandlerResult,\n\tCursorExecHandlers,\n\tCursorExecPairing,\n\tCursorMcpCall,\n\tCursorPiCall,\n\tCursorShellStreamCallbacks,\n\tCursorToolResultHandler,\n} from \"./api/cursor-agent/types.ts\";\nexport type { GoogleOptions } from \"./api/google-generative-ai.ts\";\nexport type { GoogleApiThinkingLevel, ResolvedGoogleThinkingLevel } from \"./api/google-shared.ts\";\nexport type { GoogleVertexOptions } from \"./api/google-vertex.ts\";\nexport * from \"./api/lazy.ts\";\nexport type { MistralOptions } from \"./api/mistral-conversations.ts\";\nexport type { OpenAICodexResponsesOptions, OpenAICodexWebSocketDebugStats } from \"./api/openai-codex-responses.ts\";\nexport type { OpenAICompletionsOptions } from \"./api/openai-completions.ts\";\nexport type { OpenAIResponsesOptions } from \"./api/openai-responses.ts\";\nexport { convertResponsesMessages } from \"./api/openai-responses-shared.ts\";\nexport type { PiMessagesEvent, PiMessagesOptions, PiMessagesRewriteImpact } from \"./api/pi-messages.ts\";\nexport {\n\ttype WarmPromptCacheOptions,\n\ttype WarmPromptCacheResult,\n\ttype WarmPromptCacheUsage,\n\twarmPromptCache,\n} from \"./api/warm-prompt-cache.ts\";\nexport { getApiProvider } from \"./api-registry.ts\";\nexport * from \"./auth/context.ts\";\nexport * from \"./auth/credential-store.ts\";\nexport * from \"./auth/headers.ts\";\nexport * from \"./auth/helpers.ts\";\nexport * from \"./auth/types.ts\";\nexport type {\n\tOAuthAuthInfo,\n\tOAuthDeviceCodeInfo,\n\tOAuthLoginCallbacks,\n\tOAuthPrompt,\n\tOAuthProviderId,\n\tOAuthSelectOption,\n\tOAuthSelectPrompt,\n} from \"./compat/extension-oauth-types.ts\";\nexport {\n\tCONTEXT_PROVENANCE_FIELD,\n\ttype ContextProvenance,\n\tcontextProvenanceFingerprint,\n\tcopyContextProvenance,\n\tgetContextProvenance,\n} from \"./context-provenance.ts\";\nexport * from \"./cursor/catalog-grouping.ts\";\nexport {\n\tCURSOR_MODEL_CAPABILITIES,\n\ttype CursorCapabilityEvidence,\n\ttype CursorLevelEncoding,\n\ttype CursorLevelSpec,\n\ttype CursorModelCapability,\n\ttype CursorParameterId,\n\ttype CursorVariantAlias,\n\ttype CursorVariantParse,\n\tgetCursorBaseIdForVariant,\n\tgetCursorCapabilityForBase,\n\tgetCursorVariantAlias,\n} from \"./cursor/model-capabilities.ts\";\nexport {\n\ttype CursorResolvedSelection,\n\trenderCursorCliModelString,\n\tresolveCursorSelectionDescriptor,\n} from \"./cursor/selection-descriptor.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./images-models.ts\";\nexport * from \"./models.ts\";\nexport * from \"./models-store.ts\";\nexport * from \"./providers/faux.ts\";\nexport * from \"./session-resources.ts\";\nexport {\n\tgetProtocol,\n\tgetToolCallFormat,\n\thasKimiTextToolCallRecovery,\n\tshouldRecoverTextToolCalls,\n\ttransformContext,\n\twrapStreamWithModelRecovery,\n\twrapStreamWithToolCallMiddleware,\n} from \"./tool-call-middleware/index.ts\";\nexport { createXtmlRecoveryStreamParser } from \"./tool-call-middleware/protocols/kimi-xtml/recovery-stream.ts\";\nexport { wrapStreamWithInvokeRecovery } from \"./tool-call-middleware/recovery-stream-wrapper.ts\";\nexport * from \"./types.ts\";\nexport * from \"./utils/assistant-message-frame.ts\";\nexport {\n\ttype CursorExecResolvedCarrier,\n\tcopyCursorExecResolved,\n\tisCursorExecResolved,\n\tkCursorExecResolved,\n} from \"./utils/block-symbols.ts\";\nexport * from \"./utils/diagnostics.ts\";\nexport { dropFailedAssistantTurns } from \"./utils/drop-failed-assistant-turns.ts\";\nexport { estimateContextTokens } from \"./utils/estimate.ts\";\nexport * from \"./utils/event-stream.ts\";\nexport * from \"./utils/json-parse.ts\";\nexport { extractOpenAiCodexAccountId } from \"./utils/openai-codex-auth.ts\";\nexport * from \"./utils/overflow.ts\";\nexport {\n\tisAnthropicApiBaseUrl,\n\tPROMPT_CACHE_TTL_LONG_SECONDS,\n\tPROMPT_CACHE_TTL_SHORT_SECONDS,\n\tresolvePromptCacheTtlSeconds,\n} from \"./utils/prompt-cache-ttl.ts\";\nexport * from \"./utils/retry.ts\";\nexport * from \"./utils/server-fallback-receipt.ts\";\nexport * from \"./utils/stop-details.ts\";\nexport { contentText } from \"./utils/text.ts\";\nexport * from \"./utils/tool-pair-repair.ts\";\nexport * from \"./utils/typebox-helpers.ts\";\nexport { uuidv7 } from \"./utils/uuid.ts\";\nexport * from \"./utils/validation.ts\";\nexport * from \"./utils/visible-text.ts\";\nexport { getWireIdentity, setWireIdentity } from \"./wire-identity.ts\";\n"]}
package/dist/models.d.ts CHANGED
@@ -145,6 +145,7 @@ export interface Models {
145
145
  complete<TApi extends Api>(model: Model<TApi>, context: Context, options?: ModelsApiStreamOptions<TApi>): Promise<AssistantMessage>;
146
146
  streamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;
147
147
  completeSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>;
148
+ streamDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredFetchOptions): AssistantMessageEventStream;
148
149
  fetchDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredFetchOptions): Promise<AssistantMessage>;
149
150
  cancelDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredCancelOptions): Promise<void>;
150
151
  }