@bastani/pi-ai 0.9.24 → 0.9.25-alpha.1

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 (100) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/NOTICE.md +1 -1
  3. package/README.md +17 -6
  4. package/dist/api/cloudflare-workers-ai-system-one.js +2 -2
  5. package/dist/api/cloudflare-workers-ai-system-one.js.map +1 -1
  6. package/dist/api/openai-codex-responses.d.ts +2 -2
  7. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  8. package/dist/api/openai-codex-responses.js +8 -28
  9. package/dist/api/openai-codex-responses.js.map +1 -1
  10. package/dist/api/openai-responses-shared.d.ts +25 -6
  11. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  12. package/dist/api/openai-responses-shared.js +66 -19
  13. package/dist/api/openai-responses-shared.js.map +1 -1
  14. package/dist/api/openai-responses.d.ts +2 -1
  15. package/dist/api/openai-responses.d.ts.map +1 -1
  16. package/dist/api/openai-responses.js +21 -32
  17. package/dist/api/openai-responses.js.map +1 -1
  18. package/dist/api/system-one-shared.d.ts +2 -2
  19. package/dist/api/system-one-shared.d.ts.map +1 -1
  20. package/dist/api/system-one-shared.js +26 -1
  21. package/dist/api/system-one-shared.js.map +1 -1
  22. package/dist/api/typesafe-system-one.js +2 -2
  23. package/dist/api/typesafe-system-one.js.map +1 -1
  24. package/dist/auth/helpers.js +1 -1
  25. package/dist/auth/helpers.js.map +1 -1
  26. package/dist/auth/oauth/anthropic.d.ts.map +1 -1
  27. package/dist/auth/oauth/anthropic.js +19 -128
  28. package/dist/auth/oauth/anthropic.js.map +1 -1
  29. package/dist/auth/oauth/callback-server.d.ts +31 -0
  30. package/dist/auth/oauth/callback-server.d.ts.map +1 -0
  31. package/dist/auth/oauth/callback-server.js +138 -0
  32. package/dist/auth/oauth/callback-server.js.map +1 -0
  33. package/dist/auth/oauth/load.d.ts +2 -0
  34. package/dist/auth/oauth/load.d.ts.map +1 -1
  35. package/dist/auth/oauth/load.js +5 -0
  36. package/dist/auth/oauth/load.js.map +1 -1
  37. package/dist/auth/oauth/oauth-page.js +1 -1
  38. package/dist/auth/oauth/oauth-page.js.map +1 -1
  39. package/dist/auth/oauth/openai-chatgpt.d.ts +3 -0
  40. package/dist/auth/oauth/openai-chatgpt.d.ts.map +1 -0
  41. package/dist/auth/oauth/openai-chatgpt.js +250 -0
  42. package/dist/auth/oauth/openai-chatgpt.js.map +1 -0
  43. package/dist/auth/oauth/openai-codex.d.ts +1 -1
  44. package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
  45. package/dist/auth/oauth/openai-codex.js +20 -124
  46. package/dist/auth/oauth/openai-codex.js.map +1 -1
  47. package/dist/auth/oauth/openrouter.d.ts +1 -1
  48. package/dist/auth/oauth/openrouter.d.ts.map +1 -1
  49. package/dist/auth/oauth/openrouter.js +19 -138
  50. package/dist/auth/oauth/openrouter.js.map +1 -1
  51. package/dist/auth/oauth/radius.d.ts +1 -1
  52. package/dist/auth/oauth/radius.d.ts.map +1 -1
  53. package/dist/auth/oauth/radius.js +21 -89
  54. package/dist/auth/oauth/radius.js.map +1 -1
  55. package/dist/auth/types.d.ts +6 -1
  56. package/dist/auth/types.d.ts.map +1 -1
  57. package/dist/auth/types.js.map +1 -1
  58. package/dist/bun-oauth.d.ts.map +1 -1
  59. package/dist/bun-oauth.js +2 -0
  60. package/dist/bun-oauth.js.map +1 -1
  61. package/dist/cli.js +2 -1
  62. package/dist/cli.js.map +1 -1
  63. package/dist/models.d.ts +5 -3
  64. package/dist/models.d.ts.map +1 -1
  65. package/dist/models.js +6 -2
  66. package/dist/models.js.map +1 -1
  67. package/dist/providers/data/.manifest.json +1 -1
  68. package/dist/providers/data/amazon-bedrock.json +1 -1
  69. package/dist/providers/data/azure-openai-responses.json +1 -1
  70. package/dist/providers/data/baseten.json +1 -1
  71. package/dist/providers/data/cerebras.json +1 -1
  72. package/dist/providers/data/github-copilot.json +1 -1
  73. package/dist/providers/data/openai-codex.json +1 -1
  74. package/dist/providers/data/openai.json +1 -1
  75. package/dist/providers/data/opencode.json +1 -1
  76. package/dist/providers/data/openrouter.json +1 -1
  77. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  78. package/dist/providers/openai-codex.js +1 -1
  79. package/dist/providers/openai-codex.js.map +1 -1
  80. package/dist/providers/openai.d.ts.map +1 -1
  81. package/dist/providers/openai.js +11 -2
  82. package/dist/providers/openai.js.map +1 -1
  83. package/dist/providers/opencode.d.ts +3 -1
  84. package/dist/providers/opencode.d.ts.map +1 -1
  85. package/dist/providers/opencode.js +4 -2
  86. package/dist/providers/opencode.js.map +1 -1
  87. package/dist/providers/vercel-ai-gateway.d.ts.map +1 -1
  88. package/dist/providers/vercel-ai-gateway.js +4 -2
  89. package/dist/providers/vercel-ai-gateway.js.map +1 -1
  90. package/dist/types.d.ts +40 -1
  91. package/dist/types.d.ts.map +1 -1
  92. package/dist/types.js.map +1 -1
  93. package/dist/utils/oauth-page.d.ts +2 -0
  94. package/dist/utils/oauth-page.d.ts.map +1 -0
  95. package/dist/utils/oauth-page.js +2 -0
  96. package/dist/utils/oauth-page.js.map +1 -0
  97. package/dist/utils/retry.d.ts.map +1 -1
  98. package/dist/utils/retry.js +3 -0
  99. package/dist/utils/retry.js.map +1 -1
  100. package/package.json +6 -2
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses.js","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAelD,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,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AI,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 } from \"openai/resources/responses/responses.js\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tModel,\n\tOpenAIResponsesCompat,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTranscriptContext,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { createStreamDeadline, withStreamDeadline } from \"../utils/stream-deadline.ts\";\nimport { getDeclaredTools, resolveTranscript, resolveTranscriptTools } from \"../utils/transcript.ts\";\nimport { createGrammarToolInputProperties } from \"./constrained-sampling.ts\";\nimport {\n\tbuildCopilotDynamicHeaders,\n\thasCopilotVisionInput,\n\tpreserveCopilotIntegrationHeader,\n} from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport {\n\tassertPayloadPreservesFastRoute,\n\tconvertResponsesMessages,\n\tconvertResponsesTools,\n\tprocessResponsesStream,\n\tresolveRequestedServiceTier,\n} from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\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\nfunction hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {\n\tif (!headers) return false;\n\tconst expected = name.toLowerCase();\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true;\n\t}\n\treturn false;\n}\n\nfunction getClientApiKey(provider: string, apiKey: string | undefined, headers: ProviderHeaders | undefined): string {\n\tif (apiKey) return apiKey;\n\tif (hasHeader(headers, \"authorization\") || hasHeader(headers, \"cf-aig-authorization\")) return \"unused\";\n\tthrow new Error(`No API key for provider: ${provider}`);\n}\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\">): Required<OpenAIResponsesCompat> {\n\treturn {\n\t\tsupportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true,\n\t\tsupportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,\n\t\tsessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model),\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\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 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): ResponseCreateParamsStreaming[\"prompt_cache_options\"] {\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\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\"];\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: TranscriptContext,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst normalizedContext = resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages);\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\tconst streamDeadline = createStreamDeadline(options?.streamDeadlineMs, options?.signal);\n\n\t\ttry {\n\t\t\t// Create OpenAI client\n\t\t\tconst apiKey = getClientApiKey(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);\n\t\t\tconst grammarToolInputProperties = createGrammarToolInputProperties(\n\t\t\t\tgetDeclaredTools(normalizedContext.messages),\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\tnormalizedContext,\n\t\t\t\tapiKey,\n\t\t\t\toptions?.headers,\n\t\t\t\toptions?.fetch,\n\t\t\t\tcacheSessionId,\n\t\t\t\toptions?.apiKey,\n\t\t\t);\n\t\t\tlet params = buildParams(model, normalizedContext, 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 ResponseCreateParamsStreaming;\n\t\t\t}\n\t\t\tassertPayloadPreservesFastRoute(model, params);\n\t\t\tconst requestOptions = {\n\t\t\t\t...(streamDeadline.signal ? { signal: streamDeadline.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: streamDeadline.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(\n\t\t\t\twithStreamDeadline(openaiStream, streamDeadline.deadlineMs, streamDeadline.abort),\n\t\t\t\toutput,\n\t\t\t\tstream,\n\t\t\t\tmodel,\n\t\t\t\t{\n\t\t\t\t\tonProviderStreamEvent: options?.onProviderStreamEvent,\n\t\t\t\t\tserviceTier: resolveRequestedServiceTier(model, options?.serviceTier),\n\t\t\t\t\tgrammarToolInputProperties,\n\t\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t\t},\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 = formatProviderError(\n\t\t\t\tnormalizeProviderError(error),\n\t\t\t\t`${model.provider === \"openai\" ? \"OpenAI\" : model.provider} API error`,\n\t\t\t);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tstreamDeadline.cleanup();\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: TranscriptContext,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tgetClientApiKey(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} satisfies OpenAIResponsesOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\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: TranscriptContext,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n\tsessionId?: string,\n\tcopilotApiKey?: string,\n) {\n\tconst compat = getCompat(model);\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 = preserveCopilotIntegrationHeader(\n\t\t\tmodel.headers,\n\t\t\tbuildCopilotDynamicHeaders({\n\t\t\t\tmessages: context.messages,\n\t\t\t\thasImages,\n\t\t\t\tapiKey: copilotApiKey,\n\t\t\t}),\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: 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: TranscriptContext,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat> = getCompat(model),\n\tgrammarToolInputProperties: ReadonlyMap<string, string> = createGrammarToolInputProperties(\n\t\tgetDeclaredTools(context.messages),\n\t\tcompat.supportsOpenAIGrammarTools,\n\t),\n) {\n\tconst transcriptTools = resolveTranscriptTools(\n\t\tcontext.messages,\n\t\tcompat.supportsAdditionalTools || compat.supportsToolSearch,\n\t);\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {\n\t\tgrammarToolInputProperties,\n\t\tsupportsMidConvoSystemMessages: compat.supportsMidConvoSystemMessages,\n\t\tsupportsAdditionalTools: compat.supportsAdditionalTools,\n\t\tsupportsToolSearch: compat.supportsToolSearch,\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, options?.env);\n\tconst params: ResponseCreateParamsStreaming = {\n\t\t// A fast variant keeps its canonical `-fast` id on the model object — that is the identity the\n\t\t// caller selected and records — while routing to the base upstream model plus a service tier.\n\t\tmodel: model.fastRoute?.upstreamModelId ?? 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\t// A fast variant carries its own tier, so a caller that only hands over the model still routes fast.\n\tconst requestedServiceTier = resolveRequestedServiceTier(model, options?.serviceTier);\n\tif (requestedServiceTier !== undefined) {\n\t\tparams.service_tier = requestedServiceTier;\n\t}\n\n\tif (transcriptTools.requestTools.length > 0) {\n\t\tparams.tools = convertResponsesTools(transcriptTools.requestTools, {\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 (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tconst effort = options?.reasoningEffort\n\t\t\t\t? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n\t\t\t\t: \"medium\";\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: effort as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else if (model.provider !== \"github-copilot\" && model.thinkingLevelMap?.off !== null) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: (model.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\t// Last so custom keys override the named request fields. Per-request keys override model defaults.\n\tObject.assign(params, model.samplingParams, options?.samplingParams);\n\n\treturn params;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-responses\">, \"fastRoute\" | \"id\">,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): number {\n\t// Price against the model that was actually billed upstream, so a `-fast` variant of a\n\t// per-model rate (gpt-5.5) is not silently charged the generic multiplier.\n\tconst pricedModelId = model.fastRoute?.baseModelId ?? model.id;\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 pricedModelId === \"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\"] | undefined,\n\tmodel: Pick<Model<\"openai-responses\">, \"fastRoute\" | \"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
+ {"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D,CAAC;aAAM,IAAI,KAAK,CAAC,QAAQ,KAAK,gBAAgB,IAAI,KAAK,CAAC,gBAAgB,EAAE,GAAG,KAAK,IAAI,EAAE,CAAC;YACxF,MAAM,CAAC,SAAS,GAAG;gBAClB,MAAM,EAAE,CAAC,KAAK,CAAC,gBAAgB,EAAE,GAAG,IAAI,MAAM,CAAmD;aACjG,CAAC;QACH,CAAC;QACD,IAAI,KAAK,CAAC,QAAQ,KAAK,KAAK;YAAE,MAAM,CAAC,OAAO,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAChF,CAAC;IAED,mGAAmG;IACnG,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,cAAc,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC;IAErE,OAAO,MAAM,CAAC;AACf,CAAC;AAED,SAAS,+BAA+B,CACvC,KAAgC,EAChC,kBAAoD;IAEpD,OAAO,2BAA2B,CAAC,KAAK,EAAE,2BAA2B,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC,CAAC;AACnG,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tModel,\n\tOpenAIResponsesCompat,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTranscriptContext,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { createStreamDeadline, withStreamDeadline } from \"../utils/stream-deadline.ts\";\nimport { getDeclaredTools, resolveTranscript, resolveTranscriptTools } from \"../utils/transcript.ts\";\nimport { createGrammarToolInputProperties } from \"./constrained-sampling.ts\";\nimport {\n\tbuildCopilotDynamicHeaders,\n\thasCopilotVisionInput,\n\tpreserveCopilotIntegrationHeader,\n} from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport {\n\tapplyServiceTierPricing,\n\tassertPayloadPreservesFastRoute,\n\tconvertResponsesMessages,\n\tconvertResponsesTools,\n\tprocessResponsesStream,\n\ttype ResponsesServiceTier,\n\tresolveRequestedServiceTier,\n\topenAIServiceTierForRequest,\n} from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\n// OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265\nconst OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;\nconst CHATGPT_USAGE_URL = \"https://chatgpt.com/settings/usage\";\n\nfunction isChatGPTSignIn(model: Model<\"openai-responses\">, apiKey: string | undefined): boolean {\n\treturn (\n\t\tmodel.provider === \"openai\" &&\n\t\tmodel.baseUrl === \"https://api.openai.com/v1\" &&\n\t\tapiKey !== undefined &&\n\t\t!apiKey.startsWith(\"sk-\")\n\t);\n}\n\nfunction hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {\n\tif (!headers) return false;\n\tconst expected = name.toLowerCase();\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true;\n\t}\n\treturn false;\n}\n\nfunction getClientApiKey(provider: string, apiKey: string | undefined, headers: ProviderHeaders | undefined): string {\n\tif (apiKey) return apiKey;\n\tif (hasHeader(headers, \"authorization\") || hasHeader(headers, \"cf-aig-authorization\")) return \"unused\";\n\tthrow new Error(`No API key for provider: ${provider}`);\n}\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\">): Required<OpenAIResponsesCompat> {\n\treturn {\n\t\tsupportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true,\n\t\tsupportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,\n\t\tsessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model),\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\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 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): ResponseCreateParamsStreaming[\"prompt_cache_options\"] {\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\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?: ResponsesServiceTier;\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: TranscriptContext,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst normalizedContext = resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages);\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\tconst streamDeadline = createStreamDeadline(options?.streamDeadlineMs, options?.signal);\n\n\t\ttry {\n\t\t\t// Create OpenAI client\n\t\t\tconst apiKey = getClientApiKey(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);\n\t\t\tconst grammarToolInputProperties = createGrammarToolInputProperties(\n\t\t\t\tgetDeclaredTools(normalizedContext.messages),\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\tnormalizedContext,\n\t\t\t\tapiKey,\n\t\t\t\toptions?.headers,\n\t\t\t\toptions?.fetch,\n\t\t\t\tcacheSessionId,\n\t\t\t\toptions?.apiKey,\n\t\t\t);\n\t\t\tlet params = buildParams(model, normalizedContext, 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 ResponseCreateParamsStreaming;\n\t\t\t}\n\t\t\tassertPayloadPreservesFastRoute(model, params);\n\t\t\tconst requestOptions = {\n\t\t\t\t...(streamDeadline.signal ? { signal: streamDeadline.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: streamDeadline.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(\n\t\t\t\twithStreamDeadline(openaiStream, streamDeadline.deadlineMs, streamDeadline.abort),\n\t\t\t\toutput,\n\t\t\t\tstream,\n\t\t\t\tmodel,\n\t\t\t\t{\n\t\t\t\t\tonProviderStreamEvent: options?.onProviderStreamEvent,\n\t\t\t\t\tserviceTier: resolveOpenAIRequestServiceTier(model, options?.serviceTier),\n\t\t\t\t\tgrammarToolInputProperties,\n\t\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t\t},\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\tconst errorMessage = formatProviderError(\n\t\t\t\tnormalizeProviderError(error),\n\t\t\t\t`${model.provider === \"openai\" ? \"OpenAI\" : model.provider} API error`,\n\t\t\t);\n\t\t\toutput.errorMessage = errorMessage.includes(\"subscription_sharing_usage_limit_exceeded\")\n\t\t\t\t? `${errorMessage}\\nCheck your ChatGPT usage: ${CHATGPT_USAGE_URL}`\n\t\t\t\t: errorMessage;\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tstreamDeadline.cleanup();\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: TranscriptContext,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tgetClientApiKey(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} satisfies OpenAIResponsesOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\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: TranscriptContext,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n\tsessionId?: string,\n\tcopilotApiKey?: string,\n) {\n\tconst compat = getCompat(model);\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 = preserveCopilotIntegrationHeader(\n\t\t\tmodel.headers,\n\t\t\tbuildCopilotDynamicHeaders({\n\t\t\t\tmessages: context.messages,\n\t\t\t\thasImages,\n\t\t\t\tapiKey: copilotApiKey,\n\t\t\t}),\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: 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: TranscriptContext,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat> = getCompat(model),\n\tgrammarToolInputProperties: ReadonlyMap<string, string> = createGrammarToolInputProperties(\n\t\tgetDeclaredTools(context.messages),\n\t\tcompat.supportsOpenAIGrammarTools,\n\t),\n) {\n\tconst transcriptTools = resolveTranscriptTools(\n\t\tcontext.messages,\n\t\tcompat.supportsAdditionalTools || compat.supportsToolSearch,\n\t);\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {\n\t\tgrammarToolInputProperties,\n\t\tsupportsMidConvoSystemMessages: compat.supportsMidConvoSystemMessages,\n\t\tsupportsAdditionalTools: compat.supportsAdditionalTools,\n\t\tsupportsToolSearch: compat.supportsToolSearch,\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, options?.env);\n\tconst omitUnsupportedFields = isChatGPTSignIn(model, options?.apiKey);\n\tconst params: ResponseCreateParamsStreaming = {\n\t\t// A fast variant keeps its canonical `-fast` id on the model object — that is the identity the\n\t\t// caller selected and records — while routing to the base upstream model plus a service tier.\n\t\tmodel: model.fastRoute?.upstreamModelId ?? 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: omitUnsupportedFields ? undefined : getPromptCacheRetention(compat, cacheRetention),\n\t\tprompt_cache_options: omitUnsupportedFields ? undefined : getPromptCacheOptions(compat, cacheRetention),\n\t\tstore: false,\n\t};\n\n\tif (options?.maxTokens && compat.supportsMaxOutputTokens && !omitUnsupportedFields) {\n\t\tparams.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);\n\t}\n\n\tif (options?.temperature !== undefined && !omitUnsupportedFields) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tconst requestedServiceTier = resolveOpenAIRequestServiceTier(model, options?.serviceTier);\n\tif (requestedServiceTier !== undefined) {\n\t\tparams.service_tier = requestedServiceTier;\n\t}\n\n\tif (transcriptTools.requestTools.length > 0) {\n\t\tparams.tools = convertResponsesTools(transcriptTools.requestTools, {\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 (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tconst effort = options?.reasoningEffort\n\t\t\t\t? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n\t\t\t\t: \"medium\";\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: effort as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else if (model.provider !== \"github-copilot\" && model.thinkingLevelMap?.off !== null) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: (model.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\t// Last so custom keys override the named request fields. Per-request keys override model defaults.\n\tObject.assign(params, model.samplingParams, options?.samplingParams);\n\n\treturn params;\n}\n\nfunction resolveOpenAIRequestServiceTier(\n\tmodel: Model<\"openai-responses\">,\n\toptionsServiceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\treturn openAIServiceTierForRequest(model, resolveRequestedServiceTier(model, optionsServiceTier));\n}\n"]}
@@ -14,8 +14,8 @@ export interface SystemOneTransport {
14
14
  url(model: ClassifierModel<ClassifierApi>): URL;
15
15
  /** Wraps the System One request in the service's request envelope. */
16
16
  payload(model: ClassifierModel<ClassifierApi>, request: SystemOneWireRequest): unknown;
17
- /** Extracts the System One `answers` object from the service's response envelope. */
18
- answers(body: unknown): unknown;
17
+ /** Extracts the System One output, including answers and usage. */
18
+ output(body: unknown): Record<string, unknown>;
19
19
  }
20
20
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
21
21
  /** Runs one System One classification over the given transport. */
@@ -1 +1 @@
1
- {"version":3,"file":"system-one-shared.d.ts","sourceRoot":"","sources":["../../src/api/system-one-shared.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAEhB,MAAM,aAAa,CAAC;AAKrB,gFAAgF;AAChF,MAAM,WAAW,oBAAoB;IACpC,KAAK,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC;AAED,iEAAiE;AACjE,MAAM,WAAW,kBAAkB;IAClC,oDAAoD;IACpD,GAAG,EAAE,aAAa,CAAC;IACnB,2CAA2C;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,4BAA4B;IAC5B,GAAG,CAAC,KAAK,EAAE,eAAe,CAAC,aAAa,CAAC,GAAG,GAAG,CAAC;IAChD,sEAAsE;IACtE,OAAO,CAAC,KAAK,EAAE,eAAe,CAAC,aAAa,CAAC,EAAE,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC;IACvF,qFAAqF;IACrF,OAAO,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC;CAChC;AAyBD,wBAAgB,QAAQ,CAAC,KAAK,EA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AE,kBAAkB,EAC7B,KAAK,EAAE,eAAe,CAAC,aAAa,CAAC,EACrC,OAAO,EAAE,iBAAiB,EAC1B,OAAO,EAAE,iBAAiB,GAAG,SAAS,GACpC,OAAO,CAAC,gBAAgB,CAAC,CAyD3B"}
@@ -1,3 +1,4 @@
1
+ import { calculateCost } from "../models.js";
1
2
  import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";
2
3
  import { headersToRecord, providerHeadersToRecord } from "../utils/headers.js";
3
4
  import { retryProviderRequest } from "../utils/provider-retry.js";
@@ -97,6 +98,25 @@ function parseAnswers(label, value, context) {
97
98
  }
98
99
  return Object.fromEntries(answers);
99
100
  }
101
+ function tokenCount(value) {
102
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
103
+ }
104
+ function parseUsage(value, model) {
105
+ if (!isRecord(value) || (value.input_tokens === undefined && value.output_tokens === undefined))
106
+ return undefined;
107
+ const input = tokenCount(value.input_tokens);
108
+ const output = tokenCount(value.output_tokens);
109
+ const usage = {
110
+ input,
111
+ output,
112
+ cacheRead: 0,
113
+ cacheWrite: 0,
114
+ totalTokens: input + output,
115
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
116
+ };
117
+ calculateCost(model, usage);
118
+ return usage;
119
+ }
100
120
  /** Maps public `bool` questions to TypeSafe's wire-level `noul` type. */
101
121
  function wireRequest(context) {
102
122
  return {
@@ -158,7 +178,12 @@ export async function classifySystemOne(transport, model, context, options) {
158
178
  signal: options.signal,
159
179
  });
160
180
  await options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
161
- output.answers = parseAnswers(transport.label, transport.answers(body), context);
181
+ const result = transport.output(body);
182
+ // Malformed answers may still be billed, so retain usage before parsing them.
183
+ const usage = parseUsage(result.usage, model);
184
+ if (usage)
185
+ output.usage = usage;
186
+ output.answers = parseAnswers(transport.label, result.answers, context);
162
187
  return output;
163
188
  }
164
189
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file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AAY,CAAC,OAAO,CAAC,SAAU,CAAC,CAAC;gBAC/F,MAAM,KAAK,CAAC;YACb,CAAC;QACF,CAAC,EACD;YACC,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,CAAC;YACnC,eAAe,EAAE,OAAO,CAAC,eAAe;YACxC,MAAM,EAAE,OAAO,CAAC,MAAM;SACtB,CACD,CAAC;QACF,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,eAAe,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QAC3G,MAAM,CAAC,OAAO,GAAG,YAAY,CAAC,SAAS,CAAC,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;QACjF,OAAO,MAAM,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,CAAC,UAAU,GAAG,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;QACnE,MAAM,CAAC,YAAY,GAAG,mBAAmB,CAAC,sBAAsB,CAAC,KAAK,CAAC,EAAE,GAAG,SAAS,CAAC,KAAK,QAAQ,CAAC,CAAC;QACrG,OAAO,MAAM,CAAC;IACf,CAAC;AACF,CAAC","sourcesContent":["import type {\n\tClassifierAnswer,\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tProviderHeaders,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\n\n/** TypeSafe System One request body without the transport-specific envelope. */\nexport interface SystemOneWireRequest {\n\tstate: ClassifierContext[\"state\"];\n\tquestions: Record<string, unknown>;\n}\n\n/** Differences between services that serve System One models. */\nexport interface SystemOneTransport {\n\t/** Classifier API implemented by this transport. */\n\tapi: ClassifierApi;\n\t/** Service name used in error messages. */\n\tlabel: string;\n\t/** Absolute request URL. */\n\turl(model: ClassifierModel<ClassifierApi>): URL;\n\t/** Wraps the System One request in the service's request envelope. */\n\tpayload(model: ClassifierModel<ClassifierApi>, request: SystemOneWireRequest): unknown;\n\t/** Extracts the System One `answers` object from the service's response envelope. */\n\tanswers(body: unknown): unknown;\n}\n\ninterface SystemOneHttpError extends Error {\n\tstatus: number | undefined;\n\theaders: Headers | undefined;\n\tbody: string;\n}\n\nfunction httpError(label: string, response: Response, body: string): SystemOneHttpError {\n\tconst error = new Error(`${label} returned ${response.status}`) as SystemOneHttpError;\n\terror.status = response.status;\n\terror.headers = response.headers;\n\terror.body = body;\n\treturn error;\n}\n\nfunction timeoutError(timeoutMs: number): SystemOneHttpError {\n\tconst error = new Error(`Request timed out after ${timeoutMs}ms`) as SystemOneHttpError;\n\terror.name = \"TimeoutError\";\n\terror.status = undefined;\n\terror.headers = undefined;\n\terror.body = \"\";\n\treturn error;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requiredNumber(label: string, value: unknown, field: string): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\tthrow new Error(`${label} returned an invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction unitInterval(label: string, value: unknown, field: string): number {\n\tconst number = requiredNumber(label, value, field);\n\tif (number < 0 || number > 1) throw new Error(`${label} returned an invalid ${field}`);\n\treturn number;\n}\n\nfunction probabilities(label: string, value: unknown, id: string): Record<string, number> {\n\tif (!isRecord(value)) throw new Error(`${label} returned invalid probabilities for ${id}`);\n\treturn Object.fromEntries(\n\t\tObject.entries(value).map(([key, probability]) => [\n\t\t\tkey,\n\t\t\tunitInterval(label, probability, `probability for ${id}.${key}`),\n\t\t]),\n\t);\n}\n\nfunction parseAnswers(label: string, value: unknown, context: ClassifierContext): Record<string, ClassifierAnswer> {\n\tif (!isRecord(value)) throw new Error(`${label} returned an unexpected response`);\n\tconst answers: Array<[string, ClassifierAnswer]> = [];\n\tfor (const [id, question] of Object.entries(context.questions)) {\n\t\tconst answer = value[id];\n\t\tif (!isRecord(answer)) throw new Error(`${label} did not return an answer for ${id}`);\n\t\tif (question.type === \"choice\") {\n\t\t\tif (\n\t\t\t\tanswer.type !== \"choice\" ||\n\t\t\t\ttypeof answer.choice !== \"string\" ||\n\t\t\t\t!Object.hasOwn(question.criteria, answer.choice)\n\t\t\t) {\n\t\t\t\tthrow new Error(`${label} did not return a valid choice answer for ${id}`);\n\t\t\t}\n\t\t\tconst choiceProbabilities = probabilities(label, answer.probabilities, id);\n\t\t\tif (Object.keys(choiceProbabilities).some((key) => !Object.hasOwn(question.criteria, key))) {\n\t\t\t\tthrow new Error(`${label} returned an unknown choice probability for ${id}`);\n\t\t\t}\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"choice\",\n\t\t\t\t\tchoice: answer.choice,\n\t\t\t\t\tprobabilities: choiceProbabilities,\n\t\t\t\t\tconfidence: unitInterval(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (answer.type !== \"score\") throw new Error(`${label} did not return a score answer for ${id}`);\n\t\t\tconst score = requiredNumber(label, answer.score, `score for ${id}`);\n\t\t\tif (score < 0 || score > question.criteria.length - 1) {\n\t\t\t\tthrow new Error(`${label} returned an invalid score for ${id}`);\n\t\t\t}\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"score\",\n\t\t\t\t\tscore,\n\t\t\t\t\tconfidence: unitInterval(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else {\n\t\t\tif (answer.type !== \"noul\") throw new Error(`${label} did not return a bool answer for ${id}`);\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"bool\",\n\t\t\t\t\tprobability: unitInterval(label, answer.noul, `probability for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t}\n\treturn Object.fromEntries(answers);\n}\n\n/** Maps public `bool` questions to TypeSafe's wire-level `noul` type. */\nfunction wireRequest(context: ClassifierContext): SystemOneWireRequest {\n\treturn {\n\t\tstate: context.state,\n\t\tquestions: Object.fromEntries(\n\t\t\tObject.entries(context.questions).map(([id, question]) => [\n\t\t\t\tid,\n\t\t\t\tquestion.type === \"bool\" ? { ...question, type: \"noul\" } : question,\n\t\t\t]),\n\t\t),\n\t};\n}\n\nfunction requestHeaders(\n\tmodel: ClassifierModel<ClassifierApi>,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n): Record<string, string> {\n\treturn (\n\t\tproviderHeadersToRecord(\n\t\t\t{ authorization: `Bearer ${apiKey}`, \"content-type\": \"application/json\" },\n\t\t\tmodel.headers,\n\t\t\toptionsHeaders,\n\t\t) ?? {}\n\t);\n}\n\n/** Runs one System One classification over the given transport. */\nexport async function classifySystemOne(\n\ttransport: SystemOneTransport,\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions: ClassifierOptions | undefined,\n): Promise<ClassifierResult> {\n\tconst output: ClassifierResult = {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tanswers: {},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\n\ttry {\n\t\tif (model.api !== transport.api) throw new Error(`Unsupported classifier API: ${model.api}`);\n\t\tif (!options?.apiKey) throw new Error(`No API key for provider: ${model.provider}`);\n\t\tconst apiKey = options.apiKey;\n\t\tlet payload = transport.payload(model, wireRequest(context));\n\t\tconst transformed = await options.onPayload?.(payload, model);\n\t\tif (transformed !== undefined) payload = transformed;\n\t\tconst requestFetch = options.fetch ?? globalThis.fetch;\n\t\tconst { response, body } = await retryProviderRequest(\n\t\t\tasync () => {\n\t\t\t\tconst timeoutSignal = options.timeoutMs !== undefined ? AbortSignal.timeout(options.timeoutMs) : undefined;\n\t\t\t\tconst signal =\n\t\t\t\t\toptions.signal && timeoutSignal\n\t\t\t\t\t\t? AbortSignal.any([options.signal, timeoutSignal])\n\t\t\t\t\t\t: (options.signal ?? timeoutSignal);\n\t\t\t\ttry {\n\t\t\t\t\tconst next = await requestFetch(transport.url(model), {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders(model, apiKey, options.headers),\n\t\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t});\n\t\t\t\t\tif (!next.ok) throw httpError(transport.label, next, await next.text());\n\t\t\t\t\treturn { response: next, body: (await next.json()) as unknown };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (timeoutSignal?.aborted && !options.signal?.aborted) throw timeoutError(options.timeoutMs!);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tmaxRetries: options.maxRetries ?? 2,\n\t\t\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t\t\t\tsignal: options.signal,\n\t\t\t},\n\t\t);\n\t\tawait options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\toutput.answers = parseAnswers(transport.label, transport.answers(body), context);\n\t\treturn output;\n\t} catch (error) {\n\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error), `${transport.label} error`);\n\t\treturn output;\n\t}\n}\n"]}
1
+ {"version":3,"file":"system-one-shared.js","sourceRoot":"","sources":["../../src/api/system-one-shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAW7C,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAw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CAAC;QACtC,8EAA8E;QAC9E,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAC9C,IAAI,KAAK;YAAE,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;QAChC,MAAM,CAAC,OAAO,GAAG,YAAY,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxE,OAAO,MAAM,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,CAAC,UAAU,GAAG,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;QACnE,MAAM,CAAC,YAAY,GAAG,mBAAmB,CAAC,sBAAsB,CAAC,KAAK,CAAC,EAAE,GAAG,SAAS,CAAC,KAAK,QAAQ,CAAC,CAAC;QACrG,OAAO,MAAM,CAAC;IACf,CAAC;AACF,CAAC","sourcesContent":["import { calculateCost } from \"../models.ts\";\nimport type {\n\tClassifierAnswer,\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tProviderHeaders,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\n\n/** TypeSafe System One request body without the transport-specific envelope. */\nexport interface SystemOneWireRequest {\n\tstate: ClassifierContext[\"state\"];\n\tquestions: Record<string, unknown>;\n}\n\n/** Differences between services that serve System One models. */\nexport interface SystemOneTransport {\n\t/** Classifier API implemented by this transport. */\n\tapi: ClassifierApi;\n\t/** Service name used in error messages. */\n\tlabel: string;\n\t/** Absolute request URL. */\n\turl(model: ClassifierModel<ClassifierApi>): URL;\n\t/** Wraps the System One request in the service's request envelope. */\n\tpayload(model: ClassifierModel<ClassifierApi>, request: SystemOneWireRequest): unknown;\n\t/** Extracts the System One output, including answers and usage. */\n\toutput(body: unknown): Record<string, unknown>;\n}\n\ninterface SystemOneHttpError extends Error {\n\tstatus: number | undefined;\n\theaders: Headers | undefined;\n\tbody: string;\n}\n\nfunction httpError(label: string, response: Response, body: string): SystemOneHttpError {\n\tconst error = new Error(`${label} returned ${response.status}`) as SystemOneHttpError;\n\terror.status = response.status;\n\terror.headers = response.headers;\n\terror.body = body;\n\treturn error;\n}\n\nfunction timeoutError(timeoutMs: number): SystemOneHttpError {\n\tconst error = new Error(`Request timed out after ${timeoutMs}ms`) as SystemOneHttpError;\n\terror.name = \"TimeoutError\";\n\terror.status = undefined;\n\terror.headers = undefined;\n\terror.body = \"\";\n\treturn error;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requiredNumber(label: string, value: unknown, field: string): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\tthrow new Error(`${label} returned an invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction unitInterval(label: string, value: unknown, field: string): number {\n\tconst number = requiredNumber(label, value, field);\n\tif (number < 0 || number > 1) throw new Error(`${label} returned an invalid ${field}`);\n\treturn number;\n}\n\nfunction probabilities(label: string, value: unknown, id: string): Record<string, number> {\n\tif (!isRecord(value)) throw new Error(`${label} returned invalid probabilities for ${id}`);\n\treturn Object.fromEntries(\n\t\tObject.entries(value).map(([key, probability]) => [\n\t\t\tkey,\n\t\t\tunitInterval(label, probability, `probability for ${id}.${key}`),\n\t\t]),\n\t);\n}\n\nfunction parseAnswers(label: string, value: unknown, context: ClassifierContext): Record<string, ClassifierAnswer> {\n\tif (!isRecord(value)) throw new Error(`${label} returned an unexpected response`);\n\tconst answers: Array<[string, ClassifierAnswer]> = [];\n\tfor (const [id, question] of Object.entries(context.questions)) {\n\t\tconst answer = value[id];\n\t\tif (!isRecord(answer)) throw new Error(`${label} did not return an answer for ${id}`);\n\t\tif (question.type === \"choice\") {\n\t\t\tif (\n\t\t\t\tanswer.type !== \"choice\" ||\n\t\t\t\ttypeof answer.choice !== \"string\" ||\n\t\t\t\t!Object.hasOwn(question.criteria, answer.choice)\n\t\t\t) {\n\t\t\t\tthrow new Error(`${label} did not return a valid choice answer for ${id}`);\n\t\t\t}\n\t\t\tconst choiceProbabilities = probabilities(label, answer.probabilities, id);\n\t\t\tif (Object.keys(choiceProbabilities).some((key) => !Object.hasOwn(question.criteria, key))) {\n\t\t\t\tthrow new Error(`${label} returned an unknown choice probability for ${id}`);\n\t\t\t}\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"choice\",\n\t\t\t\t\tchoice: answer.choice,\n\t\t\t\t\tprobabilities: choiceProbabilities,\n\t\t\t\t\tconfidence: unitInterval(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (answer.type !== \"score\") throw new Error(`${label} did not return a score answer for ${id}`);\n\t\t\tconst score = requiredNumber(label, answer.score, `score for ${id}`);\n\t\t\tif (score < 0 || score > question.criteria.length - 1) {\n\t\t\t\tthrow new Error(`${label} returned an invalid score for ${id}`);\n\t\t\t}\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"score\",\n\t\t\t\t\tscore,\n\t\t\t\t\tconfidence: unitInterval(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else {\n\t\t\tif (answer.type !== \"noul\") throw new Error(`${label} did not return a bool answer for ${id}`);\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"bool\",\n\t\t\t\t\tprobability: unitInterval(label, answer.noul, `probability for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t}\n\treturn Object.fromEntries(answers);\n}\n\nfunction tokenCount(value: unknown): number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\n}\n\nfunction parseUsage(value: unknown, model: ClassifierModel<ClassifierApi>): Usage | undefined {\n\tif (!isRecord(value) || (value.input_tokens === undefined && value.output_tokens === undefined)) return undefined;\n\tconst input = tokenCount(value.input_tokens);\n\tconst output = tokenCount(value.output_tokens);\n\tconst usage: Usage = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: input + output,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tcalculateCost(model, usage);\n\treturn usage;\n}\n\n/** Maps public `bool` questions to TypeSafe's wire-level `noul` type. */\nfunction wireRequest(context: ClassifierContext): SystemOneWireRequest {\n\treturn {\n\t\tstate: context.state,\n\t\tquestions: Object.fromEntries(\n\t\t\tObject.entries(context.questions).map(([id, question]) => [\n\t\t\t\tid,\n\t\t\t\tquestion.type === \"bool\" ? { ...question, type: \"noul\" } : question,\n\t\t\t]),\n\t\t),\n\t};\n}\n\nfunction requestHeaders(\n\tmodel: ClassifierModel<ClassifierApi>,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n): Record<string, string> {\n\treturn (\n\t\tproviderHeadersToRecord(\n\t\t\t{ authorization: `Bearer ${apiKey}`, \"content-type\": \"application/json\" },\n\t\t\tmodel.headers,\n\t\t\toptionsHeaders,\n\t\t) ?? {}\n\t);\n}\n\n/** Runs one System One classification over the given transport. */\nexport async function classifySystemOne(\n\ttransport: SystemOneTransport,\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions: ClassifierOptions | undefined,\n): Promise<ClassifierResult> {\n\tconst output: ClassifierResult = {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tanswers: {},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\n\ttry {\n\t\tif (model.api !== transport.api) throw new Error(`Unsupported classifier API: ${model.api}`);\n\t\tif (!options?.apiKey) throw new Error(`No API key for provider: ${model.provider}`);\n\t\tconst apiKey = options.apiKey;\n\t\tlet payload = transport.payload(model, wireRequest(context));\n\t\tconst transformed = await options.onPayload?.(payload, model);\n\t\tif (transformed !== undefined) payload = transformed;\n\t\tconst requestFetch = options.fetch ?? globalThis.fetch;\n\t\tconst { response, body } = await retryProviderRequest(\n\t\t\tasync () => {\n\t\t\t\tconst timeoutSignal = options.timeoutMs !== undefined ? AbortSignal.timeout(options.timeoutMs) : undefined;\n\t\t\t\tconst signal =\n\t\t\t\t\toptions.signal && timeoutSignal\n\t\t\t\t\t\t? AbortSignal.any([options.signal, timeoutSignal])\n\t\t\t\t\t\t: (options.signal ?? timeoutSignal);\n\t\t\t\ttry {\n\t\t\t\t\tconst next = await requestFetch(transport.url(model), {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders(model, apiKey, options.headers),\n\t\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t});\n\t\t\t\t\tif (!next.ok) throw httpError(transport.label, next, await next.text());\n\t\t\t\t\treturn { response: next, body: (await next.json()) as unknown };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (timeoutSignal?.aborted && !options.signal?.aborted) throw timeoutError(options.timeoutMs!);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tmaxRetries: options.maxRetries ?? 2,\n\t\t\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t\t\t\tsignal: options.signal,\n\t\t\t},\n\t\t);\n\t\tawait options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\tconst result = transport.output(body);\n\t\t// Malformed answers may still be billed, so retain usage before parsing them.\n\t\tconst usage = parseUsage(result.usage, model);\n\t\tif (usage) output.usage = usage;\n\t\toutput.answers = parseAnswers(transport.label, result.answers, context);\n\t\treturn output;\n\t} catch (error) {\n\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error), `${transport.label} error`);\n\t\treturn output;\n\t}\n}\n"]}
@@ -8,10 +8,10 @@ const transport = {
8
8
  label: "System One API",
9
9
  url: (model) => new URL("systemone", `${model.baseUrl.replace(/\/+$/u, "")}/`),
10
10
  payload: (model, request) => ({ model: model.id, ...request }),
11
- answers: (body) => {
11
+ output: (body) => {
12
12
  if (!isRecord(body))
13
13
  throw new Error("System One API returned an unexpected response");
14
- return body.answers;
14
+ return body;
15
15
  },
16
16
  };
17
17
  /** TypeSafe System One classification with public `bool` values mapped to wire-level `noul`. */
@@ -1 +1 @@
1
- {"version":3,"file":"typesafe-system-one.js","sourceRoot":"","sources":["../../src/api/typesafe-system-one.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAA2B,MAAM,wBAAwB,CAAC;AAE9F;;;GAGG;AACH,MAAM,SAAS,GAAuB;IACrC,GAAG,EAAE,qBAAqB;IAC1B,KAAK,EAAE,gBAAgB;IACvB,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,WAAW,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC;IAC9E,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC;IAC9D,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE;QACjB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACvF,OAAO,IAAI,CAAC,OAAO,CAAC;IACrB,CAAC;CACD,CAAC;AAEF,gGAAgG;AAChG,MAAM,CAAC,MAAM,QAAQ,GAA0C,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAC1F,iBAAiB,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC","sourcesContent":["import type { ClassifierFunction, ClassifierOptions } from \"../types.ts\";\nimport { classifySystemOne, isRecord, type SystemOneTransport } from \"./system-one-shared.ts\";\n\n/**\n * TypeSafe's native System One protocol. OpenRouter serves the same protocol,\n * so both providers use this API with different base URLs.\n */\nconst transport: SystemOneTransport = {\n\tapi: \"typesafe-system-one\",\n\tlabel: \"System One API\",\n\turl: (model) => new URL(\"systemone\", `${model.baseUrl.replace(/\\/+$/u, \"\")}/`),\n\tpayload: (model, request) => ({ model: model.id, ...request }),\n\tanswers: (body) => {\n\t\tif (!isRecord(body)) throw new Error(\"System One API returned an unexpected response\");\n\t\treturn body.answers;\n\t},\n};\n\n/** TypeSafe System One classification with public `bool` values mapped to wire-level `noul`. */\nexport const classify: ClassifierFunction<ClassifierOptions> = (model, context, options) =>\n\tclassifySystemOne(transport, model, context, options);\n"]}
1
+ {"version":3,"file":"typesafe-system-one.js","sourceRoot":"","sources":["../../src/api/typesafe-system-one.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAA2B,MAAM,wBAAwB,CAAC;AAE9F;;;GAGG;AACH,MAAM,SAAS,GAAuB;IACrC,GAAG,EAAE,qBAAqB;IAC1B,KAAK,EAAE,gBAAgB;IACvB,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,WAAW,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC;IAC9E,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC;IAC9D,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;QAChB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACvF,OAAO,IAAI,CAAC;IACb,CAAC;CACD,CAAC;AAEF,gGAAgG;AAChG,MAAM,CAAC,MAAM,QAAQ,GAA0C,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAC1F,iBAAiB,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC","sourcesContent":["import type { ClassifierFunction, ClassifierOptions } from \"../types.ts\";\nimport { classifySystemOne, isRecord, type SystemOneTransport } from \"./system-one-shared.ts\";\n\n/**\n * TypeSafe's native System One protocol. OpenRouter serves the same protocol,\n * so both providers use this API with different base URLs.\n */\nconst transport: SystemOneTransport = {\n\tapi: \"typesafe-system-one\",\n\tlabel: \"System One API\",\n\turl: (model) => new URL(\"systemone\", `${model.baseUrl.replace(/\\/+$/u, \"\")}/`),\n\tpayload: (model, request) => ({ model: model.id, ...request }),\n\toutput: (body) => {\n\t\tif (!isRecord(body)) throw new Error(\"System One API returned an unexpected response\");\n\t\treturn body;\n\t},\n};\n\n/** TypeSafe System One classification with public `bool` values mapped to wire-level `noul`. */\nexport const classify: ClassifierFunction<ClassifierOptions> = (model, context, options) =>\n\tclassifySystemOne(transport, model, context, options);\n"]}
@@ -45,7 +45,7 @@ export function lazyOAuth(input) {
45
45
  name: input.name,
46
46
  isSubscription: input.isSubscription,
47
47
  loginLabel: input.loginLabel,
48
- login: async (interaction) => (await loaded()).login(interaction),
48
+ login: async (interaction, options) => (await loaded()).login(interaction, options),
49
49
  refresh: async (credential, signal) => (await loaded()).refresh(credential, signal),
50
50
  toAuth: async (credential) => (await loaded()).toAuth(credential),
51
51
  };
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE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CAAC;IAChB,CAAC,CAAC;IACF,OAAO;QACN,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC;QACjE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC;QACnF,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC;KACjE,CAAC;AACH,CAAC","sourcesContent":["import type { ApiKeyAuth, OAuthAuth } from \"./types.ts\";\n\n/**\n * Standard api-key auth: a stored credential key wins, otherwise the first\n * set env var resolves. Includes a `login` that prompts for the key.\n * Providers with non-standard resolution (provider env, ambient files, IAM)\n * write their own `ApiKeyAuth`.\n */\nexport function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth {\n\treturn {\n\t\tname,\n\t\tlogin: async (interaction) => {\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: `Enter ${name}` });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\t\t\tfor (const envVar of envVars) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (value) return { auth: { apiKey: value }, source: envVar };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/**\n * Wraps a dynamically imported `OAuthAuth` so provider definitions can\n * advertise OAuth without importing the implementation. The flow loads on\n * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out\n * of bundles by loading through a bundler-opaque dynamic import (variable\n * specifier, see the bedrock lazy wrapper).\n */\nexport function lazyOAuth(input: {\n\tname: string;\n\tisSubscription?: boolean;\n\tloginLabel?: string;\n\tload: () => Promise<OAuthAuth>;\n}): OAuthAuth {\n\tlet promise: Promise<OAuthAuth> | undefined;\n\tconst loaded = () => {\n\t\tpromise ??= input.load();\n\t\treturn promise;\n\t};\n\treturn {\n\t\tname: input.name,\n\t\tisSubscription: input.isSubscription,\n\t\tloginLabel: input.loginLabel,\n\t\tlogin: async (interaction) => (await loaded()).login(interaction),\n\t\trefresh: async (credential, signal) => (await loaded()).refresh(credential, signal),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAA0B;IACrE,OAAO;QACN,IAAI;QACJ,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE;YAC5B,WAAW,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YACpC,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE,EAAE,CAAC,CAAC;YACnF,WAAW,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YACpC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;QACjC,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE;YAC9C,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,IAAI,U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CAAC,UAAU,CAAC;KACjE,CAAC;AACH,CAAC","sourcesContent":["import type { ApiKeyAuth, OAuthAuth } from \"./types.ts\";\n\n/**\n * Standard api-key auth: a stored credential key wins, otherwise the first\n * set env var resolves. Includes a `login` that prompts for the key.\n * Providers with non-standard resolution (provider env, ambient files, IAM)\n * write their own `ApiKeyAuth`.\n */\nexport function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth {\n\treturn {\n\t\tname,\n\t\tlogin: async (interaction) => {\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: `Enter ${name}` });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\t\t\tfor (const envVar of envVars) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (value) return { auth: { apiKey: value }, source: envVar };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/**\n * Wraps a dynamically imported `OAuthAuth` so provider definitions can\n * advertise OAuth without importing the implementation. The flow loads on\n * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out\n * of bundles by loading through a bundler-opaque dynamic import (variable\n * specifier, see the bedrock lazy wrapper).\n */\nexport function lazyOAuth(input: {\n\tname: string;\n\tisSubscription?: boolean;\n\tloginLabel?: string;\n\tload: () => Promise<OAuthAuth>;\n}): OAuthAuth {\n\tlet promise: Promise<OAuthAuth> | undefined;\n\tconst loaded = () => {\n\t\tpromise ??= input.load();\n\t\treturn promise;\n\t};\n\treturn {\n\t\tname: input.name,\n\t\tisSubscription: input.isSubscription,\n\t\tloginLabel: input.loginLabel,\n\t\tlogin: async (interaction, options) => (await loaded()).login(interaction, options),\n\t\trefresh: async (credential, signal) => (await loaded()).refresh(credential, signal),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAyVvF,eAAO,MAAM,cAAc,EAAE,SAS5B,CAAC"}
1
+ {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA4NvF,eAAO,MAAM,cAAc,EAAE,SAS5B,CAAC"}
@@ -5,10 +5,8 @@
5
5
  * It is only intended for CLI use, not browser environments.
6
6
  */
7
7
  import { getProviderEnvValue } from "../../utils/provider-env.js";
8
- import { oauthErrorHtml, oauthSuccessHtml } from "./oauth-page.js";
8
+ import { startOAuthCallbackServer, waitForCallbackOrManualInput } from "./callback-server.js";
9
9
  import { generatePKCE } from "./pkce.js";
10
- let nodeApis = null;
11
- let nodeApisPromise = null;
12
10
  const decode = (s) => atob(s);
13
11
  const CLIENT_ID = decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
14
12
  const AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
@@ -18,20 +16,6 @@ const CALLBACK_PORT = 53692;
18
16
  const CALLBACK_PATH = "/callback";
19
17
  const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
20
18
  const SCOPES = "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
21
- async function getNodeApis() {
22
- if (nodeApis)
23
- return nodeApis;
24
- if (!nodeApisPromise) {
25
- if (typeof process === "undefined" || (!process.versions?.node && !process.versions?.bun)) {
26
- throw new Error("Anthropic OAuth is only available in Node.js environments");
27
- }
28
- nodeApisPromise = import("node:http").then((httpModule) => ({
29
- createServer: httpModule.createServer,
30
- }));
31
- }
32
- nodeApis = await nodeApisPromise;
33
- return nodeApis;
34
- }
35
19
  function parseAuthorizationInput(input) {
36
20
  const value = input.trim();
37
21
  if (!value)
@@ -77,69 +61,6 @@ function formatErrorDetails(error) {
77
61
  }
78
62
  return String(error);
79
63
  }
80
- async function startCallbackServer(expectedState) {
81
- const { createServer } = await getNodeApis();
82
- return new Promise((resolve, reject) => {
83
- let settleWait;
84
- const waitForCodePromise = new Promise((resolveWait) => {
85
- let settled = false;
86
- settleWait = (value) => {
87
- if (settled)
88
- return;
89
- settled = true;
90
- resolveWait(value);
91
- };
92
- });
93
- const server = createServer((req, res) => {
94
- try {
95
- const url = new URL(req.url || "", "http://localhost");
96
- if (url.pathname !== CALLBACK_PATH) {
97
- res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
98
- res.end(oauthErrorHtml("Callback route not found."));
99
- return;
100
- }
101
- const code = url.searchParams.get("code");
102
- const state = url.searchParams.get("state");
103
- const error = url.searchParams.get("error");
104
- if (error) {
105
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
106
- res.end(oauthErrorHtml("Anthropic authentication did not complete.", `Error: ${error}`));
107
- return;
108
- }
109
- if (!code || !state) {
110
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
111
- res.end(oauthErrorHtml("Missing code or state parameter."));
112
- return;
113
- }
114
- if (state !== expectedState) {
115
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
116
- res.end(oauthErrorHtml("State mismatch."));
117
- return;
118
- }
119
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
120
- res.end(oauthSuccessHtml("Anthropic authentication completed. You can close this window."));
121
- settleWait?.({ code, state });
122
- }
123
- catch {
124
- res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
125
- res.end("Internal error");
126
- }
127
- });
128
- server.on("error", (err) => {
129
- reject(err);
130
- });
131
- server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
132
- resolve({
133
- server,
134
- redirectUri: REDIRECT_URI,
135
- cancelWait: () => {
136
- settleWait?.(null);
137
- },
138
- waitForCode: () => waitForCodePromise,
139
- });
140
- });
141
- });
142
- }
143
64
  async function postJson(url, body, signal) {
144
65
  const response = await fetch(url, {
145
66
  method: "POST",
@@ -187,16 +108,15 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig
187
108
  }
188
109
  async function loginAnthropic(interaction) {
189
110
  const { verifier, challenge } = await generatePKCE();
190
- const server = await startCallbackServer(verifier);
191
- const manualAbort = new AbortController();
192
- const onAbort = () => server.cancelWait();
193
- interaction.signal.addEventListener("abort", onAbort, { once: true });
194
- if (interaction.signal.aborted)
195
- onAbort();
196
- let code;
197
- let state;
198
- let manualInput;
199
- let manualError;
111
+ const callback = await startOAuthCallbackServer({
112
+ providerName: "Anthropic",
113
+ host: CALLBACK_HOST,
114
+ port: CALLBACK_PORT,
115
+ path: CALLBACK_PATH,
116
+ state: verifier,
117
+ complete: async (code) => code,
118
+ signal: interaction.signal,
119
+ }).catch(() => undefined);
200
120
  try {
201
121
  const authParams = new URLSearchParams({
202
122
  code: "true",
@@ -213,58 +133,29 @@ async function loginAnthropic(interaction) {
213
133
  url: `${AUTHORIZE_URL}?${authParams.toString()}`,
214
134
  instructions: "Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.",
215
135
  });
216
- const manualPromise = interaction
217
- .prompt({
218
- type: "manual_code",
136
+ const result = await waitForCallbackOrManualInput(interaction, callback, {
219
137
  message: "Complete login in your browser, or paste the authorization code / redirect URL here:",
220
138
  placeholder: REDIRECT_URI,
221
- signal: manualAbort.signal,
222
- })
223
- .then((input) => {
224
- manualInput = input;
225
- server.cancelWait();
226
- })
227
- .catch((error) => {
228
- manualError = error instanceof Error ? error : new Error(String(error));
229
- server.cancelWait();
230
139
  });
231
- const result = await server.waitForCode();
232
- if (manualError)
233
- throw manualError;
234
- if (result?.code) {
235
- code = result.code;
236
- state = result.state;
140
+ let code;
141
+ let state = verifier;
142
+ if (result.type === "callback") {
143
+ code = result.value;
237
144
  }
238
- else if (manualInput) {
239
- const parsed = parseAuthorizationInput(manualInput);
145
+ else {
146
+ const parsed = parseAuthorizationInput(result.input);
240
147
  if (parsed.state && parsed.state !== verifier)
241
148
  throw new Error("OAuth state mismatch");
242
149
  code = parsed.code;
243
150
  state = parsed.state ?? verifier;
244
151
  }
245
- if (!code) {
246
- await manualPromise;
247
- if (manualError)
248
- throw manualError;
249
- if (manualInput) {
250
- const parsed = parseAuthorizationInput(manualInput);
251
- if (parsed.state && parsed.state !== verifier)
252
- throw new Error("OAuth state mismatch");
253
- code = parsed.code;
254
- state = parsed.state ?? verifier;
255
- }
256
- }
257
152
  if (!code)
258
153
  throw new Error("Missing authorization code");
259
- if (!state)
260
- throw new Error("Missing OAuth state");
261
154
  interaction.notify({ type: "progress", message: "Exchanging authorization code for tokens..." });
262
- return exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);
155
+ return await exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);
263
156
  }
264
157
  finally {
265
- interaction.signal.removeEventListener("abort", onAbort);
266
- manualAbort.abort();
267
- server.server.close();
158
+ callback?.close();
268
159
  }
269
160
  }
270
161
  /**