@bastani/pi-ai 0.9.74 → 0.9.75
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.
- package/CHANGELOG.md +43 -0
- package/README.md +3 -1
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +21 -7
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +4 -2
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/constrained-sampling.d.ts +0 -2
- package/dist/api/constrained-sampling.d.ts.map +1 -1
- package/dist/api/constrained-sampling.js +0 -13
- package/dist/api/constrained-sampling.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +9 -5
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-images-options.d.ts +18 -5
- package/dist/api/openai-images-options.d.ts.map +1 -1
- package/dist/api/openai-images-options.js +9 -3
- package/dist/api/openai-images-options.js.map +1 -1
- package/dist/api/openai-images.d.ts.map +1 -1
- package/dist/api/openai-images.js +121 -19
- package/dist/api/openai-images.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +10 -3
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/strict-tool-limits.d.ts +13 -0
- package/dist/api/strict-tool-limits.d.ts.map +1 -0
- package/dist/api/strict-tool-limits.js +50 -0
- package/dist/api/strict-tool-limits.js.map +1 -0
- package/dist/auth/types.d.ts +7 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cache-warming.d.ts +53 -0
- package/dist/cache-warming.d.ts.map +1 -0
- package/dist/cache-warming.js +82 -0
- package/dist/cache-warming.js.map +1 -0
- package/dist/image-generation-error.d.ts +10 -3
- package/dist/image-generation-error.d.ts.map +1 -1
- package/dist/image-generation-error.js +3 -2
- package/dist/image-generation-error.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +15 -6
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +22 -7
- package/dist/models.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/providers/data/anthropic.json +1 -1
- package/dist/providers/data/azure.json +1 -1
- package/dist/providers/data/google.json +1 -1
- package/dist/providers/data/meta.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/github-copilot-errors.d.ts +17 -5
- package/dist/providers/github-copilot-errors.d.ts.map +1 -1
- package/dist/providers/github-copilot-errors.js +55 -11
- package/dist/providers/github-copilot-errors.js.map +1 -1
- package/dist/providers/github-copilot-stream-attempt.d.ts +27 -0
- package/dist/providers/github-copilot-stream-attempt.d.ts.map +1 -0
- package/dist/providers/github-copilot-stream-attempt.js +45 -0
- package/dist/providers/github-copilot-stream-attempt.js.map +1 -0
- package/dist/providers/github-copilot.d.ts +10 -2
- package/dist/providers/github-copilot.d.ts.map +1 -1
- package/dist/providers/github-copilot.js +62 -36
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/stream-deadline.d.ts +6 -2
- package/dist/utils/stream-deadline.d.ts.map +1 -1
- package/dist/utils/stream-deadline.js +12 -3
- package/dist/utils/stream-deadline.js.map +1 -1
- package/dist/utils/version.d.ts +1 -1
- package/dist/utils/version.js +1 -1
- package/dist/utils/version.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-responses.js","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names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C,OAAO,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,KAAK,gBAAgB,CAAC,CAAC,CAAC,GAAG,KAAK,IAAI,CAAC;AAC/E,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 type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport { githubCopilotEmptyResponse, recordGitHubCopilotFailure } from \"../providers/github-copilot-errors.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} 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 { type ClientIdentity, getIdentityHeaders } from \"../utils/identity.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { admitOpenAIRequests, getFetchAdmission } from \"../utils/request-admission.js\";\nimport { getProviderRetryAfterMs } from \"../utils/retry-hints.ts\";\nimport { createStreamDeadline, withStreamDeadline } from \"../utils/stream-deadline.ts\";\nimport { recordThinkingOffFallback } from \"../utils/thinking-off.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\tappendServiceTierRejectedWarning,\n\tapplyServiceTierPricing,\n\tassertPayloadPreservesFastRoute,\n\tconvertResponsesMessages,\n\tconvertResponsesTools,\n\tgetResponsesToolSupport,\n\tisChatGPTSubscriptionToken,\n\tisServiceTierRejection,\n\topenAIServiceTierForRequest,\n\tprocessResponsesStream,\n\ttype ResponsesServiceTier,\n\tresolveChatGPTBackendServiceTier,\n\tresolveRequestedServiceTier,\n} from \"./openai-responses-shared.ts\";\nimport { RetryHintOpenAI } from \"./openai-retry-hint-client.ts\";\nimport { buildBaseOptions, resolveSamplingParams } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-api\", \"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\";\nconst CHATGPT_WORKSPACE_LIMIT_HINT =\n\t\"You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com → Workspace → Usage limits.\";\nconst CONFIGURATION_UPDATE_REQUEST_EFFORT = \"medium\";\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 headerValue(headers: ProviderHeaders | undefined, name: string): string | undefined {\n\tif (!headers) return undefined;\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 value.trim();\n\t}\n\treturn undefined;\n}\n\nfunction hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {\n\treturn headerValue(headers, name) !== undefined;\n}\n\nfunction bearerToken(apiKey: string | undefined, headers: ProviderHeaders | undefined): string | undefined {\n\treturn apiKey ?? headerValue(headers, \"authorization\")?.replace(/^Bearer\\s+/i, \"\");\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\tpromptCacheKeyMode: model.compat?.promptCacheKeyMode ?? \"auto\",\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\tsupportsMidConvoEffort: model.compat?.supportsMidConvoEffort ?? false,\n\t};\n}\n\n/** Effort to send in configuration_update items, or undefined to send it as reasoning.effort. */\nfunction getConfigurationUpdateEffort(\n\tmodel: Model<\"openai-responses\">,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat>,\n): string | undefined {\n\tif (\n\t\t!compat.supportsMidConvoEffort ||\n\t\t!options?.reasoningEffort ||\n\t\t// Sign in with ChatGPT rejects configuration_update items.\n\t\tisChatGPTSignIn(model, options.apiKey) ||\n\t\tisChatGPTSubscriptionToken(bearerToken(options.apiKey, options.headers))\n\t) {\n\t\treturn undefined;\n\t}\n\treturn model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\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 compat = getCompat(model);\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\t\tlet startEmitted = false;\n\n\t\ttry {\n\t\t\tconst thinkingOffFallback =\n\t\t\t\toptions?.reasoningEffort || options?.reasoningSummary\n\t\t\t\t\t? undefined\n\t\t\t\t\t: recordThinkingOffFallback(model, output);\n\t\t\tconst reasoningOptions = thinkingOffFallback ? { ...options, reasoningEffort: thinkingOffFallback } : options;\n\t\t\tconst configurationUpdateEffort = getConfigurationUpdateEffort(model, reasoningOptions, compat);\n\t\t\tif (configurationUpdateEffort !== undefined) output.providerThinkingLevel = configurationUpdateEffort;\n\t\t\t// Create OpenAI client\n\t\t\tconst apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);\n\t\t\tconst chatGPTBackend = isChatGPTSubscriptionToken(bearerToken(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 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?.identity,\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(\n\t\t\t\tmodel,\n\t\t\t\tnormalizedContext,\n\t\t\t\treasoningOptions,\n\t\t\t\tcompat,\n\t\t\t\tgrammarToolInputProperties,\n\t\t\t\tconfigurationUpdateEffort,\n\t\t\t);\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 sendRequest = (requestParams: ResponseCreateParamsStreaming) =>\n\t\t\t\tretryProviderRequest(() => client.responses.create(requestParams, requestOptions).withResponse(), {\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// Every attempt reports its HTTP response before its body is consumed, and the message stream starts\n\t\t\t// once. A streamed request reports a rejected service_tier as an `error` event after HTTP 200, so the\n\t\t\t// response preamble is read before the request counts as accepted.\n\t\t\tconst openStream = async (requestParams: ResponseCreateParamsStreaming) => {\n\t\t\t\tconst { data, response } = await sendRequest(requestParams);\n\t\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\t\tif (!startEmitted) {\n\t\t\t\t\tstartEmitted = true;\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t}\n\t\t\t\treturn readResponsePreamble(withStreamDeadline(data, streamDeadline.deadlineMs, streamDeadline.abort));\n\t\t\t};\n\t\t\tlet requestedServiceTier = resolveOpenAIRequestServiceTier(model, options?.serviceTier);\n\t\t\tlet openaiStream: Awaited<ReturnType<typeof openStream>>;\n\t\t\ttry {\n\t\t\t\topenaiStream = await openStream(params);\n\t\t\t} catch (error) {\n\t\t\t\tif (params.service_tier == null || !isServiceTierRejection(error)) throw error;\n\t\t\t\tconst rejectedServiceTier = params.service_tier;\n\t\t\t\tconst { service_tier: _rejectedServiceTier, ...defaultTierParams } = params;\n\t\t\t\topenaiStream = await openStream(defaultTierParams);\n\t\t\t\trequestedServiceTier = undefined;\n\t\t\t\tappendServiceTierRejectedWarning(output, model, rejectedServiceTier);\n\t\t\t}\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model, {\n\t\t\t\tonProviderStreamEvent: options?.onProviderStreamEvent,\n\t\t\t\tserviceTier: requestedServiceTier,\n\t\t\t\tgrammarToolInputProperties,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t\t...(chatGPTBackend\n\t\t\t\t\t? { resolveServiceTier: resolveChatGPTBackendServiceTier }\n\t\t\t\t\t: { warnOnServiceTierDowngrade: true }),\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\t\t\tconst emptyResponse = githubCopilotEmptyResponse(output);\n\t\t\tif (emptyResponse) throw emptyResponse;\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\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.retryAfterMs = error instanceof Error ? getProviderRetryAfterMs(error) : undefined;\n\t\t\tconst errorMessage = formatProviderError(\n\t\t\t\tnormalizeProviderError(error),\n\t\t\t\t`${model.provider === \"openai\" || model.provider === \"openai-api\" ? \"OpenAI\" : model.provider} API error`,\n\t\t\t);\n\t\t\t// On ChatGPT Business plans, the workspace admin also sets a per-user limit.\n\t\t\tif (errorMessage.includes(\"subscription_sharing_usage_limit_exceeded\")) {\n\t\t\t\toutput.errorMessage = `${errorMessage}\\nCheck your ChatGPT usage: ${CHATGPT_USAGE_URL}`;\n\t\t\t} else if (errorMessage.includes(\"subscription_sharing_workplace_individual_usage_limit_exceeded\")) {\n\t\t\t\toutput.errorMessage = `${errorMessage}\\n${CHATGPT_WORKSPACE_LIMIT_HINT}`;\n\t\t\t} else {\n\t\t\t\toutput.errorMessage = errorMessage;\n\t\t\t}\n\t\t\tif (model.provider === \"github-copilot\") recordGitHubCopilotFailure(output, error, startEmitted);\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\nconst RESPONSE_PREAMBLE_EVENT_TYPES = new Set([\"response.created\", \"response.in_progress\", \"response.queued\"]);\n\nfunction failedResponseTierRejection(event: { type: string } | undefined): Error | undefined {\n\tif (event?.type !== \"response.failed\") return undefined;\n\tconst failure = (event as { response?: { error?: { code?: string | null; message?: string } | null } }).response\n\t\t?.error;\n\tif (!failure?.message) return undefined;\n\tconst error = new Error(failure.message);\n\treturn isServiceTierRejection(error) ? error : undefined;\n}\n\n/**\n * Read a stream up to its first event after the response preamble, so an error the server raises\n * before producing output is thrown here. Returns a stream that replays every event read.\n */\nasync function readResponsePreamble<T extends { type: string }>(events: AsyncIterable<T>): Promise<AsyncIterable<T>> {\n\tconst iterator = events[Symbol.asyncIterator]();\n\tconst preamble: T[] = [];\n\tlet done = false;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst next = await iterator.next();\n\t\t\tif (next.done) {\n\t\t\t\tdone = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpreamble.push(next.value);\n\t\t\tif (!RESPONSE_PREAMBLE_EVENT_TYPES.has(next.value.type)) break;\n\t\t}\n\t} catch (error) {\n\t\tawait iterator.return?.();\n\t\tthrow error;\n\t}\n\tconst tierRejection = failedResponseTierRejection(preamble.at(-1));\n\tif (tierRejection) {\n\t\tawait iterator.return?.();\n\t\tthrow tierRejection;\n\t}\n\treturn (async function* () {\n\t\ttry {\n\t\t\tyield* preamble;\n\t\t\tif (done) return;\n\t\t\tfor (;;) {\n\t\t\t\tconst next = await iterator.next();\n\t\t\t\tif (next.done) return;\n\t\t\t\tyield next.value;\n\t\t\t}\n\t\t} finally {\n\t\t\tawait iterator.return?.();\n\t\t}\n\t})();\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\tidentity?: ClientIdentity,\n\tfetch?: typeof globalThis.fetch,\n\tsessionId?: string,\n\tcopilotApiKey?: string,\n) {\n\tconst compat = getCompat(model);\n\tconst headers: ProviderHeaders = { ...getIdentityHeaders(model, identity), ...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 admitOpenAIRequests(\n\t\tnew RetryHintOpenAI({\n\t\t\tapiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tfetch: getFetchAdmission(fetch)?.fetch ?? fetch,\n\t\t\tdefaultHeaders: headers,\n\t\t}),\n\t\tfetch,\n\t);\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: TranscriptContext,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat>,\n\tgrammarToolInputProperties: ReadonlyMap<string, string>,\n\tconfigurationUpdateEffort: string | undefined,\n) {\n\tconst transcriptTools = resolveTranscriptTools(context.messages, getResponsesToolSupport(compat));\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\tconfigurationUpdateEffort,\n\t});\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);\n\tconst sendPromptCacheKey = cacheRetention !== \"none\" && compat.promptCacheKeyMode !== \"disabled\";\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: sendPromptCacheKey ? clampOpenAIPromptCacheKey(options?.sessionId) : undefined,\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\tconst reasoningEffort = options?.reasoningEffort ?? (options?.reasoningSummary ? \"medium\" : undefined);\n\tif (model.reasoning) {\n\t\tif (reasoningEffort) {\n\t\t\tconst requestedEffort = options?.reasoningEffort\n\t\t\t\t? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n\t\t\t\t: reasoningEffort;\n\t\t\tconst effort = configurationUpdateEffort === undefined ? requestedEffort : CONFIGURATION_UPDATE_REQUEST_EFFORT;\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 (sendsThinkingOffEffort(model)) {\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 model and request sampling parameters override named request fields.\n\tconst samplingParams = resolveSamplingParams(model, reasoningEffort ?? \"off\", options?.samplingParams);\n\tif (samplingParams) {\n\t\tObject.assign(params, samplingParams);\n\t}\n\n\treturn params;\n}\n\n/**\n * Copilot rejected an unlisted `none` effort (earendil-works/pi#2567), so it is sent an off effort only\n * when the model's thinking map lists one.\n */\nfunction sendsThinkingOffEffort(model: Model<\"openai-responses\">): boolean {\n\tconst off = model.thinkingLevelMap?.off;\n\treturn off === undefined ? model.provider !== \"github-copilot\" : off !== null;\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"]}
|
|
1
|
+
{"version":3,"file":"openai-responses.js","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AAC/G,OAAO,EAAE,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAc3F,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,EAAuB,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACvF,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EACN,0BAA0B,EAC1B,qBAAqB,E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C;aAAM,IAAI,sBAAsB,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1C,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,+EAA+E;IAC/E,MAAM,cAAc,GAAG,qBAAqB,CAAC,KAAK,EAAE,eAAe,IAAI,KAAK,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC;IACvG,IAAI,cAAc,EAAE,CAAC;QACpB,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAED;;;GAGG;AACH,SAAS,sBAAsB,CAAC,KAAgC;IAC/D,MAAM,GAAG,GAAG,KAAK,CAAC,gBAAgB,EAAE,GAAG,CAAC;IACxC,OAAO,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,KAAK,gBAAgB,CAAC,CAAC,CAAC,GAAG,KAAK,IAAI,CAAC;AAC/E,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 type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport { githubCopilotEmptyResponse, recordGitHubCopilotFailure } from \"../providers/github-copilot-errors.ts\";\nimport { GitHubCopilotStreamAttempt } from \"../providers/github-copilot-stream-attempt.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} 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 { type ClientIdentity, getIdentityHeaders } from \"../utils/identity.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { admitOpenAIRequests, getFetchAdmission } from \"../utils/request-admission.js\";\nimport { getProviderRetryAfterMs } from \"../utils/retry-hints.ts\";\nimport { createStreamDeadline, withStreamDeadline } from \"../utils/stream-deadline.ts\";\nimport { recordThinkingOffFallback } from \"../utils/thinking-off.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\tappendServiceTierRejectedWarning,\n\tapplyServiceTierPricing,\n\tassertPayloadPreservesFastRoute,\n\tconvertResponsesMessages,\n\tconvertResponsesTools,\n\tgetResponsesToolSupport,\n\tisChatGPTSubscriptionToken,\n\tisServiceTierRejection,\n\topenAIServiceTierForRequest,\n\tprocessResponsesStream,\n\ttype ResponsesServiceTier,\n\tresolveChatGPTBackendServiceTier,\n\tresolveRequestedServiceTier,\n} from \"./openai-responses-shared.ts\";\nimport { RetryHintOpenAI } from \"./openai-retry-hint-client.ts\";\nimport { buildBaseOptions, resolveSamplingParams } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-api\", \"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\";\nconst CHATGPT_WORKSPACE_LIMIT_HINT =\n\t\"You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com → Workspace → Usage limits.\";\nconst CONFIGURATION_UPDATE_REQUEST_EFFORT = \"medium\";\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 headerValue(headers: ProviderHeaders | undefined, name: string): string | undefined {\n\tif (!headers) return undefined;\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 value.trim();\n\t}\n\treturn undefined;\n}\n\nfunction hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {\n\treturn headerValue(headers, name) !== undefined;\n}\n\nfunction bearerToken(apiKey: string | undefined, headers: ProviderHeaders | undefined): string | undefined {\n\treturn apiKey ?? headerValue(headers, \"authorization\")?.replace(/^Bearer\\s+/i, \"\");\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\tpromptCacheKeyMode: model.compat?.promptCacheKeyMode ?? \"auto\",\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\tsupportsMidConvoEffort: model.compat?.supportsMidConvoEffort ?? false,\n\t};\n}\n\n/** Effort to send in configuration_update items, or undefined to send it as reasoning.effort. */\nfunction getConfigurationUpdateEffort(\n\tmodel: Model<\"openai-responses\">,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat>,\n): string | undefined {\n\tif (\n\t\t!compat.supportsMidConvoEffort ||\n\t\t!options?.reasoningEffort ||\n\t\t// Sign in with ChatGPT rejects configuration_update items.\n\t\tisChatGPTSignIn(model, options.apiKey) ||\n\t\tisChatGPTSubscriptionToken(bearerToken(options.apiKey, options.headers))\n\t) {\n\t\treturn undefined;\n\t}\n\treturn model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\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 compat = getCompat(model);\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\t\tconst streamAttempt = new GitHubCopilotStreamAttempt();\n\t\tlet startEmitted = false;\n\n\t\ttry {\n\t\t\tconst thinkingOffFallback =\n\t\t\t\toptions?.reasoningEffort || options?.reasoningSummary\n\t\t\t\t\t? undefined\n\t\t\t\t\t: recordThinkingOffFallback(model, output);\n\t\t\tconst reasoningOptions = thinkingOffFallback ? { ...options, reasoningEffort: thinkingOffFallback } : options;\n\t\t\tconst configurationUpdateEffort = getConfigurationUpdateEffort(model, reasoningOptions, compat);\n\t\t\tif (configurationUpdateEffort !== undefined) output.providerThinkingLevel = configurationUpdateEffort;\n\t\t\t// Create OpenAI client\n\t\t\tconst apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);\n\t\t\tconst chatGPTBackend = isChatGPTSubscriptionToken(bearerToken(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 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?.identity,\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(\n\t\t\t\tmodel,\n\t\t\t\tnormalizedContext,\n\t\t\t\treasoningOptions,\n\t\t\t\tcompat,\n\t\t\t\tgrammarToolInputProperties,\n\t\t\t\tconfigurationUpdateEffort,\n\t\t\t);\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 createRequest = (requestParams: ResponseCreateParamsStreaming) => {\n\t\t\t\tstreamAttempt.begin();\n\t\t\t\treturn client.responses.create(requestParams, requestOptions).withResponse();\n\t\t\t};\n\t\t\tconst sendRequest = (requestParams: ResponseCreateParamsStreaming) =>\n\t\t\t\tretryProviderRequest(() => createRequest(requestParams), {\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// Every attempt reports its HTTP response before its body is consumed, and the message stream starts\n\t\t\t// once. A streamed request reports a rejected service_tier as an `error` event after HTTP 200, so the\n\t\t\t// response preamble is read before the request counts as accepted.\n\t\t\tconst openStream = async (requestParams: ResponseCreateParamsStreaming) => {\n\t\t\t\tconst { data, response } = await sendRequest(requestParams);\n\t\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\t\tif (!startEmitted) {\n\t\t\t\t\tstartEmitted = true;\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t}\n\t\t\t\tstreamAttempt.respond(response.headers);\n\t\t\t\treturn readResponsePreamble(\n\t\t\t\t\tstreamAttempt.observe(withStreamDeadline(data, streamDeadline.deadlineMs, streamDeadline.abort)),\n\t\t\t\t);\n\t\t\t};\n\t\t\tlet requestedServiceTier = resolveOpenAIRequestServiceTier(model, options?.serviceTier);\n\t\t\tlet openaiStream: Awaited<ReturnType<typeof openStream>>;\n\t\t\ttry {\n\t\t\t\topenaiStream = await openStream(params);\n\t\t\t} catch (error) {\n\t\t\t\tif (params.service_tier == null || !isServiceTierRejection(error)) throw error;\n\t\t\t\tconst rejectedServiceTier = params.service_tier;\n\t\t\t\tconst { service_tier: _rejectedServiceTier, ...defaultTierParams } = params;\n\t\t\t\topenaiStream = await openStream(defaultTierParams);\n\t\t\t\trequestedServiceTier = undefined;\n\t\t\t\tappendServiceTierRejectedWarning(output, model, rejectedServiceTier);\n\t\t\t}\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model, {\n\t\t\t\tonProviderStreamEvent: options?.onProviderStreamEvent,\n\t\t\t\tserviceTier: requestedServiceTier,\n\t\t\t\tgrammarToolInputProperties,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t\t...(chatGPTBackend\n\t\t\t\t\t? { resolveServiceTier: resolveChatGPTBackendServiceTier }\n\t\t\t\t\t: { warnOnServiceTierDowngrade: true }),\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\t\t\tconst emptyResponse = githubCopilotEmptyResponse(output);\n\t\t\tif (emptyResponse) throw emptyResponse;\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\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.retryAfterMs = error instanceof Error ? getProviderRetryAfterMs(error) : undefined;\n\t\t\tconst errorMessage = formatProviderError(\n\t\t\t\tnormalizeProviderError(error),\n\t\t\t\t`${model.provider === \"openai\" || model.provider === \"openai-api\" ? \"OpenAI\" : model.provider} API error`,\n\t\t\t);\n\t\t\t// On ChatGPT Business plans, the workspace admin also sets a per-user limit.\n\t\t\tif (errorMessage.includes(\"subscription_sharing_usage_limit_exceeded\")) {\n\t\t\t\toutput.errorMessage = `${errorMessage}\\nCheck your ChatGPT usage: ${CHATGPT_USAGE_URL}`;\n\t\t\t} else if (errorMessage.includes(\"subscription_sharing_workplace_individual_usage_limit_exceeded\")) {\n\t\t\t\toutput.errorMessage = `${errorMessage}\\n${CHATGPT_WORKSPACE_LIMIT_HINT}`;\n\t\t\t} else {\n\t\t\t\toutput.errorMessage = errorMessage;\n\t\t\t}\n\t\t\tif (model.provider === \"github-copilot\") recordGitHubCopilotFailure(output, error, streamAttempt.snapshot());\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\nconst RESPONSE_PREAMBLE_EVENT_TYPES = new Set([\"response.created\", \"response.in_progress\", \"response.queued\"]);\n\nfunction failedResponseTierRejection(event: { type: string } | undefined): Error | undefined {\n\tif (event?.type !== \"response.failed\") return undefined;\n\tconst failure = (event as { response?: { error?: { code?: string | null; message?: string } | null } }).response\n\t\t?.error;\n\tif (!failure?.message) return undefined;\n\tconst error = new Error(failure.message);\n\treturn isServiceTierRejection(error) ? error : undefined;\n}\n\n/**\n * Read a stream up to its first event after the response preamble, so an error the server raises\n * before producing output is thrown here. Returns a stream that replays every event read.\n */\nasync function readResponsePreamble<T extends { type: string }>(events: AsyncIterable<T>): Promise<AsyncIterable<T>> {\n\tconst iterator = events[Symbol.asyncIterator]();\n\tconst preamble: T[] = [];\n\tlet done = false;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst next = await iterator.next();\n\t\t\tif (next.done) {\n\t\t\t\tdone = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpreamble.push(next.value);\n\t\t\tif (!RESPONSE_PREAMBLE_EVENT_TYPES.has(next.value.type)) break;\n\t\t}\n\t} catch (error) {\n\t\tawait iterator.return?.();\n\t\tthrow error;\n\t}\n\tconst tierRejection = failedResponseTierRejection(preamble.at(-1));\n\tif (tierRejection) {\n\t\tawait iterator.return?.();\n\t\tthrow tierRejection;\n\t}\n\treturn (async function* () {\n\t\ttry {\n\t\t\tyield* preamble;\n\t\t\tif (done) return;\n\t\t\tfor (;;) {\n\t\t\t\tconst next = await iterator.next();\n\t\t\t\tif (next.done) return;\n\t\t\t\tyield next.value;\n\t\t\t}\n\t\t} finally {\n\t\t\tawait iterator.return?.();\n\t\t}\n\t})();\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\tidentity?: ClientIdentity,\n\tfetch?: typeof globalThis.fetch,\n\tsessionId?: string,\n\tcopilotApiKey?: string,\n) {\n\tconst compat = getCompat(model);\n\tconst headers: ProviderHeaders = { ...getIdentityHeaders(model, identity), ...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 admitOpenAIRequests(\n\t\tnew RetryHintOpenAI({\n\t\t\tapiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tfetch: getFetchAdmission(fetch)?.fetch ?? fetch,\n\t\t\tdefaultHeaders: headers,\n\t\t}),\n\t\tfetch,\n\t);\n}\n\nfunction buildParams(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: TranscriptContext,\n\toptions: OpenAIResponsesOptions | undefined,\n\tcompat: Required<OpenAIResponsesCompat>,\n\tgrammarToolInputProperties: ReadonlyMap<string, string>,\n\tconfigurationUpdateEffort: string | undefined,\n) {\n\tconst transcriptTools = resolveTranscriptTools(context.messages, getResponsesToolSupport(compat));\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\tconfigurationUpdateEffort,\n\t});\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);\n\tconst sendPromptCacheKey = cacheRetention !== \"none\" && compat.promptCacheKeyMode !== \"disabled\";\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: sendPromptCacheKey ? clampOpenAIPromptCacheKey(options?.sessionId) : undefined,\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\tconst reasoningEffort = options?.reasoningEffort ?? (options?.reasoningSummary ? \"medium\" : undefined);\n\tif (model.reasoning) {\n\t\tif (reasoningEffort) {\n\t\t\tconst requestedEffort = options?.reasoningEffort\n\t\t\t\t? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n\t\t\t\t: reasoningEffort;\n\t\t\tconst effort = configurationUpdateEffort === undefined ? requestedEffort : CONFIGURATION_UPDATE_REQUEST_EFFORT;\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 (sendsThinkingOffEffort(model)) {\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 model and request sampling parameters override named request fields.\n\tconst samplingParams = resolveSamplingParams(model, reasoningEffort ?? \"off\", options?.samplingParams);\n\tif (samplingParams) {\n\t\tObject.assign(params, samplingParams);\n\t}\n\n\treturn params;\n}\n\n/**\n * Copilot rejected an unlisted `none` effort (earendil-works/pi#2567), so it is sent an off effort only\n * when the model's thinking map lists one.\n */\nfunction sendsThinkingOffEffort(model: Model<\"openai-responses\">): boolean {\n\tconst off = model.thinkingLevelMap?.off;\n\treturn off === undefined ? model.provider !== \"github-copilot\" : off !== null;\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"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Returns true when a provider error message says the request's strict tools exceed the provider's limits. */
|
|
2
|
+
export declare function isStrictToolLimitErrorMessage(message: string): boolean;
|
|
3
|
+
/**
|
|
4
|
+
* Records that a session's strict tools exceeded Claude's limits; does nothing without a session. Keeps at most
|
|
5
|
+
* `MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS` sessions.
|
|
6
|
+
*
|
|
7
|
+
* Entries are normally freed by `cleanupSessionResources(sessionId)` when a session ends. The cap bounds memory for
|
|
8
|
+
* library users that never call it; a dropped session just pays one more rejection.
|
|
9
|
+
*/
|
|
10
|
+
export declare function markStrictToolLimitsExceeded(sessionId: string | undefined): void;
|
|
11
|
+
/** Returns true when an earlier request of this session had its strict tools rejected for exceeding Claude's limits. */
|
|
12
|
+
export declare function hasExceededStrictToolLimits(sessionId: string | undefined): boolean;
|
|
13
|
+
//# sourceMappingURL=strict-tool-limits.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"strict-tool-limits.d.ts","sourceRoot":"","sources":["../../src/api/strict-tool-limits.ts"],"names":[],"mappings":"AAYA,+GAA+G;AAC/G,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEtE;AAWD;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAOhF;AAED,wHAAwH;AACxH,wBAAgB,2BAA2B,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAElF"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { registerSessionResourceCleanup } from "../session-resources.js";
|
|
2
|
+
/**
|
|
3
|
+
* Claude rejects (on the Anthropic API and on Bedrock) a request whose strict tools exceed its limits with one of these
|
|
4
|
+
* messages. Observed limits: 20 strict tools, and 16 optional or union-typed parameters across all strict tools.
|
|
5
|
+
*/
|
|
6
|
+
const STRICT_TOOL_LIMIT_ERROR_MESSAGES = [
|
|
7
|
+
"The compiled grammar is too large",
|
|
8
|
+
"Too many strict tools (",
|
|
9
|
+
"Schemas contains too many parameters with union types (",
|
|
10
|
+
];
|
|
11
|
+
/** Returns true when a provider error message says the request's strict tools exceed the provider's limits. */
|
|
12
|
+
export function isStrictToolLimitErrorMessage(message) {
|
|
13
|
+
return STRICT_TOOL_LIMIT_ERROR_MESSAGES.some((limitMessage) => message.includes(limitMessage));
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Sessions whose strict tools Claude rejected for exceeding its limits. Their later requests send `strict: "prefer"`
|
|
17
|
+
* tools non-strict right away: the tool set rarely changes between turns, so trying strict again would only repeat
|
|
18
|
+
* the rejection, and switching back to strict later would rewrite the tool definitions and miss the prompt cache.
|
|
19
|
+
* Shared by the Anthropic and Bedrock providers, which run the same Claude limits.
|
|
20
|
+
*/
|
|
21
|
+
const sessionsOverStrictToolLimits = new Set();
|
|
22
|
+
const MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS = 10_000;
|
|
23
|
+
/**
|
|
24
|
+
* Records that a session's strict tools exceeded Claude's limits; does nothing without a session. Keeps at most
|
|
25
|
+
* `MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS` sessions.
|
|
26
|
+
*
|
|
27
|
+
* Entries are normally freed by `cleanupSessionResources(sessionId)` when a session ends. The cap bounds memory for
|
|
28
|
+
* library users that never call it; a dropped session just pays one more rejection.
|
|
29
|
+
*/
|
|
30
|
+
export function markStrictToolLimitsExceeded(sessionId) {
|
|
31
|
+
if (sessionId === undefined)
|
|
32
|
+
return;
|
|
33
|
+
sessionsOverStrictToolLimits.add(sessionId);
|
|
34
|
+
if (sessionsOverStrictToolLimits.size > MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS) {
|
|
35
|
+
const oldest = sessionsOverStrictToolLimits.values().next().value;
|
|
36
|
+
if (oldest !== undefined)
|
|
37
|
+
sessionsOverStrictToolLimits.delete(oldest);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Returns true when an earlier request of this session had its strict tools rejected for exceeding Claude's limits. */
|
|
41
|
+
export function hasExceededStrictToolLimits(sessionId) {
|
|
42
|
+
return sessionId !== undefined && sessionsOverStrictToolLimits.has(sessionId);
|
|
43
|
+
}
|
|
44
|
+
registerSessionResourceCleanup((sessionId) => {
|
|
45
|
+
if (sessionId)
|
|
46
|
+
sessionsOverStrictToolLimits.delete(sessionId);
|
|
47
|
+
else
|
|
48
|
+
sessionsOverStrictToolLimits.clear();
|
|
49
|
+
});
|
|
50
|
+
//# sourceMappingURL=strict-tool-limits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"strict-tool-limits.js","sourceRoot":"","sources":["../../src/api/strict-tool-limits.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAEzE;;;GAGG;AACH,MAAM,gCAAgC,GAAG;IACxC,mCAAmC;IACnC,yBAAyB;IACzB,yDAAyD;CACzD,CAAC;AAEF,+GAA+G;AAC/G,MAAM,UAAU,6BAA6B,CAAC,OAAe;IAC5D,OAAO,gCAAgC,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC;AAChG,CAAC;AAED;;;;;GAKG;AACH,MAAM,4BAA4B,GAAG,IAAI,GAAG,EAAU,CAAC;AACvD,MAAM,oCAAoC,GAAG,MAAM,CAAC;AAEpD;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAAC,SAA6B;IACzE,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO;IACpC,4BAA4B,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC5C,IAAI,4BAA4B,CAAC,IAAI,GAAG,oCAAoC,EAAE,CAAC;QAC9E,MAAM,MAAM,GAAG,4BAA4B,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;QAClE,IAAI,MAAM,KAAK,SAAS;YAAE,4BAA4B,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACvE,CAAC;AACF,CAAC;AAED,wHAAwH;AACxH,MAAM,UAAU,2BAA2B,CAAC,SAA6B;IACxE,OAAO,SAAS,KAAK,SAAS,IAAI,4BAA4B,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAC/E,CAAC;AAED,8BAA8B,CAAC,CAAC,SAAS,EAAE,EAAE;IAC5C,IAAI,SAAS;QAAE,4BAA4B,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;;QACzD,4BAA4B,CAAC,KAAK,EAAE,CAAC;AAC3C,CAAC,CAAC,CAAC","sourcesContent":["import { registerSessionResourceCleanup } from \"../session-resources.ts\";\n\n/**\n * Claude rejects (on the Anthropic API and on Bedrock) a request whose strict tools exceed its limits with one of these\n * messages. Observed limits: 20 strict tools, and 16 optional or union-typed parameters across all strict tools.\n */\nconst STRICT_TOOL_LIMIT_ERROR_MESSAGES = [\n\t\"The compiled grammar is too large\",\n\t\"Too many strict tools (\",\n\t\"Schemas contains too many parameters with union types (\",\n];\n\n/** Returns true when a provider error message says the request's strict tools exceed the provider's limits. */\nexport function isStrictToolLimitErrorMessage(message: string): boolean {\n\treturn STRICT_TOOL_LIMIT_ERROR_MESSAGES.some((limitMessage) => message.includes(limitMessage));\n}\n\n/**\n * Sessions whose strict tools Claude rejected for exceeding its limits. Their later requests send `strict: \"prefer\"`\n * tools non-strict right away: the tool set rarely changes between turns, so trying strict again would only repeat\n * the rejection, and switching back to strict later would rewrite the tool definitions and miss the prompt cache.\n * Shared by the Anthropic and Bedrock providers, which run the same Claude limits.\n */\nconst sessionsOverStrictToolLimits = new Set<string>();\nconst MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS = 10_000;\n\n/**\n * Records that a session's strict tools exceeded Claude's limits; does nothing without a session. Keeps at most\n * `MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS` sessions.\n *\n * Entries are normally freed by `cleanupSessionResources(sessionId)` when a session ends. The cap bounds memory for\n * library users that never call it; a dropped session just pays one more rejection.\n */\nexport function markStrictToolLimitsExceeded(sessionId: string | undefined): void {\n\tif (sessionId === undefined) return;\n\tsessionsOverStrictToolLimits.add(sessionId);\n\tif (sessionsOverStrictToolLimits.size > MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS) {\n\t\tconst oldest = sessionsOverStrictToolLimits.values().next().value;\n\t\tif (oldest !== undefined) sessionsOverStrictToolLimits.delete(oldest);\n\t}\n}\n\n/** Returns true when an earlier request of this session had its strict tools rejected for exceeding Claude's limits. */\nexport function hasExceededStrictToolLimits(sessionId: string | undefined): boolean {\n\treturn sessionId !== undefined && sessionsOverStrictToolLimits.has(sessionId);\n}\n\nregisterSessionResourceCleanup((sessionId) => {\n\tif (sessionId) sessionsOverStrictToolLimits.delete(sessionId);\n\telse sessionsOverStrictToolLimits.clear();\n});\n"]}
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -16,6 +16,13 @@ export interface ApiKeyCredential {
|
|
|
16
16
|
type: "api_key";
|
|
17
17
|
key?: string;
|
|
18
18
|
env?: ProviderEnv;
|
|
19
|
+
/**
|
|
20
|
+
* GitHub Copilot only: the model IDs the key's account lists in its model picker, saved by a model
|
|
21
|
+
* refresh that read the account's list with this key. A replaced key starts without them.
|
|
22
|
+
*/
|
|
23
|
+
availableModelIds?: string[];
|
|
24
|
+
/** GitHub Copilot only: the fast model IDs the key's account lists. Saved with `availableModelIds`. */
|
|
25
|
+
fastModelIds?: string[];
|
|
19
26
|
}
|
|
20
27
|
/** OAuth token data returned by extension compatibility flows. */
|
|
21
28
|
export interface OAuthCredentials {
|
package/dist/auth/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,EAAE,MAAM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IACpE,WAAW,CAAC,EAAE,MAAM,MAAM,CAAC;IAC3B,qFAAqF;IACrF,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACzB,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IAEb,oFAAoF;IACpF,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB,6FAA6F;IAC7F,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B,KAAK,CAAC,WAAW,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE9F;;;OAGG;IACH,OAAO,CAAC,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAEpF;;;;OAIG;IACH,YAAY,CAAC,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC;IAEpD;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB"}
|
package/dist/auth/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\t\t\topenBrowserOnConfirm?: boolean;\n\t\t\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\t\t\tcopyCodeOnConfirm?: boolean;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Provider ids whose stored api-key credentials this provider reuses, in\n\t * precedence order. A borrowing provider has no stored credential of its\n\t * own; anything stored under its id is ignored. The first\n\t * listed provider with a stored api-key credential that has a key is passed\n\t * to `resolve()` as `credential`; stored OAuth credentials and key-less\n\t * api-key credentials are skipped. When none qualifies, `resolve()` runs\n\t * without a credential, so ambient sources (env vars) still apply. Pair with\n\t * an absent `login`.\n\t */\n\tborrowCredentialsFrom?: readonly string[];\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App context supplied to provider login flows. */\nexport interface LoginOptions {\n\t/** Stable UUID for this installation, created lazily by the app. */\n\tgetDeviceId?: () => string;\n\t/** App name used for OpenAI's agent name hint and Codex browser login originator. */\n\tagentName?: string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tusesCallbackServer?: boolean;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Optional: whether an unexpired stored credential still lacks data that only `refresh`\n\t * restores, such as an account model list an older login never saved. `Models.refresh()` with\n\t * network access refreshes such a credential once per call; request auth is unaffected.\n\t */\n\tneedsRefresh?(credential: OAuthCredential): boolean;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n\t/**\n\t * GitHub Copilot only: the model IDs the key's account lists in its model picker, saved by a model\n\t * refresh that read the account's list with this key. A replaced key starts without them.\n\t */\n\tavailableModelIds?: string[];\n\t/** GitHub Copilot only: the fast model IDs the key's account lists. Saved with `availableModelIds`. */\n\tfastModelIds?: string[];\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\t\t\topenBrowserOnConfirm?: boolean;\n\t\t\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\t\t\tcopyCodeOnConfirm?: boolean;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Provider ids whose stored api-key credentials this provider reuses, in\n\t * precedence order. A borrowing provider has no stored credential of its\n\t * own; anything stored under its id is ignored. The first\n\t * listed provider with a stored api-key credential that has a key is passed\n\t * to `resolve()` as `credential`; stored OAuth credentials and key-less\n\t * api-key credentials are skipped. When none qualifies, `resolve()` runs\n\t * without a credential, so ambient sources (env vars) still apply. Pair with\n\t * an absent `login`.\n\t */\n\tborrowCredentialsFrom?: readonly string[];\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App context supplied to provider login flows. */\nexport interface LoginOptions {\n\t/** Stable UUID for this installation, created lazily by the app. */\n\tgetDeviceId?: () => string;\n\t/** App name used for OpenAI's agent name hint and Codex browser login originator. */\n\tagentName?: string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tusesCallbackServer?: boolean;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Optional: whether an unexpired stored credential still lacks data that only `refresh`\n\t * restores, such as an account model list an older login never saved. `Models.refresh()` with\n\t * network access refreshes such a credential once per call; request auth is unaffected.\n\t */\n\tneedsRefresh?(credential: OAuthCredential): boolean;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Api, Model, SimpleStreamOptions } from "./types.ts";
|
|
2
|
+
/** Whether a refresh is sent ("warm") or warming ends until the next real request ("stop"). */
|
|
3
|
+
export type CacheWarmingAction = "warm" | "stop";
|
|
4
|
+
/** "streaming" while the agent run that sent the request is still active; "idle" after it settled. */
|
|
5
|
+
export type CacheWarmingPhase = "streaming" | "idle";
|
|
6
|
+
/** Inputs and outcome of one warm-or-stop decision. */
|
|
7
|
+
export interface CacheWarmingDecision {
|
|
8
|
+
phase: CacheWarmingPhase;
|
|
9
|
+
/** Price of this refresh: a cache read of the prompt plus one output token. */
|
|
10
|
+
warmCost: number;
|
|
11
|
+
/** Extra price of the next real request if the cache entry is lost. */
|
|
12
|
+
missCost: number;
|
|
13
|
+
/** Estimated chance that a real request arrives before the entry expires. */
|
|
14
|
+
continuationProbability: number;
|
|
15
|
+
/** `continuationProbability * missCost - warmCost`. */
|
|
16
|
+
expectedSavings: number;
|
|
17
|
+
/** False when the prompt size or the model's prices are unknown. */
|
|
18
|
+
economicsAvailable: boolean;
|
|
19
|
+
/** "warm" when `expectedSavings` is at least `CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS`. */
|
|
20
|
+
action: CacheWarmingAction;
|
|
21
|
+
}
|
|
22
|
+
/** Streaming warming never continues past this long after the real request that started it. */
|
|
23
|
+
export declare const CACHE_WARMING_MAX_AGE_MS: number;
|
|
24
|
+
/** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */
|
|
25
|
+
export declare const CACHE_WARMING_MAX_IDLE_AGE_MS: number;
|
|
26
|
+
/** A refresh is sent only when it is expected to save at least this many dollars. */
|
|
27
|
+
export declare const CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;
|
|
28
|
+
/**
|
|
29
|
+
* Chance that a real request arrives before the cache entry expires while the agent sits idle. Measured from our own
|
|
30
|
+
* usage; per-session estimates were not better than this constant.
|
|
31
|
+
*/
|
|
32
|
+
export declare const CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY = 0.15;
|
|
33
|
+
/** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */
|
|
34
|
+
export declare function getCacheWarmingDelayMs(ttlMs: number): number | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* Lifetime of the prompt cache entry a request writes, from the model's `promptCache` tier for the retention the
|
|
37
|
+
* request used. Undefined when the model has no lifetime for that tier or caching is off.
|
|
38
|
+
*/
|
|
39
|
+
export declare function getPromptCacheTtlMs(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Whether replaying the request with a one-token output cap leaves its cache entry untouched. Anthropic's budget-based
|
|
42
|
+
* thinking (Claude models without adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay would get a
|
|
43
|
+
* different budget, which Anthropic keys the message cache on, and the model could still think for thousands of tokens.
|
|
44
|
+
*/
|
|
45
|
+
export declare function isCacheWarmingReplayable(model: Model<Api>, options: SimpleStreamOptions | undefined): boolean;
|
|
46
|
+
/**
|
|
47
|
+
* The options of a refresh: the request's own, capped at one output token, without retries, and without replacing the
|
|
48
|
+
* conversation's provider thread state (the refresh repeats the last request).
|
|
49
|
+
*/
|
|
50
|
+
export declare function getCacheWarmingRequestOptions<T extends SimpleStreamOptions>(options: T, signal: AbortSignal): T;
|
|
51
|
+
/** Decide whether refreshing the cache entry of a `promptTokens`-token request pays for itself in `phase`. */
|
|
52
|
+
export declare function evaluateCacheWarming(model: Model<Api>, promptTokens: number, phase: CacheWarmingPhase): CacheWarmingDecision;
|
|
53
|
+
//# sourceMappingURL=cache-warming.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-warming.d.ts","sourceRoot":"","sources":["../src/cache-warming.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,mBAAmB,EAAS,MAAM,YAAY,CAAC;AAGzE,+FAA+F;AAC/F,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,MAAM,CAAC;AAEjD,sGAAsG;AACtG,MAAM,MAAM,iBAAiB,GAAG,WAAW,GAAG,MAAM,CAAC;AAErD,uDAAuD;AACvD,MAAM,WAAW,oBAAoB;IACpC,KAAK,EAAE,iBAAiB,CAAC;IACzB,+EAA+E;IAC/E,QAAQ,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,QAAQ,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,uBAAuB,EAAE,MAAM,CAAC;IAChC,uDAAuD;IACvD,eAAe,EAAE,MAAM,CAAC;IACxB,oEAAoE;IACpE,kBAAkB,EAAE,OAAO,CAAC;IAC5B,0FAA0F;IAC1F,MAAM,EAAE,kBAAkB,CAAC;CAC3B;AAED,+FAA+F;AAC/F,eAAO,MAAM,wBAAwB,QAAc,CAAC;AAEpD,wGAAwG;AACxG,eAAO,MAAM,6BAA6B,QAAc,CAAC;AAEzD,qFAAqF;AACrF,eAAO,MAAM,sCAAsC,OAAO,CAAC;AAE3D;;;GAGG;AACH,eAAO,MAAM,2CAA2C,OAAO,CAAC;AAEhE,iFAAiF;AACjF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGxE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,mBAAmB,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAOnH;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,mBAAmB,GAAG,SAAS,GAAG,OAAO,CAG7G;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,CAAC,SAAS,mBAAmB,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,CAAC,CAE/G;AAED,8GAA8G;AAC9G,wBAAgB,oBAAoB,CACnC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,iBAAiB,GACtB,oBAAoB,CAoBtB"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Prompt cache warming policy shared by pi's hosts: when a refresh is due, whether a request can be replayed, and
|
|
2
|
+
// whether a refresh pays for itself. Hosts own the scheduling; this module owns the numbers.
|
|
3
|
+
import { calculateCost } from "./models.js";
|
|
4
|
+
import { getProviderEnvValue } from "./utils/provider-env.js";
|
|
5
|
+
/** Streaming warming never continues past this long after the real request that started it. */
|
|
6
|
+
export const CACHE_WARMING_MAX_AGE_MS = 60 * 60_000;
|
|
7
|
+
/** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */
|
|
8
|
+
export const CACHE_WARMING_MAX_IDLE_AGE_MS = 30 * 60_000;
|
|
9
|
+
/** A refresh is sent only when it is expected to save at least this many dollars. */
|
|
10
|
+
export const CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;
|
|
11
|
+
/**
|
|
12
|
+
* Chance that a real request arrives before the cache entry expires while the agent sits idle. Measured from our own
|
|
13
|
+
* usage; per-session estimates were not better than this constant.
|
|
14
|
+
*/
|
|
15
|
+
export const CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY = 0.15;
|
|
16
|
+
/** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */
|
|
17
|
+
export function getCacheWarmingDelayMs(ttlMs) {
|
|
18
|
+
if (ttlMs <= 10_000)
|
|
19
|
+
return undefined;
|
|
20
|
+
return Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Lifetime of the prompt cache entry a request writes, from the model's `promptCache` tier for the retention the
|
|
24
|
+
* request used. Undefined when the model has no lifetime for that tier or caching is off.
|
|
25
|
+
*/
|
|
26
|
+
export function getPromptCacheTtlMs(model, options) {
|
|
27
|
+
const retention = options?.cacheRetention ??
|
|
28
|
+
(getProviderEnvValue("PI_CACHE_RETENTION", options?.env) === "long" ? "long" : "short");
|
|
29
|
+
if (retention === "none")
|
|
30
|
+
return undefined;
|
|
31
|
+
const seconds = model.promptCache?.[retention];
|
|
32
|
+
return seconds === undefined ? undefined : seconds * 1000;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Whether replaying the request with a one-token output cap leaves its cache entry untouched. Anthropic's budget-based
|
|
36
|
+
* thinking (Claude models without adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay would get a
|
|
37
|
+
* different budget, which Anthropic keys the message cache on, and the model could still think for thousands of tokens.
|
|
38
|
+
*/
|
|
39
|
+
export function isCacheWarmingReplayable(model, options) {
|
|
40
|
+
if (!options?.reasoning || model.api !== "anthropic-messages")
|
|
41
|
+
return true;
|
|
42
|
+
return model.compat?.forceAdaptiveThinking === true;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The options of a refresh: the request's own, capped at one output token, without retries, and without replacing the
|
|
46
|
+
* conversation's provider thread state (the refresh repeats the last request).
|
|
47
|
+
*/
|
|
48
|
+
export function getCacheWarmingRequestOptions(options, signal) {
|
|
49
|
+
return { ...options, maxTokens: 1, disableContinuation: true, maxRetries: 0, signal };
|
|
50
|
+
}
|
|
51
|
+
/** Decide whether refreshing the cache entry of a `promptTokens`-token request pays for itself in `phase`. */
|
|
52
|
+
export function evaluateCacheWarming(model, promptTokens, phase) {
|
|
53
|
+
const cacheHitCost = price(model, { cacheRead: promptTokens });
|
|
54
|
+
const cacheMissCost = price(model, model.cost.cacheWrite > 0 ? { cacheWrite: promptTokens } : { input: promptTokens });
|
|
55
|
+
const warmCost = price(model, { cacheRead: promptTokens, output: 1 });
|
|
56
|
+
const missCost = Math.max(0, cacheMissCost - cacheHitCost);
|
|
57
|
+
const continuationProbability = phase === "idle" ? CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY : 1;
|
|
58
|
+
const economicsAvailable = promptTokens > 0 && (cacheHitCost > 0 || cacheMissCost > 0);
|
|
59
|
+
const expectedSavings = continuationProbability * missCost - warmCost;
|
|
60
|
+
return {
|
|
61
|
+
phase,
|
|
62
|
+
warmCost,
|
|
63
|
+
missCost,
|
|
64
|
+
continuationProbability,
|
|
65
|
+
expectedSavings,
|
|
66
|
+
economicsAvailable,
|
|
67
|
+
action: expectedSavings >= CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS ? "warm" : "stop",
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function price(model, tokens) {
|
|
71
|
+
const usage = {
|
|
72
|
+
input: 0,
|
|
73
|
+
output: 0,
|
|
74
|
+
cacheRead: 0,
|
|
75
|
+
cacheWrite: 0,
|
|
76
|
+
totalTokens: 0,
|
|
77
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
78
|
+
...tokens,
|
|
79
|
+
};
|
|
80
|
+
return calculateCost(model, usage).total;
|
|
81
|
+
}
|
|
82
|
+
//# sourceMappingURL=cache-warming.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-warming.js","sourceRoot":"","sources":["../src/cache-warming.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,6FAA6F;AAC7F,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAyB9D,+FAA+F;AAC/F,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,GAAG,MAAM,CAAC;AAEpD,wGAAwG;AACxG,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,GAAG,MAAM,CAAC;AAEzD,qFAAqF;AACrF,MAAM,CAAC,MAAM,sCAAsC,GAAG,IAAI,CAAC;AAE3D;;;GAGG;AACH,MAAM,CAAC,MAAM,2CAA2C,GAAG,IAAI,CAAC;AAEhE,iFAAiF;AACjF,MAAM,UAAU,sBAAsB,CAAC,KAAa;IACnD,IAAI,KAAK,IAAI,MAAM;QAAE,OAAO,SAAS,CAAC;IACtC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,GAAG,EAAE,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAiB,EAAE,OAAwC;IAC9F,MAAM,SAAS,GACd,OAAO,EAAE,cAA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C,KAAK,EAAE,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;IACtE,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,aAAa,GAAG,YAAY,CAAC,CAAC;IAC3D,MAAM,uBAAuB,GAAG,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,2CAA2C,CAAC,CAAC,CAAC,CAAC,CAAC;IACnG,MAAM,kBAAkB,GAAG,YAAY,GAAG,CAAC,IAAI,CAAC,YAAY,GAAG,CAAC,IAAI,aAAa,GAAG,CAAC,CAAC,CAAC;IACvF,MAAM,eAAe,GAAG,uBAAuB,GAAG,QAAQ,GAAG,QAAQ,CAAC;IACtE,OAAO;QACN,KAAK;QACL,QAAQ;QACR,QAAQ;QACR,uBAAuB;QACvB,eAAe;QACf,kBAAkB;QAClB,MAAM,EAAE,eAAe,IAAI,sCAAsC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM;KACnF,CAAC;AACH,CAAC;AAED,SAAS,KAAK,CACb,KAAiB,EACjB,MAA6E;IAE7E,MAAM,KAAK,GAAU;QACpB,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;QACpE,GAAG,MAAM;KACT,CAAC;IACF,OAAO,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC;AAC1C,CAAC","sourcesContent":["// Prompt cache warming policy shared by pi's hosts: when a refresh is due, whether a request can be replayed, and\n// whether a refresh pays for itself. Hosts own the scheduling; this module owns the numbers.\nimport { calculateCost } from \"./models.ts\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"./types.ts\";\nimport { getProviderEnvValue } from \"./utils/provider-env.ts\";\n\n/** Whether a refresh is sent (\"warm\") or warming ends until the next real request (\"stop\"). */\nexport type CacheWarmingAction = \"warm\" | \"stop\";\n\n/** \"streaming\" while the agent run that sent the request is still active; \"idle\" after it settled. */\nexport type CacheWarmingPhase = \"streaming\" | \"idle\";\n\n/** Inputs and outcome of one warm-or-stop decision. */\nexport interface CacheWarmingDecision {\n\tphase: CacheWarmingPhase;\n\t/** Price of this refresh: a cache read of the prompt plus one output token. */\n\twarmCost: number;\n\t/** Extra price of the next real request if the cache entry is lost. */\n\tmissCost: number;\n\t/** Estimated chance that a real request arrives before the entry expires. */\n\tcontinuationProbability: number;\n\t/** `continuationProbability * missCost - warmCost`. */\n\texpectedSavings: number;\n\t/** False when the prompt size or the model's prices are unknown. */\n\teconomicsAvailable: boolean;\n\t/** \"warm\" when `expectedSavings` is at least `CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS`. */\n\taction: CacheWarmingAction;\n}\n\n/** Streaming warming never continues past this long after the real request that started it. */\nexport const CACHE_WARMING_MAX_AGE_MS = 60 * 60_000;\n\n/** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */\nexport const CACHE_WARMING_MAX_IDLE_AGE_MS = 30 * 60_000;\n\n/** A refresh is sent only when it is expected to save at least this many dollars. */\nexport const CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;\n\n/**\n * Chance that a real request arrives before the cache entry expires while the agent sits idle. Measured from our own\n * usage; per-session estimates were not better than this constant.\n */\nexport const CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY = 0.15;\n\n/** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */\nexport function getCacheWarmingDelayMs(ttlMs: number): number | undefined {\n\tif (ttlMs <= 10_000) return undefined;\n\treturn Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));\n}\n\n/**\n * Lifetime of the prompt cache entry a request writes, from the model's `promptCache` tier for the retention the\n * request used. Undefined when the model has no lifetime for that tier or caching is off.\n */\nexport function getPromptCacheTtlMs(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined {\n\tconst retention =\n\t\toptions?.cacheRetention ??\n\t\t(getProviderEnvValue(\"PI_CACHE_RETENTION\", options?.env) === \"long\" ? \"long\" : \"short\");\n\tif (retention === \"none\") return undefined;\n\tconst seconds = model.promptCache?.[retention];\n\treturn seconds === undefined ? undefined : seconds * 1000;\n}\n\n/**\n * Whether replaying the request with a one-token output cap leaves its cache entry untouched. Anthropic's budget-based\n * thinking (Claude models without adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay would get a\n * different budget, which Anthropic keys the message cache on, and the model could still think for thousands of tokens.\n */\nexport function isCacheWarmingReplayable(model: Model<Api>, options: SimpleStreamOptions | undefined): boolean {\n\tif (!options?.reasoning || model.api !== \"anthropic-messages\") return true;\n\treturn (model as Model<\"anthropic-messages\">).compat?.forceAdaptiveThinking === true;\n}\n\n/**\n * The options of a refresh: the request's own, capped at one output token, without retries, and without replacing the\n * conversation's provider thread state (the refresh repeats the last request).\n */\nexport function getCacheWarmingRequestOptions<T extends SimpleStreamOptions>(options: T, signal: AbortSignal): T {\n\treturn { ...options, maxTokens: 1, disableContinuation: true, maxRetries: 0, signal };\n}\n\n/** Decide whether refreshing the cache entry of a `promptTokens`-token request pays for itself in `phase`. */\nexport function evaluateCacheWarming(\n\tmodel: Model<Api>,\n\tpromptTokens: number,\n\tphase: CacheWarmingPhase,\n): CacheWarmingDecision {\n\tconst cacheHitCost = price(model, { cacheRead: promptTokens });\n\tconst cacheMissCost = price(\n\t\tmodel,\n\t\tmodel.cost.cacheWrite > 0 ? { cacheWrite: promptTokens } : { input: promptTokens },\n\t);\n\tconst warmCost = price(model, { cacheRead: promptTokens, output: 1 });\n\tconst missCost = Math.max(0, cacheMissCost - cacheHitCost);\n\tconst continuationProbability = phase === \"idle\" ? CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY : 1;\n\tconst economicsAvailable = promptTokens > 0 && (cacheHitCost > 0 || cacheMissCost > 0);\n\tconst expectedSavings = continuationProbability * missCost - warmCost;\n\treturn {\n\t\tphase,\n\t\twarmCost,\n\t\tmissCost,\n\t\tcontinuationProbability,\n\t\texpectedSavings,\n\t\teconomicsAvailable,\n\t\taction: expectedSavings >= CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS ? \"warm\" : \"stop\",\n\t};\n}\n\nfunction price(\n\tmodel: Model<Api>,\n\ttokens: Partial<Pick<Usage, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\">>,\n): number {\n\tconst usage: Usage = {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t...tokens,\n\t};\n\treturn calculateCost(model, usage).total;\n}\n"]}
|
|
@@ -53,7 +53,13 @@ export declare class ImageGenerationError extends Error {
|
|
|
53
53
|
private dataWithCauses;
|
|
54
54
|
toJSON(): ImageGenerationErrorData;
|
|
55
55
|
}
|
|
56
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Why an option was rejected. The first seven are found before a request is sent. The last three
|
|
58
|
+
* come from the API's own rejection of an option: `required-by-api` (the API needs an option the
|
|
59
|
+
* request did not carry), `rejected-by-api` (the API refused the option's value) and
|
|
60
|
+
* `unsupported-by-api` (the API does not accept the option for this account or model).
|
|
61
|
+
*/
|
|
62
|
+
export type ImageGenerationConfigReason = "out-of-range" | "requires-option" | "conflicts-with-option" | "generation-only" | "unsupported-by-model" | "requires-base-image" | "duplicate-role" | "required-by-api" | "rejected-by-api" | "unsupported-by-api";
|
|
57
63
|
export interface ImageGenerationConfigErrorInit {
|
|
58
64
|
model: string;
|
|
59
65
|
field: string;
|
|
@@ -66,8 +72,9 @@ export interface ImageGenerationConfigErrorInit {
|
|
|
66
72
|
cause?: unknown;
|
|
67
73
|
}
|
|
68
74
|
/**
|
|
69
|
-
* The request options or input are invalid.
|
|
70
|
-
*
|
|
75
|
+
* The request options or input are invalid. Found before any request is sent, or reported by the
|
|
76
|
+
* API as a rejected option (`reason` `required-by-api`, `rejected-by-api` or `unsupported-by-api`).
|
|
77
|
+
* Either way nothing was billed and retrying the same request fails the same way.
|
|
71
78
|
*/
|
|
72
79
|
export declare class ImageGenerationConfigError extends ImageGenerationError {
|
|
73
80
|
readonly name: "ImageGenerationConfigError";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image-generation-error.d.ts","sourceRoot":"","sources":["../src/image-generation-error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,8BAA8B,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;AAEvG,gFAAgF;AAChF,MAAM,WAAW,+BAA+B;IAC/C,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,wBAAwB,GAAG,+BAA+B,CAAC;CACnE;AAED,iGAAiG;AACjG,MAAM,WAAW,wBAAwB;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,8BAA8B,CAAC,CAAC;IACvD;;;OAGG;IACH,KAAK,CAAC,EAAE,wBAAwB,GAAG,+BAA+B,CAAC;CACnE;AAED,UAAU,wBAAwB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,KAAK,CAAC,EAAE,OAAO,CAAC;CAChB;AAoED,oDAAoD;AACpD,qBAAa,oBAAqB,SAAQ,KAAK;IAC9C,SAAkB,IAAI,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,sEAAsE;IACtE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAEvB,YAAY,IAAI,EAAE,wBAAwB,EAMzC;IAED,iGAAiG;IACjG,SAAS,CAAC,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,8BAA8B,CAAC,CAErE;IAED,MAAM,IAAI,wBAAwB,CAEjC;IAED,OAAO,CAAC,MAAM,CAAC,SAAS;IAgBxB,OAAO,CAAC,cAAc;IAatB,MAAM,IAAI,wBAAwB,CAEjC;CACD;AAED,MAAM,MAAM,2BAA2B,GACpC,cAAc,GACd,iBAAiB,GACjB,uBAAuB,GACvB,iBAAiB,GACjB,sBAAsB,GACtB,qBAAqB,GACrB,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"image-generation-error.d.ts","sourceRoot":"","sources":["../src/image-generation-error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,8BAA8B,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;AAEvG,gFAAgF;AAChF,MAAM,WAAW,+BAA+B;IAC/C,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,wBAAwB,GAAG,+BAA+B,CAAC;CACnE;AAED,iGAAiG;AACjG,MAAM,WAAW,wBAAwB;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,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