@codeworksh/aikit 0.10.0 → 0.11.0-dev.20261012163102
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/cli.mjs +3 -3
- package/{copilot-bFammM5T.mjs → copilot-JLgwmznn.mjs} +2 -2
- package/{copilot-bFammM5T.mjs.map → copilot-JLgwmznn.mjs.map} +1 -1
- package/{copilot-headers-01-kLz8g.mjs → copilot-headers-BvQ3FFn-.mjs} +2 -2
- package/{copilot-headers-01-kLz8g.mjs.map → copilot-headers-BvQ3FFn-.mjs.map} +1 -1
- package/{failure-CN0horoO.mjs → failure-DFQNKc-O.mjs} +23 -6
- package/failure-DFQNKc-O.mjs.map +1 -0
- package/{github-copilot-eDhLBMfL.mjs → github-copilot-C7oJ2Tfp.mjs} +2 -2
- package/{github-copilot-eDhLBMfL.mjs.map → github-copilot-C7oJ2Tfp.mjs.map} +1 -1
- package/github-copilot-CLJx-bcP.mjs +3 -0
- package/index.d.mts +46 -6
- package/index.mjs +238 -16
- package/index.mjs.map +1 -1
- package/llm/failure.mjs +1 -1
- package/{model-Czo0SKj0.mjs → model-D-FoGzVN.mjs} +5 -3
- package/model-D-FoGzVN.mjs.map +1 -0
- package/{model-yhqJA3dm.d.mts → model-DCfjY0fS.d.mts} +2 -2
- package/{modelgen-BHm-jA64.mjs → modelgen-D6UBM1fq.mjs} +5 -5
- package/modelgen-D6UBM1fq.mjs.map +1 -0
- package/modelgen.d.mts +1 -1
- package/modelgen.mjs +1 -1
- package/oauth/github/copilot.mjs +1 -1
- package/openai-codex-CIBVNhQx.mjs +2 -0
- package/{openai-codex-MpxV35tx.mjs → openai-codex-Dj0oh0UV.mjs} +26 -15
- package/openai-codex-Dj0oh0UV.mjs.map +1 -0
- package/package.json +1 -1
- package/{registry-CZtcfRPL.mjs → registry-CfGgGfSs.mjs} +4 -4
- package/{registry-CZtcfRPL.mjs.map → registry-CfGgGfSs.mjs.map} +1 -1
- package/failure-CN0horoO.mjs.map +0 -1
- package/github-copilot-gMaBI_-X.mjs +0 -3
- package/model-Czo0SKj0.mjs.map +0 -1
- package/modelgen-BHm-jA64.mjs.map +0 -1
- package/openai-codex-CvdfMYoU.mjs +0 -2
- package/openai-codex-MpxV35tx.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-codex-Dj0oh0UV.mjs","names":["Type","Model.KnownProviderEnumSchema","Model.ProviderInfo","Model.ThinkingLevel","Failure.FailureSchema","asRecord","asString"],"sources":["../../src/message/message.ts","../../src/providers/openai-codex/codex-tools.ts","../../src/utils/hash.ts","../../src/providers/openai-codex/codex-error.ts","../../src/providers/openai-codex/codex-prompt.ts","../../src/providers/openai-codex/codex-sse.ts","../../src/providers/openai-codex/codex-usage.ts","../../src/providers/openai-codex/codex-language-model.ts","../../src/providers/openai-codex/codex-provider.ts"],"sourcesContent":["import Type, { type Static, type TSchema } from \"typebox\";\nimport { uuidv7 } from \"uuidv7\";\nimport * as Failure from \"../llm/failure/schema.ts\";\nimport * as Model from \"../model/model.ts\";\n\nexport const TextContentSchema = Type.Object({\n\ttype: Type.Literal(\"text\"),\n\ttext: Type.String(),\n\ttextSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the message ID\n});\nexport type TextContent = Static<typeof TextContentSchema>;\n\nexport const ImageContentSchema = Type.Object({\n\ttype: Type.Literal(\"image\"),\n\tdata: Type.String(), // base64 encoded image data\n\tmimeType: Type.String(), // e.g., \"image/jpeg\", \"image/png\"\n});\nexport type ImageContent = Static<typeof ImageContentSchema>;\n\nexport const ThinkingContentSchema = Type.Object({\n\ttype: Type.Literal(\"thinking\"),\n\tthinking: Type.String(),\n\t// Provider-native replay data: an Anthropic signature, serialized OpenAI\n\t// reasoning metadata, or a serialized OpenAI Codex reasoning item.\n\tthinkingSignature: Type.Optional(Type.String()),\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted: Type.Optional(Type.Boolean()),\n});\nexport type ThinkingContent = Static<typeof ThinkingContentSchema>;\n\nexport const ToolCallBaseSchema = Type.Object({\n\ttype: Type.Literal(\"toolCall\"),\n\tcallID: Type.String(),\n\tname: Type.String(),\n\targuments: Type.Record(Type.String(), Type.Any()),\n\tthoughtSignature: Type.Optional(Type.String()), // Google-specific: opaque signature for reusing thought context\n\tnamespace: Type.Optional(Type.String()), // OpenAI Responses namespace for dynamically loaded tools\n\t/** Names from Context.tools that became available after this tool result. */\n\taddedToolNames: Type.Optional(Type.Array(Type.String())),\n\ttime: Type.Object({\n\t\tstart: Type.Number(), // Unix timestamp in milliseconds\n\t\tend: Type.Number(), // Unix timestamp in milliseconds, last known lifecycle update\n\t}),\n});\n\nexport const ToolSuccessResult = Type.Object({\n\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\tdetails: Type.Optional(Type.Any()),\n\tisError: Type.Literal(false),\n});\nexport const ToolErrorResult = Type.Object({\n\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\tdetails: Type.Optional(Type.Any()),\n\tisError: Type.Literal(true),\n});\nexport const ToolRunningPartial = Type.Object({\n\tcontent: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),\n\tdetails: Type.Optional(Type.Any()),\n});\n\nexport const ToolStatusEnum = {\n\tpending: \"pending\",\n\trunning: \"running\",\n\tcompleted: \"completed\",\n\terror: \"error\",\n\tskipped: \"skipped\",\n\taborted: \"aborted\",\n} as const;\n\nexport const ToolRunningSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.running),\n\tpartial: Type.Optional(ToolRunningPartial),\n});\nexport const ToolCompletedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.completed),\n\tresult: ToolSuccessResult,\n});\nexport const ToolErrorSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.error),\n\tresult: ToolErrorResult,\n});\nexport const ToolSkippedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.skipped),\n\tresult: ToolErrorResult,\n});\nexport const ToolAbortedSchema = Type.Object({\n\tstatus: Type.Literal(ToolStatusEnum.aborted),\n\tresult: ToolErrorResult,\n});\n\nexport const ToolCallPendingPartSchema = Type.Intersect([\n\tToolCallBaseSchema,\n\tType.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.pending),\n\t}),\n]);\nexport const ToolCallRunningPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolRunningSchema]));\nexport const ToolCallCompletedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));\nexport const ToolCallErrorPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolErrorSchema]));\nexport const ToolCallSkippedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));\nexport const ToolCallAbortedPartSchema = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));\nexport const ToolCallTerminalPartSchema = Type.Union([\n\tToolCallCompletedPartSchema,\n\tToolCallErrorPartSchema,\n\tToolCallSkippedPartSchema,\n\tToolCallAbortedPartSchema,\n]);\n\nexport const ToolCallInFlightSchema = Type.Object({\n\tcallID: Type.String(),\n\tname: Type.String(),\n\trawArgs: Type.Record(Type.String(), Type.Unknown()),\n\targs: Type.Optional(Type.Unknown()),\n});\nexport type ToolCallInFlight = Static<typeof ToolCallInFlightSchema>;\n\nexport const ToolCallSchema = Type.Union([\n\tToolCallPendingPartSchema,\n\tToolCallRunningPartSchema,\n\tToolCallTerminalPartSchema,\n]);\n\nexport type ToolCall = Static<typeof ToolCallSchema>;\nexport type ToolCallPendingPart = Static<typeof ToolCallPendingPartSchema>;\nexport type ToolCallRunningPart = Static<typeof ToolCallRunningPartSchema>;\nexport type ToolCallCompletedPart = Static<typeof ToolCallCompletedPartSchema>;\nexport type ToolCallErrorPart = Static<typeof ToolCallErrorPartSchema>;\nexport type ToolCallSkippedPart = Static<typeof ToolCallSkippedPartSchema>;\nexport type ToolCallAbortedPart = Static<typeof ToolCallAbortedPartSchema>;\nexport type ToolCallTerminalPart = Static<typeof ToolCallTerminalPartSchema>;\n\nexport const UsageSchema = Type.Object({\n\tinput: Type.Number(),\n\toutput: Type.Number(),\n\tcacheRead: Type.Number(),\n\tcacheWrite: Type.Number(),\n\t/** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */\n\tcacheWrite1h: Type.Optional(Type.Number()),\n\treasoning: Type.Optional(Type.Number()),\n\ttotalTokens: Type.Number(),\n\tcost: Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t\ttotal: Type.Number(),\n\t}),\n});\nexport type Usage = Static<typeof UsageSchema>;\n\nexport const StopReasonSchema = Type.Union([\n\tType.Literal(\"stop\"),\n\tType.Literal(\"length\"),\n\tType.Literal(\"toolUse\"),\n\tType.Literal(\"error\"),\n\tType.Literal(\"aborted\"),\n]);\nexport type StopReason = Static<typeof StopReasonSchema>;\n\nexport const UserMessageSchema = Type.Object({\n\tmessageId: Type.String(),\n\trole: Type.Literal(\"user\"),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t}),\n\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n});\nexport type UserMessage = Static<typeof UserMessageSchema>;\n\nexport const AssistantMessageSchema = Type.Object({\n\trole: Type.Literal(\"assistant\"),\n\tprotocol: Model.KnownProviderEnumSchema,\n\tprovider: Model.ProviderInfo,\n\tmodel: Type.String(),\n\t/** Thinking level the caller requested, before aikit fits it to the model. */\n\tthinkingLevel: Model.ThinkingLevel,\n\t/** Provider-native thinking value the request carried. Absent for budget-only or unmanaged reasoning. */\n\tproviderThinkingLevel: Type.Optional(Type.String()),\n\tusage: UsageSchema,\n\tstopReason: StopReasonSchema,\n\terrorMessage: Type.Optional(Type.String()),\n\t/**\n\t * Structured, provider-independent failure details for a failed request.\n\t * The schema is based on ai-sdk as the underlying provider wire protocol.\n\t * Depends on ai-sdk\n\t */\n\tfailure: Type.Optional(Failure.FailureSchema),\n\ttime: Type.Object({\n\t\tcreated: Type.Number(),\n\t\tcompleted: Type.Number(),\n\t}),\n\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema, ThinkingContentSchema, ToolCallSchema])),\n\tresponseId: Type.Optional(Type.String()), // Provider-specific response/message identifier when the upstream API exposes one\n\tresponseModel: Type.Optional(Type.String()), // Concrete routed model identifier when it differs from the requested model\n\tmessageId: Type.String(),\n});\nexport type AssistantMessage = Static<typeof AssistantMessageSchema>;\n\nexport const MessageSchema = Type.Union([UserMessageSchema, AssistantMessageSchema]);\nexport type Message = Static<typeof MessageSchema>;\n\ntype UserMessageInit = Omit<UserMessage, \"messageId\"> & {\n\tmessageId?: string;\n};\n\ntype AssistantMessageInit = Omit<AssistantMessage, \"messageId\"> & {\n\tmessageId?: string;\n};\n\nexport function createMessageId(): string {\n\treturn uuidv7();\n}\n\nexport function createUserMessage(message: UserMessageInit): UserMessage {\n\tconst { messageId = createMessageId(), ...rest } = message;\n\treturn {\n\t\tmessageId,\n\t\t...rest,\n\t};\n}\n\nexport function createAssistantMessage(message: AssistantMessageInit): AssistantMessage {\n\tconst { messageId = createMessageId(), ...rest } = message;\n\treturn {\n\t\tmessageId,\n\t\t...rest,\n\t};\n}\n\nexport const GrammarVariantsSchema = Type.Partial(\n\tType.Object({\n\t\topenai_lark: Type.String(),\n\t\topenai_regex: Type.String(),\n\t}),\n);\nexport type GrammarVariants = Static<typeof GrammarVariantsSchema>;\n\nexport const ConstrainedSamplingSchema = Type.Union([\n\tType.Object({\n\t\ttype: Type.Literal(\"json_schema\"),\n\t\tstrict: Type.Union([Type.Literal(\"prefer\"), Type.Literal(\"require\")]),\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(\"grammar\"),\n\t\tvariants: GrammarVariantsSchema,\n\t}),\n]);\nexport type ConstrainedSampling = Static<typeof ConstrainedSamplingSchema>;\n\n/**\n * Generic tool definition with typed parameter schema.\n * Usage:\n *\n * const search = Message.defineTool({\n * name: \"search\",\n * description: \"Search documents\",\n * parameters: Type.Object({\n * query: Type.String(),\n * limit: Type.Optional(Type.Number()),\n * }),\n * });\n *\n * type SearchParams = Static<typeof search.parameters>;\n */\nexport const ToolSchema = Type.Object({\n\tname: Type.String(),\n\tdescription: Type.String(),\n\tparameters: Type.Unsafe<TSchema>({}),\n\tconstrainedSampling: Type.Optional(Type.Union([Type.Literal(false), ConstrainedSamplingSchema])),\n});\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n\t/** How the provider constrains generated tool-call arguments (strict JSON schema or grammar).\n\t * used by convert tool.\n\t * */\n\tconstrainedSampling?: false | ConstrainedSampling;\n}\nexport type ToolArguments<T extends Tool> = Static<T[\"parameters\"]>;\n\nexport function defineTool<TParameters extends TSchema>(tool: Tool<TParameters>): Tool<TParameters> {\n\treturn tool;\n}\n\nexport const ContextSchema = Type.Object({\n\tsystemPrompt: Type.Optional(Type.String()),\n\tmessages: Type.Array(MessageSchema),\n\ttools: Type.Optional(Type.Array(ToolSchema)),\n});\nexport type Context = Static<typeof ContextSchema>;\n\nfunction isUnresolvedToolCall(toolCall: ToolCall): toolCall is ToolCallPendingPart | ToolCallRunningPart {\n\treturn toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;\n}\n\nfunction syntheticSkippedToolCall(toolCall: ToolCallPendingPart | ToolCallRunningPart): ToolCall {\n\tconst {\n\t\tstatus: _status,\n\t\tpartial: _partial,\n\t\t...base\n\t} = toolCall as (ToolCallPendingPart | ToolCallRunningPart) & {\n\t\tpartial?: unknown;\n\t};\n\n\treturn {\n\t\t...base,\n\t\tstatus: ToolStatusEnum.skipped,\n\t\tresult: {\n\t\t\tcontent: [{ type: \"text\", text: \"no result provided\" }],\n\t\t\tisError: true,\n\t\t},\n\t\ttime: {\n\t\t\t...toolCall.time,\n\t\t\tend: Math.max(toolCall.time.end, Date.now()),\n\t\t},\n\t};\n}\n\nconst USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\n\n// Consecutive images collapse into a single placeholder.\nfunction omitImages(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tfor (const [index, block] of content.entries()) {\n\t\tif (block.type === \"text\") result.push(block);\n\t\telse if (content[index - 1]?.type !== \"image\") result.push({ type: \"text\", text: placeholder });\n\t}\n\treturn result;\n}\n\nfunction omitToolImages(toolCall: ToolCall): ToolCall {\n\tif (!(\"result\" in toolCall) || !toolCall.result.content.some((content) => content.type === \"image\")) return toolCall;\n\treturn {\n\t\t...toolCall,\n\t\tresult: { ...toolCall.result, content: omitImages(toolCall.result.content, TOOL_IMAGE_PLACEHOLDER) },\n\t} as ToolCall;\n}\n\nexport function transformMessages<TProtocol extends Model.KnownProviderEnum>(\n\tmessages: Message[],\n\tmodel: Model.TModel<TProtocol>,\n\tnormalizeToolCallId?: (id: string, model: Model.TModel<TProtocol>, source: AssistantMessage) => string,\n): Message[] {\n\tconst toolCallIDMap = new Map<string, string>();\n\tconst supportsImages = model.input.includes(\"image\");\n\n\tconst transformed: Message[] = [];\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\ttransformed.push(supportsImages ? msg : { ...msg, parts: omitImages(msg.parts, USER_IMAGE_PLACEHOLDER) });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tconst isSameModel =\n\t\t\tassistantMsg.provider.id === model.provider.id &&\n\t\t\tassistantMsg.protocol === model.protocol &&\n\t\t\tassistantMsg.model === model.id;\n\n\t\tconst transformedParts = assistantMsg.parts.flatMap((block) => {\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\tif (isSameModel && block.thinkingSignature) return block;\n\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\tif (isSameModel) return block;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\ttext: block.thinking,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (block.type === \"text\") {\n\t\t\t\tif (isSameModel) return block;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\ttext: block.text,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t}\n\n\t\t\t\tconst normalizedID = toolCallIDMap.get(block.callID);\n\t\t\t\tif (normalizedID && normalizedID !== block.callID) {\n\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: normalizedID };\n\t\t\t\t} else if (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\tconst nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);\n\t\t\t\t\tif (nextID !== toolCall.callID) {\n\t\t\t\t\t\ttoolCallIDMap.set(toolCall.callID, nextID);\n\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: nextID };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn normalizedToolCall;\n\t\t\t}\n\n\t\t\treturn block;\n\t\t});\n\t\tconst parts = transformedParts.map((block) => {\n\t\t\tif (block.type !== \"toolCall\") return block;\n\t\t\tconst toolCall = isUnresolvedToolCall(block) ? syntheticSkippedToolCall(block) : block;\n\t\t\treturn supportsImages ? toolCall : omitToolImages(toolCall);\n\t\t});\n\n\t\ttransformed.push({\n\t\t\t...assistantMsg,\n\t\t\tparts,\n\t\t});\n\t}\n\n\treturn transformed;\n}\n","import type { LanguageModelV3CallOptions, LanguageModelV3ToolChoice, SharedV3Warning } from \"@ai-sdk/provider\";\nimport type { TSchema } from \"typebox\";\nimport * as Message from \"../../message/message.ts\";\nimport type { OpenAICodexCompatibility } from \"./codex-language-model.ts\";\n\nexport type OpenAICodexTool =\n\t| {\n\t\t\ttype: \"function\";\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tparameters: Record<string, unknown>;\n\t\t\tstrict?: boolean | null;\n\t\t\tdefer_loading?: boolean;\n\t }\n\t| {\n\t\t\ttype: \"custom\";\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tformat: {\n\t\t\t\ttype: \"grammar\";\n\t\t\t\tsyntax: \"lark\" | \"regex\";\n\t\t\t\tdefinition: string;\n\t\t\t};\n\t\t\tdefer_loading?: boolean;\n\t };\n\nexport type OpenAICodexGrammarConstraint = {\n\ttype: \"grammar\";\n\tformat: \"lark\" | \"regex\";\n\tdefinition: string;\n\tinputProperty: string;\n};\n\nexport type OpenAICodexGrammarInputBuffer = {\n\tinput: string;\n\tstarted: boolean;\n\tclosed: boolean;\n};\n\nexport function appendOpenAICodexGrammarInputJsonDelta(\n\tbuffer: OpenAICodexGrammarInputBuffer,\n\tinputProperty: string,\n\tnextInput: string,\n\tclose: boolean,\n): string | undefined {\n\tif (buffer.closed) {\n\t\tif (close && nextInput === buffer.input) return undefined;\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed after it was closed`);\n\t}\n\tif (!nextInput.startsWith(buffer.input)) {\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed non-monotonically`);\n\t}\n\n\tconst inputDelta = nextInput.slice(buffer.input.length);\n\tif (!close && inputDelta.length === 0) return undefined;\n\n\tlet delta = \"\";\n\tif (!buffer.started) {\n\t\tdelta += `{${JSON.stringify(inputProperty)}:\"`;\n\t\tbuffer.started = true;\n\t}\n\tdelta += JSON.stringify(inputDelta).slice(1, -1);\n\tbuffer.input = nextInput;\n\n\tif (close) {\n\t\tdelta += '\"}';\n\t\tbuffer.closed = true;\n\t}\n\treturn delta;\n}\n\ntype JsonSchemaObject = {\n\ttype?: unknown;\n\tproperties?: Record<string, { type?: unknown } | undefined>;\n\trequired?: unknown;\n};\n\nfunction inferGrammarInputProperty(parameters: TSchema): string {\n\tconst schema = parameters as JsonSchemaObject;\n\tif (schema.type !== \"object\") throw new Error(\"grammar constrained sampling requires an object parameter schema\");\n\tif (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== \"string\") {\n\t\tthrow new Error(\"grammar constrained sampling requires exactly one required string property\");\n\t}\n\tconst inputProperty = schema.required[0];\n\tif (!schema.properties?.[inputProperty]) {\n\t\tthrow new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);\n\t}\n\tif (schema.properties[inputProperty]?.type !== \"string\") {\n\t\tthrow new Error(`grammar constrained sampling property ${inputProperty} must have type string`);\n\t}\n\treturn inputProperty;\n}\n\nexport function resolveOpenAICodexToolConstraint(\n\ttool: Message.Tool,\n\tcompat?: OpenAICodexCompatibility,\n): OpenAICodexGrammarConstraint | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config || config.type !== \"grammar\") return undefined;\n\tif (!(compat?.supportsOpenAIGrammarTools ?? false)) return undefined;\n\n\tconst lark = config.variants.openai_lark;\n\tconst regex = config.variants.openai_regex;\n\tconst hasLark = typeof lark === \"string\" && lark.trim().length > 0;\n\tconst hasRegex = typeof regex === \"string\" && regex.trim().length > 0;\n\tif (!hasLark && !hasRegex) {\n\t\tthrow new Error(\n\t\t\t`Tool \"${tool.name}\" cannot use grammar constrained sampling: no supported grammar variant was provided.`,\n\t\t);\n\t}\n\ttry {\n\t\treturn {\n\t\t\ttype: \"grammar\",\n\t\t\tformat: hasLark ? \"lark\" : \"regex\",\n\t\t\tdefinition: hasLark ? lark! : regex!,\n\t\t\tinputProperty: inferGrammarInputProperty(tool.parameters),\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`tool \"${tool.name}\" cannot use grammar constrained sampling: ${message}.`);\n\t}\n}\n\nexport const openAICodexTools = {\n\tcustom<TParameters extends TSchema>(args: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: TParameters;\n\t\tformat: { type: \"grammar\"; syntax: \"lark\" | \"regex\"; definition: string };\n\t}): Message.Tool<TParameters> {\n\t\treturn {\n\t\t\tname: args.name,\n\t\t\tdescription: args.description,\n\t\t\tparameters: args.parameters,\n\t\t\tconstrainedSampling: {\n\t\t\t\ttype: \"grammar\",\n\t\t\t\tvariants:\n\t\t\t\t\targs.format.syntax === \"lark\"\n\t\t\t\t\t\t? { openai_lark: args.format.definition }\n\t\t\t\t\t\t: { openai_regex: args.format.definition },\n\t\t\t},\n\t\t};\n\t},\n};\n\nexport type OpenAICodexToolChoice = \"auto\" | \"none\" | \"required\";\nexport type OpenAICodexDeferredToolsMode = \"additional-tools\" | \"tool-search\";\n\nexport function resolveOpenAICodexDeferredToolsMode(\n\tcompat?: OpenAICodexCompatibility,\n): OpenAICodexDeferredToolsMode | undefined {\n\tconst supportsAdditionalTools = compat?.supportsAdditionalTools ?? false;\n\tif (supportsAdditionalTools) return \"additional-tools\";\n\n\tconst supportsToolSearch = compat?.supportsToolSearch ?? false;\n\treturn supportsToolSearch ? \"tool-search\" : undefined;\n}\n\nexport function prepareOpenAICodexTools({\n\ttools,\n\ttoolChoice,\n\tdeferredToolNames,\n}: {\n\ttools: LanguageModelV3CallOptions[\"tools\"];\n\ttoolChoice: LanguageModelV3ToolChoice | undefined;\n\tdeferredToolNames?: ReadonlySet<string>;\n}): {\n\tcodexTools: OpenAICodexTool[] | undefined;\n\tdeferredCodexTools: ReadonlyMap<string, OpenAICodexTool>;\n\tgrammarToolInputProperties: ReadonlyMap<string, string>;\n\tcodexToolChoice: OpenAICodexToolChoice | undefined;\n\twarnings: SharedV3Warning[];\n} {\n\tconst warnings: SharedV3Warning[] = [];\n\tconst deferredCodexTools = new Map<string, OpenAICodexTool>();\n\tconst grammarToolInputProperties = new Map<string, string>();\n\n\tif (!tools || tools.length === 0) {\n\t\treturn {\n\t\t\tcodexTools: undefined,\n\t\t\tdeferredCodexTools,\n\t\t\tgrammarToolInputProperties,\n\t\t\tcodexToolChoice: undefined,\n\t\t\twarnings,\n\t\t};\n\t}\n\n\tconst codexTools: OpenAICodexTool[] = [];\n\tfor (const tool of tools) {\n\t\tif (tool.type !== \"function\") {\n\t\t\twarnings.push({\n\t\t\t\ttype: \"unsupported\",\n\t\t\t\tfeature: `tool type ${tool.type}`,\n\t\t\t\tdetails: `OpenAI Codex only supports function tools; ignoring ${tool.name}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst metadata = tool.providerOptions?.[\"openai-codex\"] as Record<string, unknown> | undefined;\n\t\tconst grammar = metadata?.grammar as OpenAICodexGrammarConstraint | undefined;\n\t\tconst codexTool: OpenAICodexTool =\n\t\t\tgrammar?.type === \"grammar\"\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t...(tool.description !== undefined && { description: tool.description }),\n\t\t\t\t\t\tformat: {\n\t\t\t\t\t\t\ttype: \"grammar\",\n\t\t\t\t\t\t\tsyntax: grammar.format,\n\t\t\t\t\t\t\tdefinition: grammar.definition,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t...(tool.description !== undefined && { description: tool.description }),\n\t\t\t\t\t\tparameters: tool.inputSchema as Record<string, unknown>,\n\t\t\t\t\t\tstrict: tool.strict ?? null,\n\t\t\t\t\t};\n\t\tif (grammar?.type === \"grammar\") grammarToolInputProperties.set(tool.name, grammar.inputProperty);\n\t\tif (deferredToolNames?.has(tool.name)) deferredCodexTools.set(tool.name, codexTool);\n\t\telse codexTools.push(codexTool);\n\t}\n\n\tlet codexToolChoice: OpenAICodexToolChoice | undefined;\n\tswitch (toolChoice?.type) {\n\t\tcase undefined:\n\t\t\tbreak;\n\t\tcase \"auto\":\n\t\tcase \"none\":\n\t\tcase \"required\":\n\t\t\tcodexToolChoice = toolChoice.type;\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\twarnings.push({\n\t\t\t\ttype: \"unsupported\",\n\t\t\t\tfeature: \"toolChoice tool name\",\n\t\t\t\tdetails: \"OpenAI Codex does not support forcing a specific tool; using 'required' instead.\",\n\t\t\t});\n\t\t\tcodexToolChoice = \"required\";\n\t\t\tbreak;\n\t}\n\n\treturn {\n\t\tcodexTools: codexTools.length > 0 ? codexTools : undefined,\n\t\tdeferredCodexTools,\n\t\tgrammarToolInputProperties,\n\t\tcodexToolChoice,\n\t\twarnings,\n\t};\n}\n","/** Fast deterministic hash for shortening provider wire identifiers. */\nexport function shortHash(value: string): string {\n\tlet high = 0xdeadbeef;\n\tlet low = 0x41c6ce57;\n\tfor (let index = 0; index < value.length; index++) {\n\t\tconst character = value.charCodeAt(index);\n\t\thigh = Math.imul(high ^ character, 2654435761);\n\t\tlow = Math.imul(low ^ character, 1597334677);\n\t}\n\thigh = Math.imul(high ^ (high >>> 16), 2246822507) ^ Math.imul(low ^ (low >>> 13), 3266489909);\n\tlow = Math.imul(low ^ (low >>> 16), 2246822507) ^ Math.imul(high ^ (high >>> 13), 3266489909);\n\treturn (low >>> 0).toString(36) + (high >>> 0).toString(36);\n}\n","import { APICallError } from \"@ai-sdk/provider\";\n\ntype OpenAICodexError = {\n\tcode?: string;\n\ttype?: string;\n\tmessage?: string;\n\tplan_type?: string;\n\tresets_at?: number;\n};\n\ntype OpenAICodexErrorPayload = {\n\terror?: OpenAICodexError;\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n\nconst asString = (value: unknown): string | undefined =>\n\ttypeof value === \"string\" && value.trim() ? value.trim() : undefined;\n\nfunction normalizeErrorPayload(value: unknown): OpenAICodexErrorPayload {\n\tconst record = asRecord(value);\n\tconst nested = asRecord(record?.error);\n\tconst source = nested ?? record ?? {};\n\tconst code = asString(source.code);\n\tconst type = asString(source.type);\n\tconst message = asString(source.message);\n\tconst planType = asString(source.plan_type);\n\tconst error: OpenAICodexError = {\n\t\t...(code !== undefined && { code }),\n\t\t...(type !== undefined && { type }),\n\t\t...(message !== undefined && { message }),\n\t\t...(planType !== undefined && { plan_type: planType }),\n\t\t...(typeof source.resets_at === \"number\" && { resets_at: source.resets_at }),\n\t};\n\treturn { error };\n}\n\nfunction parseErrorPayload(body: string): OpenAICodexErrorPayload | undefined {\n\ttry {\n\t\treturn normalizeErrorPayload(JSON.parse(body) as unknown);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction errorIdentifiers(error: OpenAICodexError | undefined): string {\n\treturn `${error?.code ?? \"\"} ${error?.type ?? \"\"}`.toLowerCase();\n}\n\nfunction hasIdentifier(error: OpenAICodexError | undefined, identifiers: readonly string[]): boolean {\n\tconst value = errorIdentifiers(error);\n\treturn identifiers.some((identifier) => value.includes(identifier));\n}\n\nfunction isUsageLimitError(error: OpenAICodexError | undefined): boolean {\n\treturn hasIdentifier(error, [\"usage_limit_reached\", \"gousagelimiterror\", \"freeusagelimiterror\"]);\n}\n\nfunction isTerminalRateLimitError(body: string, payload = parseErrorPayload(body)): boolean {\n\treturn (\n\t\tisUsageLimitError(payload?.error) ||\n\t\thasIdentifier(payload?.error, [\"usage_not_included\", \"insufficient_quota\"]) ||\n\t\t/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|out of budget|quota exceeded|billing/i.test(\n\t\t\tbody,\n\t\t)\n\t);\n}\n\nfunction streamErrorStatus(error: OpenAICodexError | undefined): number {\n\tif (isUsageLimitError(error) || hasIdentifier(error, [\"usage_not_included\", \"insufficient_quota\", \"rate_limit\"])) {\n\t\treturn 429;\n\t}\n\tif (hasIdentifier(error, [\"server_is_overloaded\", \"slow_down\"])) return 503;\n\tif (\n\t\thasIdentifier(error, [\n\t\t\t\"context_length_exceeded\",\n\t\t\t\"invalid_prompt\",\n\t\t\t\"bio_policy\",\n\t\t\t\"cyber_policy\",\n\t\t\t\"misalignment_policy_violation\",\n\t\t])\n\t) {\n\t\treturn 400;\n\t}\n\treturn 500;\n}\n\nfunction retryAfterHeader(message: string | undefined): Record<string, string> {\n\tconst match = message?.match(/try again in\\s*(\\d+(?:\\.\\d+)?)\\s*(s|ms|seconds?)/i);\n\tif (!match) return {};\n\tconst value = Number(match[1]);\n\tif (!Number.isFinite(value)) return {};\n\treturn { \"retry-after\": String(match[2]?.toLowerCase() === \"ms\" ? value / 1_000 : value) };\n}\n\n/**\n * Turn a Codex error payload into a human-friendly message. Only terminal\n * ChatGPT plan exhaustion is rewritten; transient 429s retain backend detail.\n */\nexport function openAICodexErrorMessage(_status: number, body: string, statusText?: string): string {\n\tlet message = body || statusText || \"OpenAI Codex request failed\";\n\tconst payload = parseErrorPayload(body);\n\tconst error = payload?.error;\n\n\tif (isUsageLimitError(error)) {\n\t\tconst plan = error?.plan_type ? ` (${error.plan_type.toLowerCase()} plan)` : \"\";\n\t\tconst minutes = error?.resets_at\n\t\t\t? Math.max(0, Math.round((error.resets_at * 1000 - Date.now()) / 60000))\n\t\t\t: undefined;\n\t\tconst when = minutes === undefined ? \"\" : ` Try again in ~${minutes} min.`;\n\t\treturn `You have hit your ChatGPT usage limit${plan}.${when}`.trim();\n\t}\n\n\tif (error?.message) message = error.message;\n\treturn message;\n}\n\nexport async function createOpenAICodexAPICallError(args: {\n\tresponse: Response;\n\turl: string;\n\trequestBodyValues: unknown;\n}): Promise<APICallError> {\n\tconst { response, url, requestBodyValues } = args;\n\tconst responseBody = await response.text().catch(() => \"\");\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\tconst data = parseErrorPayload(responseBody);\n\n\treturn new APICallError({\n\t\tmessage: openAICodexErrorMessage(response.status, responseBody, response.statusText),\n\t\turl,\n\t\trequestBodyValues,\n\t\tstatusCode: response.status,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\t...(data !== undefined && { data }),\n\t\tisRetryable:\n\t\t\tresponse.status === 408 ||\n\t\t\tresponse.status === 409 ||\n\t\t\t(response.status === 429 && !isTerminalRateLimitError(responseBody, data)) ||\n\t\t\tresponse.status >= 500,\n\t});\n}\n\n/** Map an error embedded in a successful SSE response to the same API error shape as HTTP failures. */\nexport function createOpenAICodexStreamError(args: {\n\terror: unknown;\n\turl: string;\n\trequestBodyValues: unknown;\n\tresponseHeaders?: Record<string, string>;\n}): APICallError {\n\tconst { error: value, url, requestBodyValues } = args;\n\tconst data = normalizeErrorPayload(value);\n\tconst error = data.error;\n\tconst statusCode = streamErrorStatus(error);\n\tconst responseBody = JSON.stringify(data);\n\tconst responseHeaders = {\n\t\t...args.responseHeaders,\n\t\t...retryAfterHeader(error?.message),\n\t};\n\n\treturn new APICallError({\n\t\tmessage: openAICodexErrorMessage(statusCode, responseBody),\n\t\turl,\n\t\trequestBodyValues,\n\t\tstatusCode,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\tdata,\n\t\tisRetryable:\n\t\t\tstatusCode >= 500 || (hasIdentifier(error, [\"rate_limit\"]) && !isTerminalRateLimitError(responseBody, data)),\n\t});\n}\n\n/** A transport failure used when an SSE response ends without a terminal Responses event. */\nexport function createOpenAICodexPrematureCloseError(args: {\n\turl: string;\n\trequestBodyValues: unknown;\n\tresponseHeaders?: Record<string, string>;\n}): APICallError {\n\treturn new APICallError({\n\t\tmessage: \"OpenAI Codex stream closed before response.completed\",\n\t\turl: args.url,\n\t\trequestBodyValues: args.requestBodyValues,\n\t\t...(args.responseHeaders !== undefined && { responseHeaders: args.responseHeaders }),\n\t\tisRetryable: true,\n\t});\n}\n\n/**\n * A fetch that rejects never produced a response, but its body was still sent. Wrap\n * it the way AI SDK providers do, so it reads as a retryable transport failure that\n * carries the request. Aborts pass through untouched.\n */\nexport function openAICodexFetchError(error: unknown, url: string, requestBodyValues: unknown): unknown {\n\tif (error instanceof Error && (error.name === \"AbortError\" || error.name === \"TimeoutError\")) return error;\n\tconst cause = error instanceof Error && error.cause instanceof Error ? error.cause : error;\n\treturn new APICallError({\n\t\tmessage: `Cannot connect to API: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\tcause: error,\n\t\turl,\n\t\trequestBodyValues,\n\t\tisRetryable: true,\n\t});\n}\n","import type {\n\tLanguageModelV3FilePart,\n\tLanguageModelV3Prompt,\n\tLanguageModelV3ToolResultOutput,\n\tLanguageModelV4FilePart,\n\tLanguageModelV4Prompt,\n\tLanguageModelV4ToolResultOutput,\n} from \"@ai-sdk/provider\";\nimport { shortHash } from \"../../utils/hash.ts\";\nimport type { OpenAICodexDeferredToolsMode, OpenAICodexTool } from \"./codex-tools.ts\";\n\n/**\n * OpenAI Responses API input item types accepted by the Codex backend.\n */\nexport type OpenAICodexInputItem =\n\t| {\n\t\t\trole: \"user\";\n\t\t\tcontent: Array<\n\t\t\t\t{ type: \"input_text\"; text: string } | { type: \"input_image\"; image_url: string; detail?: string }\n\t\t\t>;\n\t }\n\t| {\n\t\t\ttype: \"message\";\n\t\t\trole: \"assistant\";\n\t\t\tid: string;\n\t\t\tcontent: Array<{ type: \"output_text\"; text: string; annotations: unknown[] }>;\n\t\t\tstatus: \"completed\";\n\t }\n\t| {\n\t\t\ttype: \"function_call\";\n\t\t\tid?: string;\n\t\t\tcall_id: string;\n\t\t\tname: string;\n\t\t\targuments: string;\n\t\t\tnamespace?: string;\n\t }\n\t| {\n\t\t\ttype: \"custom_tool_call\";\n\t\t\tid?: string;\n\t\t\tcall_id: string;\n\t\t\tname: string;\n\t\t\tinput: string;\n\t\t\tnamespace?: string;\n\t }\n\t| {\n\t\t\ttype: \"reasoning\";\n\t\t\tid: string;\n\t\t\t[key: string]: unknown;\n\t }\n\t| {\n\t\t\ttype: \"function_call_output\";\n\t\t\tcall_id: string;\n\t\t\toutput:\n\t\t\t\t| string\n\t\t\t\t| Array<{ type: \"input_text\"; text: string } | { type: \"input_image\"; image_url: string; detail: \"auto\" }>;\n\t }\n\t| {\n\t\t\ttype: \"custom_tool_call_output\";\n\t\t\tcall_id: string;\n\t\t\toutput: string;\n\t }\n\t| {\n\t\t\ttype: \"additional_tools\";\n\t\t\trole: \"developer\";\n\t\t\ttools: OpenAICodexTool[];\n\t }\n\t| {\n\t\t\ttype: \"tool_search_call\";\n\t\t\tcall_id: string;\n\t\t\texecution: \"client\";\n\t\t\tstatus: \"completed\";\n\t\t\targuments: { query: string; limit: number };\n\t }\n\t| {\n\t\t\ttype: \"tool_search_output\";\n\t\t\tcall_id: string;\n\t\t\texecution: \"client\";\n\t\t\tstatus: \"completed\";\n\t\t\ttools: OpenAICodexTool[];\n\t };\n\nexport type OpenAICodexPrompt = {\n\tinstructions: string;\n\tinput: OpenAICodexInputItem[];\n};\n\nconst DEFAULT_INSTRUCTIONS = \"You are a helpful assistant.\";\n\nexport type OpenAICodexPromptOptions = {\n\tdeferredTools?: ReadonlyMap<string, OpenAICodexTool>;\n\tdeferredToolsMode?: OpenAICodexDeferredToolsMode;\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tsupportsImages?: boolean;\n};\n\n// Tool call ids round-trip through the AI SDK as `call_id|item_id` because the\n// Responses API needs both halves: `call_id` to pair function_call_output and\n// `id` for the function_call item itself.\nexport function splitToolCallId(toolCallId: string): { callId: string; itemId: string } {\n\tconst separator = toolCallId.indexOf(\"|\");\n\tif (separator === -1) return { callId: toolCallId, itemId: toolCallId };\n\treturn { callId: toolCallId.slice(0, separator), itemId: toolCallId.slice(separator + 1) };\n}\n\nexport function joinToolCallId(callId: string, itemId: string): string {\n\treturn `${callId}|${itemId}`;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary);\n}\n\nfunction imageUrlFromFilePart(part: LanguageModelV3FilePart | LanguageModelV4FilePart): string | undefined {\n\tconst data = part.data;\n\tif (data instanceof URL) return data.toString();\n\tif (typeof data === \"string\") {\n\t\tif (data.startsWith(\"data:\") || data.startsWith(\"http://\") || data.startsWith(\"https://\")) return data;\n\t\treturn `data:${part.mediaType};base64,${data}`;\n\t}\n\tif (data instanceof Uint8Array) {\n\t\treturn `data:${part.mediaType};base64,${uint8ArrayToBase64(data)}`;\n\t}\n\tif (\"type\" in data) {\n\t\tif (data.type === \"url\") return data.url.toString();\n\t\tif (data.type === \"data\") {\n\t\t\treturn typeof data.data === \"string\"\n\t\t\t\t? `data:${part.mediaType};base64,${data.data}`\n\t\t\t\t: `data:${part.mediaType};base64,${uint8ArrayToBase64(data.data)}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction toolResultOutput(\n\toutput: LanguageModelV3ToolResultOutput | LanguageModelV4ToolResultOutput,\n\tsupportsImages: boolean,\n): Extract<OpenAICodexInputItem, { type: \"function_call_output\" }>[\"output\"] {\n\tswitch (output.type) {\n\t\tcase \"text\":\n\t\tcase \"error-text\":\n\t\t\treturn output.value || \"(no tool output)\";\n\t\tcase \"json\":\n\t\tcase \"error-json\":\n\t\t\treturn JSON.stringify(output.value);\n\t\tcase \"execution-denied\":\n\t\t\treturn output.reason ?? \"Tool execution denied\";\n\t\tcase \"content\": {\n\t\t\tconst text = output.value\n\t\t\t\t.filter((part): part is Extract<typeof part, { type: \"text\" }> => part.type === \"text\")\n\t\t\t\t.map((part) => part.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst images: Array<{ type: \"input_image\"; image_url: string; detail: \"auto\" }> = [];\n\t\t\tif (supportsImages) {\n\t\t\t\tfor (const part of output.value) {\n\t\t\t\t\tif (part.type === \"file-data\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\timages.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\timage_url: `data:${part.mediaType};base64,${part.data}`,\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (part.type === \"file-url\") {\n\t\t\t\t\t\timages.push({ type: \"input_image\", image_url: part.url, detail: \"auto\" });\n\t\t\t\t\t} else if (part.type === \"file\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\tconst data = part.data;\n\t\t\t\t\t\tif (data.type === \"url\") {\n\t\t\t\t\t\t\timages.push({ type: \"input_image\", image_url: data.url.toString(), detail: \"auto\" });\n\t\t\t\t\t\t} else if (data.type === \"data\") {\n\t\t\t\t\t\t\tconst encoded = typeof data.data === \"string\" ? data.data : uint8ArrayToBase64(data.data);\n\t\t\t\t\t\t\timages.push({\n\t\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\t\timage_url: `data:${part.mediaType};base64,${encoded}`,\n\t\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (images.length === 0)\n\t\t\t\treturn text || (output.value.length > 0 ? \"(see attached image)\" : \"(no tool output)\");\n\t\t\treturn [...(text ? [{ type: \"input_text\" as const, text }] : []), ...images];\n\t\t}\n\t\tdefault:\n\t\t\treturn JSON.stringify(output);\n\t}\n}\n\nfunction customToolInput(input: unknown, toolName: string, inputProperty: string): string {\n\tif (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n\t\tthrow new Error(`custom tool \"${toolName}\" requires object input with string property \"${inputProperty}\".`);\n\t}\n\tconst value = (input as Record<string, unknown>)[inputProperty];\n\tif (typeof value !== \"string\") {\n\t\tthrow new Error(`custom tool \"${toolName}\" requires string input property \"${inputProperty}\".`);\n\t}\n\treturn value;\n}\n\nfunction customToolOutput(\n\toutput: LanguageModelV3ToolResultOutput | LanguageModelV4ToolResultOutput,\n\tsupportsImages: boolean,\n): string {\n\tconst value = toolResultOutput(output, supportsImages);\n\treturn typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\nfunction codexProviderMetadata(\n\tproviderOptions: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n\tconst codex = providerOptions?.[\"openai-codex\"];\n\treturn typeof codex === \"object\" && codex !== null && !Array.isArray(codex)\n\t\t? (codex as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction addedToolNames(providerOptions: Record<string, unknown> | undefined): string[] {\n\tconst names = codexProviderMetadata(providerOptions)?.addedToolNames;\n\treturn Array.isArray(names) ? names.filter((name): name is string => typeof name === \"string\") : [];\n}\n\nfunction reasoningItem(\n\tproviderOptions: Record<string, unknown> | undefined,\n): Extract<OpenAICodexInputItem, { type: \"reasoning\" }> | undefined {\n\tconst value = codexProviderMetadata(providerOptions)?.reasoningItem;\n\tif (typeof value !== \"string\") return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n\t\tconst item = parsed as Record<string, unknown>;\n\t\treturn item.type === \"reasoning\" && typeof item.id === \"string\"\n\t\t\t? (item as Extract<OpenAICodexInputItem, { type: \"reasoning\" }>)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Collect definitions that were introduced at a transcript load point rather than at request start. */\nexport function collectOpenAICodexDeferredToolNames(\n\tprompt: LanguageModelV3Prompt | LanguageModelV4Prompt,\n): Set<string> {\n\tconst deferredNames = new Set<string>();\n\tconst usedNames = new Set<string>();\n\n\tfor (const message of prompt) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type === \"tool-call\") usedNames.add(part.toolName);\n\t\t\t\tif (part.type === \"tool-result\") {\n\t\t\t\t\tfor (const name of addedToolNames(part.providerOptions)) {\n\t\t\t\t\t\tif (!usedNames.has(name)) deferredNames.add(name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"tool\") continue;\n\t\tfor (const part of message.content) {\n\t\t\tif (part.type !== \"tool-result\") continue;\n\t\t\tfor (const name of addedToolNames(part.providerOptions)) {\n\t\t\t\tif (!usedNames.has(name)) deferredNames.add(name);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn deferredNames;\n}\n\nfunction deferredToolCallId(toolCallId: string, names: readonly string[]): string {\n\treturn `cdwrk_aikit_tool_${shortHash(`${toolCallId}:${names.join(\",\")}`)}`;\n}\n\n/**\n * Convert an AI SDK V3 prompt into the Codex Responses request shape.\n * System messages become `instructions`; everything else maps to `input` items.\n */\nexport function convertToOpenAICodexPrompt(\n\tprompt: LanguageModelV3Prompt | LanguageModelV4Prompt,\n\toptions?: OpenAICodexPromptOptions,\n): OpenAICodexPrompt {\n\tlet instructions: string | undefined;\n\tconst input: OpenAICodexInputItem[] = [];\n\tlet syntheticMessageCounter = 0;\n\tconst loadedToolNames = new Set<string>();\n\n\tconst appendDeferredTools = (toolCallId: string, names: readonly string[]): void => {\n\t\tconst tools: OpenAICodexTool[] = [];\n\t\tfor (const name of names) {\n\t\t\tconst tool = options?.deferredTools?.get(name);\n\t\t\tif (!tool || loadedToolNames.has(name)) continue;\n\t\t\tloadedToolNames.add(name);\n\t\t\ttools.push(tool);\n\t\t}\n\t\tif (tools.length === 0) return;\n\n\t\tif (options?.deferredToolsMode === \"additional-tools\") {\n\t\t\tinput.push({ type: \"additional_tools\", role: \"developer\", tools });\n\t\t\treturn;\n\t\t}\n\t\tif (options?.deferredToolsMode === \"tool-search\") {\n\t\t\tconst callId = deferredToolCallId(\n\t\t\t\ttoolCallId,\n\t\t\t\ttools.map((tool) => tool.name),\n\t\t\t);\n\t\t\tinput.push({\n\t\t\t\ttype: \"tool_search_call\",\n\t\t\t\tcall_id: callId,\n\t\t\t\texecution: \"client\",\n\t\t\t\tstatus: \"completed\",\n\t\t\t\targuments: { query: tools.map((tool) => tool.name).join(\" \"), limit: tools.length },\n\t\t\t});\n\t\t\tinput.push({\n\t\t\t\ttype: \"tool_search_output\",\n\t\t\t\tcall_id: callId,\n\t\t\t\texecution: \"client\",\n\t\t\t\tstatus: \"completed\",\n\t\t\t\ttools: tools.map((tool) => ({ ...tool, defer_loading: true })),\n\t\t\t});\n\t\t}\n\t};\n\n\tfor (const message of prompt) {\n\t\tswitch (message.role) {\n\t\t\tcase \"system\": {\n\t\t\t\tinstructions = instructions == null ? message.content : `${instructions}\\n\\n${message.content}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"user\": {\n\t\t\t\tconst content: Extract<OpenAICodexInputItem, { role: \"user\" }>[\"content\"] = [];\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type === \"text\") {\n\t\t\t\t\t\tcontent.push({ type: \"input_text\", text: part.text });\n\t\t\t\t\t} else if (part.type === \"file\" && part.mediaType.startsWith(\"image/\")) {\n\t\t\t\t\t\tconst imageUrl = imageUrlFromFilePart(part);\n\t\t\t\t\t\tif (imageUrl) content.push({ type: \"input_image\", image_url: imageUrl, detail: \"auto\" });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (content.length > 0) {\n\t\t\t\t\tinput.push({ role: \"user\", content });\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"assistant\": {\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type === \"reasoning\") {\n\t\t\t\t\t\tconst item = reasoningItem(part.providerOptions);\n\t\t\t\t\t\tif (item) input.push(item);\n\t\t\t\t\t} else if (part.type === \"text\") {\n\t\t\t\t\t\tsyntheticMessageCounter++;\n\t\t\t\t\t\tconst messageId = codexProviderMetadata(part.providerOptions)?.messageId;\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tid:\n\t\t\t\t\t\t\t\ttypeof messageId === \"string\" && messageId.length <= 64\n\t\t\t\t\t\t\t\t\t? messageId\n\t\t\t\t\t\t\t\t\t: `msg_cdwrk_aikit_${syntheticMessageCounter}`,\n\t\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: part.text, annotations: [] }],\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (part.type === \"tool-call\") {\n\t\t\t\t\t\tconst { callId, itemId } = splitToolCallId(part.toolCallId);\n\t\t\t\t\t\tconst metadata = codexProviderMetadata(part.providerOptions);\n\t\t\t\t\t\tconst namespace = metadata?.namespace;\n\t\t\t\t\t\tconst inputProperty = options?.grammarToolInputProperties?.get(part.toolName);\n\t\t\t\t\t\tif (inputProperty) {\n\t\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\t\t...(metadata?.omitItemId === true || !itemId.startsWith(\"ctc_\") ? {} : { id: itemId }),\n\t\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\t\tname: part.toolName,\n\t\t\t\t\t\t\t\tinput: customToolInput(part.input, part.toolName, inputProperty),\n\t\t\t\t\t\t\t\t...(typeof namespace === \"string\" ? { namespace } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\t\t\t...(metadata?.omitItemId === true || !itemId.startsWith(\"fc_\") ? {} : { id: itemId }),\n\t\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\t\tname: part.toolName,\n\t\t\t\t\t\t\t\targuments: typeof part.input === \"string\" ? part.input : JSON.stringify(part.input ?? {}),\n\t\t\t\t\t\t\t\t...(typeof namespace === \"string\" ? { namespace } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool\": {\n\t\t\t\tfor (const part of message.content) {\n\t\t\t\t\tif (part.type !== \"tool-result\") continue;\n\t\t\t\t\tconst { callId } = splitToolCallId(part.toolCallId);\n\t\t\t\t\tif (options?.grammarToolInputProperties?.has(part.toolName)) {\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput: customToolOutput(part.output, options?.supportsImages ?? true),\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinput.push({\n\t\t\t\t\t\t\ttype: \"function_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput: toolResultOutput(part.output, options?.supportsImages ?? true),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tappendDeferredTools(part.toolCallId, addedToolNames(part.providerOptions));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { instructions: instructions || DEFAULT_INSTRUCTIONS, input };\n}\n","import { EventSourceParserStream, type EventSourceMessage } from \"eventsource-parser/stream\";\n\n/** Parse standards-compliant event streams from the Codex Responses endpoint. */\nexport function parseOpenAICodexSSEStream(body: ReadableStream<Uint8Array>): ReadableStream<Record<string, unknown>> {\n\tconst decoder = new TextDecoder();\n\treturn body\n\t\t.pipeThrough(\n\t\t\tnew TransformStream<Uint8Array, string>({\n\t\t\t\ttransform(chunk, controller) {\n\t\t\t\t\tconst text = decoder.decode(chunk, { stream: true });\n\t\t\t\t\tif (text) controller.enqueue(text);\n\t\t\t\t},\n\t\t\t\tflush(controller) {\n\t\t\t\t\tconst text = decoder.decode();\n\t\t\t\t\tif (text) controller.enqueue(text);\n\t\t\t\t},\n\t\t\t}),\n\t\t)\n\t\t.pipeThrough(new EventSourceParserStream({ onError: \"terminate\" }))\n\t\t.pipeThrough(\n\t\t\tnew TransformStream<EventSourceMessage, Record<string, unknown>>({\n\t\t\t\ttransform(event, controller) {\n\t\t\t\t\tconst data = event.data.trim();\n\t\t\t\t\tif (!data || data === \"[DONE]\") return;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed: unknown = JSON.parse(data);\n\t\t\t\t\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\t\t\t\t\tthrow new TypeError(\"codex SSE data must be a JSON object\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(parsed as Record<string, unknown>);\n\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\tcontroller.error(new Error(`invalid OpenAI Codex SSE JSON: ${data.slice(0, 200)}`, { cause }));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n}\n","import type { JSONObject, LanguageModelV3FinishReason, LanguageModelV3Usage } from \"@ai-sdk/provider\";\n\nexport type OpenAICodexUsage = {\n\tinput_tokens?: number;\n\toutput_tokens?: number;\n\ttotal_tokens?: number;\n\tinput_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n\toutput_tokens_details?: { reasoning_tokens?: number };\n};\n\nexport function convertOpenAICodexUsage(usage: OpenAICodexUsage | undefined): LanguageModelV3Usage {\n\tconst inputTotal = usage?.input_tokens;\n\tconst cachedTokens = usage?.input_tokens_details?.cached_tokens ?? 0;\n\tconst cacheWriteTokens = usage?.input_tokens_details?.cache_write_tokens ?? 0;\n\tconst outputTotal = usage?.output_tokens;\n\tconst reasoningTokens = usage?.output_tokens_details?.reasoning_tokens ?? 0;\n\n\treturn {\n\t\tinputTokens: {\n\t\t\ttotal: inputTotal,\n\t\t\tnoCache: inputTotal === undefined ? undefined : Math.max(inputTotal - cachedTokens - cacheWriteTokens, 0),\n\t\t\tcacheRead: inputTotal === undefined ? undefined : cachedTokens,\n\t\t\tcacheWrite: inputTotal === undefined ? undefined : cacheWriteTokens,\n\t\t},\n\t\toutputTokens: {\n\t\t\ttotal: outputTotal,\n\t\t\ttext: outputTotal === undefined ? undefined : outputTotal - reasoningTokens,\n\t\t\treasoning: outputTotal === undefined ? undefined : reasoningTokens,\n\t\t},\n\t\t...(usage ? { raw: usage as JSONObject } : {}),\n\t};\n}\n\nexport function mapOpenAICodexFinishReason(\n\tstatus: string | undefined,\n\thasToolCalls: boolean,\n\tincompleteReason?: string,\n): LanguageModelV3FinishReason {\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn { unified: hasToolCalls ? \"tool-calls\" : \"stop\", raw: status };\n\t\tcase \"incomplete\":\n\t\t\treturn incompleteReason === \"max_output_tokens\"\n\t\t\t\t? { unified: \"length\", raw: `${status}.${incompleteReason}` }\n\t\t\t\t: { unified: \"error\", raw: incompleteReason ? `${status}.${incompleteReason}` : status };\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn { unified: \"error\", raw: status };\n\t\tcase undefined:\n\t\t\treturn { unified: \"other\", raw: undefined };\n\t\tdefault:\n\t\t\treturn { unified: \"stop\", raw: status };\n\t}\n}\n","import type * as NodeZlib from \"node:zlib\";\nimport type {\n\tLanguageModelV3,\n\tLanguageModelV3CallOptions,\n\tLanguageModelV3Content,\n\tLanguageModelV3FinishReason,\n\tLanguageModelV3GenerateResult,\n\tLanguageModelV3StreamPart,\n\tLanguageModelV3StreamResult,\n\tLanguageModelV3Usage,\n\tSharedV3Warning,\n} from \"@ai-sdk/provider\";\nimport {\n\tcreateOpenAICodexAPICallError,\n\topenAICodexFetchError,\n\tcreateOpenAICodexPrematureCloseError,\n\tcreateOpenAICodexStreamError,\n} from \"./codex-error.ts\";\nimport { collectOpenAICodexDeferredToolNames, convertToOpenAICodexPrompt, joinToolCallId } from \"./codex-prompt.ts\";\nimport { parseOpenAICodexSSEStream } from \"./codex-sse.ts\";\nimport {\n\tappendOpenAICodexGrammarInputJsonDelta,\n\tprepareOpenAICodexTools,\n\tresolveOpenAICodexDeferredToolsMode,\n\ttype OpenAICodexGrammarInputBuffer,\n} from \"./codex-tools.ts\";\nimport { convertOpenAICodexUsage, mapOpenAICodexFinishReason, type OpenAICodexUsage } from \"./codex-usage.ts\";\n\nexport const OPENAI_CODEX_DEFAULT_BASE_URL = \"https://chatgpt.com/backend-api\";\nexport const OPENAI_CODEX_PROMPT_CACHE_KEY_MAX_LENGTH = 64;\nconst REQUEST_COMPRESSION_ZSTD_LEVEL = 3;\n\ntype ProcessWithBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:zlib\") => typeof NodeZlib;\n};\n\nfunction compressOpenAICodexRequest(body: string): Uint8Array | undefined {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) return undefined;\n\tconst zlib = (process as ProcessWithBuiltinModule).getBuiltinModule?.(\"node:zlib\");\n\tif (!zlib || typeof zlib.zstdCompressSync !== \"function\") return undefined;\n\ttry {\n\t\tconst compressed = zlib.zstdCompressSync(body, {\n\t\t\tparams: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL },\n\t\t});\n\t\treturn new Uint8Array(compressed.buffer, compressed.byteOffset, compressed.byteLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function clampOpenAICodexPromptCacheKey(key: string | undefined): string | undefined {\n\tif (key === undefined) return undefined;\n\tconst characters = Array.from(key);\n\treturn characters.length <= OPENAI_CODEX_PROMPT_CACHE_KEY_MAX_LENGTH\n\t\t? key\n\t\t: characters.slice(0, OPENAI_CODEX_PROMPT_CACHE_KEY_MAX_LENGTH).join(\"\");\n}\n\nexport type OpenAICodexModelId =\n\t| \"gpt-5.3-codex-spark\"\n\t| \"gpt-5.4\"\n\t| \"gpt-5.4-mini\"\n\t| \"gpt-5.5\"\n\t| \"gpt-5.6-luna\"\n\t| \"gpt-5.6-sol\"\n\t| \"gpt-5.6-terra\"\n\t| (string & {});\n\nexport type OpenAICodexServiceTier = \"auto\" | \"default\" | \"flex\" | \"scale\" | \"priority\";\n\nexport type OpenAICodexCompatibility = {\n\tsupportsToolSearch?: boolean;\n\tsupportsAdditionalTools?: boolean;\n\tsupportsStrictMode?: boolean;\n\tsupportsOpenAIGrammarTools?: boolean;\n\t/** Internal transport capability derived from the model's input modalities. */\n\tsupportsImages?: boolean;\n};\n\n/**\n * Per-call options, passed via `providerOptions[\"openai-codex\"]`.\n */\nexport type OpenAICodexLanguageModelOptions = {\n\t/** Reasoning effort forwarded as `reasoning.effort`. */\n\treasoningEffort?: \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | (string & {});\n\t/** Reasoning summary verbosity; defaults to `auto` when an effort is set. */\n\treasoningSummary?: \"auto\" | \"concise\" | \"detailed\" | \"off\" | \"on\" | null;\n\t/** Output text verbosity; defaults to `low`. */\n\ttextVerbosity?: \"low\" | \"medium\" | \"high\";\n\tserviceTier?: OpenAICodexServiceTier;\n};\n\nexport type OpenAICodexLanguageModelConfig = {\n\tprovider: string;\n\tbaseURL: string;\n\theaders: () => PromiseLike<Record<string, string | undefined>> | Record<string, string | undefined>;\n\tfetch?: typeof globalThis.fetch;\n\tsessionId?: string;\n\tserviceTier?: OpenAICodexServiceTier;\n\tcompat?: OpenAICodexCompatibility;\n};\n\n/**\n * Resolve the Codex responses endpoint from a base URL that may already\n * include the `/codex` or `/codex/responses` suffix.\n */\nexport function resolveOpenAICodexUrl(baseUrl?: string): string {\n\tconst raw = baseUrl?.trim() ? baseUrl : OPENAI_CODEX_DEFAULT_BASE_URL;\n\tconst normalized = raw.replace(/\\/+$/, \"\");\n\tif (normalized.endsWith(\"/codex/responses\")) return normalized;\n\tif (normalized.endsWith(\"/codex\")) return `${normalized}/responses`;\n\treturn `${normalized}/codex/responses`;\n}\n\ntype CodexEvent = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as CodexEvent) : undefined;\n}\n\nfunction asString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction cleanHeaders(headers: Record<string, string | undefined>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value !== undefined) result[key] = value;\n\t}\n\treturn result;\n}\n\nexport class OpenAICodexLanguageModel implements LanguageModelV3 {\n\treadonly specificationVersion = \"v3\" as const;\n\treadonly modelId: OpenAICodexModelId;\n\n\tprivate readonly config: OpenAICodexLanguageModelConfig;\n\n\tconstructor(modelId: OpenAICodexModelId, config: OpenAICodexLanguageModelConfig) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t}\n\n\tget provider(): string {\n\t\treturn this.config.provider;\n\t}\n\n\tget supportedUrls(): Record<string, RegExp[]> {\n\t\treturn {};\n\t}\n\n\tprivate getArgs(options: LanguageModelV3CallOptions): {\n\t\targs: Record<string, unknown>;\n\t\twarnings: SharedV3Warning[];\n\t\tgrammarToolInputProperties: ReadonlyMap<string, string>;\n\t} {\n\t\tconst warnings: SharedV3Warning[] = [];\n\n\t\tif (options.topP != null) warnings.push({ type: \"unsupported\", feature: \"topP\" });\n\t\tif (options.topK != null) warnings.push({ type: \"unsupported\", feature: \"topK\" });\n\t\tif (options.presencePenalty != null) warnings.push({ type: \"unsupported\", feature: \"presencePenalty\" });\n\t\tif (options.frequencyPenalty != null) warnings.push({ type: \"unsupported\", feature: \"frequencyPenalty\" });\n\t\tif (options.seed != null) warnings.push({ type: \"unsupported\", feature: \"seed\" });\n\t\tif (options.stopSequences != null) warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n\t\tif (options.maxOutputTokens != null) {\n\t\t\t// The ChatGPT Codex backend rejects max_output_tokens with a 400.\n\t\t\twarnings.push({ type: \"unsupported\", feature: \"maxOutputTokens\" });\n\t\t}\n\t\tif (options.responseFormat?.type === \"json\" && options.responseFormat.schema === undefined) {\n\t\t\twarnings.push({ type: \"unsupported\", feature: \"responseFormat\" });\n\t\t}\n\n\t\tconst codexOptions = (options.providerOptions?.[\"openai-codex\"] ?? {}) as OpenAICodexLanguageModelOptions;\n\t\tconst deferredToolsMode = resolveOpenAICodexDeferredToolsMode(this.config.compat);\n\t\tconst deferredToolNames = deferredToolsMode ? collectOpenAICodexDeferredToolNames(options.prompt) : undefined;\n\t\tconst tools = prepareOpenAICodexTools({\n\t\t\ttools: options.tools,\n\t\t\ttoolChoice: options.toolChoice,\n\t\t\t...(deferredToolNames !== undefined && { deferredToolNames }),\n\t\t});\n\t\tconst { instructions, input } = convertToOpenAICodexPrompt(options.prompt, {\n\t\t\tdeferredTools: tools.deferredCodexTools,\n\t\t\t...(deferredToolsMode !== undefined && { deferredToolsMode }),\n\t\t\tgrammarToolInputProperties: tools.grammarToolInputProperties,\n\t\t\tsupportsImages: this.config.compat?.supportsImages ?? false,\n\t\t});\n\t\twarnings.push(...tools.warnings);\n\n\t\tconst text: Record<string, unknown> = { verbosity: codexOptions.textVerbosity ?? \"low\" };\n\t\tif (options.responseFormat?.type === \"json\" && options.responseFormat.schema !== undefined) {\n\t\t\ttext.format = {\n\t\t\t\ttype: \"json_schema\",\n\t\t\t\tstrict: true,\n\t\t\t\tschema: options.responseFormat.schema,\n\t\t\t\tname: options.responseFormat.name ?? \"codex_output_schema\",\n\t\t\t};\n\t\t}\n\n\t\tconst args: Record<string, unknown> = {\n\t\t\tmodel: this.modelId,\n\t\t\t// The ChatGPT backend rejects stored responses for Codex subscriptions.\n\t\t\tstore: false,\n\t\t\tinstructions,\n\t\t\tinput,\n\t\t\ttool_choice: tools.codexToolChoice ?? \"auto\",\n\t\t\tparallel_tool_calls: true,\n\t\t\tinclude: [\"reasoning.encrypted_content\"],\n\t\t\ttext,\n\t\t};\n\n\t\tif (tools.codexTools) args.tools = tools.codexTools;\n\t\tif (options.temperature != null) args.temperature = options.temperature;\n\n\t\tconst promptCacheKey = clampOpenAICodexPromptCacheKey(this.config.sessionId);\n\t\tif (promptCacheKey) args.prompt_cache_key = promptCacheKey;\n\n\t\tconst serviceTier = codexOptions.serviceTier ?? this.config.serviceTier;\n\t\tif (serviceTier) args.service_tier = serviceTier;\n\n\t\tif (codexOptions.reasoningEffort) {\n\t\t\targs.reasoning = {\n\t\t\t\teffort: codexOptions.reasoningEffort,\n\t\t\t\tsummary: codexOptions.reasoningSummary ?? \"auto\",\n\t\t\t};\n\t\t}\n\n\t\treturn { args, warnings, grammarToolInputProperties: tools.grammarToolInputProperties };\n\t}\n\n\tasync doGenerate(options: LanguageModelV3CallOptions): Promise<LanguageModelV3GenerateResult> {\n\t\tconst { stream, request, response } = await this.doStream(options);\n\n\t\tconst content: LanguageModelV3Content[] = [];\n\t\tconst textBlocks = new Map<string, Extract<LanguageModelV3Content, { type: \"text\" }>>();\n\t\tconst reasoningBlocks = new Map<string, Extract<LanguageModelV3Content, { type: \"reasoning\" }>>();\n\t\tconst warnings: SharedV3Warning[] = [];\n\t\tlet finishReason: LanguageModelV3FinishReason = { unified: \"other\", raw: undefined };\n\t\tlet usage: LanguageModelV3Usage = convertOpenAICodexUsage(undefined);\n\t\tlet responseId: string | undefined;\n\t\tlet responseModelId: string | undefined;\n\n\t\tconst reader = stream.getReader();\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\n\t\t\tswitch (value.type) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\t\twarnings.push(...value.warnings);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\tresponseId = value.id;\n\t\t\t\t\tresponseModelId = value.modelId;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"text-start\": {\n\t\t\t\t\tconst block = { type: \"text\" as const, text: \"\" };\n\t\t\t\t\ttextBlocks.set(value.id, block);\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-delta\": {\n\t\t\t\t\tconst block = textBlocks.get(value.id);\n\t\t\t\t\tif (block) block.text += value.delta;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-end\": {\n\t\t\t\t\tconst block = textBlocks.get(value.id);\n\t\t\t\t\tif (block && value.providerMetadata !== undefined) block.providerMetadata = value.providerMetadata;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\tconst block = { type: \"reasoning\" as const, text: \"\" };\n\t\t\t\t\treasoningBlocks.set(value.id, block);\n\t\t\t\t\tcontent.push(block);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-delta\": {\n\t\t\t\t\tconst block = reasoningBlocks.get(value.id);\n\t\t\t\t\tif (block) block.text += value.delta;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-end\": {\n\t\t\t\t\tconst block = reasoningBlocks.get(value.id);\n\t\t\t\t\tif (block && value.providerMetadata !== undefined) block.providerMetadata = value.providerMetadata;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-call\":\n\t\t\t\t\tcontent.push(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tfinishReason = value.finishReason;\n\t\t\t\t\tusage = value.usage;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tthrow value.error instanceof Error ? value.error : new Error(String(value.error));\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: content.filter((part) =>\n\t\t\t\tpart.type === \"text\" || part.type === \"reasoning\"\n\t\t\t\t\t? part.text !== \"\" || part.providerMetadata !== undefined\n\t\t\t\t\t: true,\n\t\t\t),\n\t\t\tfinishReason,\n\t\t\tusage,\n\t\t\t...(request !== undefined && { request }),\n\t\t\tresponse: {\n\t\t\t\t...response,\n\t\t\t\t...(responseId !== undefined && { id: responseId }),\n\t\t\t\t...(responseModelId !== undefined && { modelId: responseModelId }),\n\t\t\t},\n\t\t\twarnings,\n\t\t};\n\t}\n\n\tasync doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {\n\t\tconst { args, warnings, grammarToolInputProperties } = this.getArgs(options);\n\t\tconst body = { ...args, stream: true };\n\t\tconst url = resolveOpenAICodexUrl(this.config.baseURL);\n\n\t\tconst headers = cleanHeaders({\n\t\t\t...(await this.config.headers()),\n\t\t\t...options.headers,\n\t\t});\n\t\tconst bodyJson = JSON.stringify(body);\n\t\tconst compressedBody = compressOpenAICodexRequest(bodyJson);\n\t\tif (compressedBody) headers[\"content-encoding\"] = \"zstd\";\n\n\t\tconst fetchImpl = this.config.fetch ?? globalThis.fetch;\n\t\tconst response = await fetchImpl(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: compressedBody ?? bodyJson,\n\t\t\t...(options.abortSignal !== undefined && { signal: options.abortSignal }),\n\t\t}).catch((error: unknown) => {\n\t\t\tthrow openAICodexFetchError(error, url, body);\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow await createOpenAICodexAPICallError({ response, url, requestBodyValues: body });\n\t\t}\n\t\tif (!response.body) {\n\t\t\tthrow new Error(\"openAI codex response has no body\");\n\t\t}\n\n\t\tconst responseHeaders: Record<string, string> = {};\n\t\tresponse.headers.forEach((value, key) => {\n\t\t\tresponseHeaders[key] = value;\n\t\t});\n\n\t\treturn {\n\t\t\tstream: parseOpenAICodexSSEStream(response.body).pipeThrough(\n\t\t\t\tthis.createTransformStream(warnings, options.includeRawChunks ?? false, grammarToolInputProperties, {\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: body,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t}),\n\t\t\t),\n\t\t\trequest: { body },\n\t\t\tresponse: { headers: responseHeaders },\n\t\t};\n\t}\n\n\tprivate createTransformStream(\n\t\twarnings: SharedV3Warning[],\n\t\tincludeRawChunks: boolean,\n\t\tgrammarToolInputProperties: ReadonlyMap<string, string>,\n\t\trequest: {\n\t\t\turl: string;\n\t\t\trequestBodyValues: unknown;\n\t\t\tresponseHeaders: Record<string, string>;\n\t\t},\n\t): TransformStream<CodexEvent, LanguageModelV3StreamPart> {\n\t\tlet finishReason: LanguageModelV3FinishReason = { unified: \"other\", raw: undefined };\n\t\tlet usage: OpenAICodexUsage | undefined;\n\t\tlet hasToolCalls = false;\n\t\tlet finished = false;\n\t\tlet servedServiceTier: string | undefined;\n\t\t// function_call argument deltas arrive keyed by item id; tool parts use the\n\t\t// composite `call_id|item_id` so multi-turn replay can recover both halves.\n\t\tconst toolCallIdsByItemId = new Map<string, string>();\n\t\tconst customToolInputsByItemId = new Map<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\ttoolCallId: string;\n\t\t\t\ttoolName: string;\n\t\t\t\tinputProperty: string;\n\t\t\t\tbuffer: OpenAICodexGrammarInputBuffer;\n\t\t\t}\n\t\t>();\n\t\tconst finish = (controller: TransformStreamDefaultController<LanguageModelV3StreamPart>): void => {\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"finish\",\n\t\t\t\tfinishReason,\n\t\t\t\tusage: convertOpenAICodexUsage(usage),\n\t\t\t\t// The tier the response was served at decides what it costs, and it is\n\t\t\t\t// not always the tier that was requested.\n\t\t\t\t...(servedServiceTier === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { providerMetadata: { \"openai-codex\": { serviceTier: servedServiceTier } } }),\n\t\t\t});\n\t\t};\n\t\tconst fail = (controller: TransformStreamDefaultController<LanguageModelV3StreamPart>, error: unknown): void => {\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\tcontroller.enqueue({ type: \"error\", error });\n\t\t\tcontroller.terminate();\n\t\t};\n\n\t\tconst handleOutputItemAdded = (\n\t\t\titem: CodexEvent,\n\t\t\tcontroller: TransformStreamDefaultController<LanguageModelV3StreamPart>,\n\t\t) => {\n\t\t\tconst itemType = asString(item.type);\n\t\t\tconst itemId = asString(item.id);\n\t\t\tif (!itemType || !itemId) return;\n\n\t\t\tif (itemType === \"message\") {\n\t\t\t\tcontroller.enqueue({ type: \"text-start\", id: itemId });\n\t\t\t} else if (itemType === \"reasoning\") {\n\t\t\t\tcontroller.enqueue({ type: \"reasoning-start\", id: itemId });\n\t\t\t} else if (itemType === \"function_call\") {\n\t\t\t\tconst toolCallId = joinToolCallId(asString(item.call_id) ?? itemId, itemId);\n\t\t\t\ttoolCallIdsByItemId.set(itemId, toolCallId);\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"tool-input-start\",\n\t\t\t\t\tid: toolCallId,\n\t\t\t\t\ttoolName: asString(item.name) ?? \"\",\n\t\t\t\t});\n\t\t\t} else if (itemType === \"custom_tool_call\") {\n\t\t\t\tconst toolName = asString(item.name) ?? \"\";\n\t\t\t\tconst inputProperty = grammarToolInputProperties.get(toolName) ?? \"input\";\n\t\t\t\tconst toolCallId = joinToolCallId(asString(item.call_id) ?? itemId, itemId);\n\t\t\t\tcustomToolInputsByItemId.set(itemId, {\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\ttoolName,\n\t\t\t\t\tinputProperty,\n\t\t\t\t\tbuffer: { input: \"\", started: false, closed: false },\n\t\t\t\t});\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-start\", id: toolCallId, toolName });\n\t\t\t}\n\t\t};\n\n\t\tconst handleOutputItemDone = (\n\t\t\titem: CodexEvent,\n\t\t\tcontroller: TransformStreamDefaultController<LanguageModelV3StreamPart>,\n\t\t) => {\n\t\t\tconst itemType = asString(item.type);\n\t\t\tconst itemId = asString(item.id);\n\t\t\tif (!itemType || !itemId) return;\n\n\t\t\tif (itemType === \"message\") {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\tid: itemId,\n\t\t\t\t\tproviderMetadata: { \"openai-codex\": { messageId: itemId } },\n\t\t\t\t});\n\t\t\t} else if (itemType === \"reasoning\") {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\tid: itemId,\n\t\t\t\t\tproviderMetadata: { \"openai-codex\": { reasoningItem: JSON.stringify(item) } },\n\t\t\t\t});\n\t\t\t} else if (itemType === \"function_call\") {\n\t\t\t\tconst toolCallId =\n\t\t\t\t\ttoolCallIdsByItemId.get(itemId) ?? joinToolCallId(asString(item.call_id) ?? itemId, itemId);\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-end\", id: toolCallId });\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\ttoolName: asString(item.name) ?? \"\",\n\t\t\t\t\tinput: asString(item.arguments) ?? \"\",\n\t\t\t\t\t...(asString(item.namespace)\n\t\t\t\t\t\t? { providerMetadata: { \"openai-codex\": { namespace: asString(item.namespace)! } } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t} else if (itemType === \"custom_tool_call\") {\n\t\t\t\tconst state = customToolInputsByItemId.get(itemId);\n\t\t\t\tif (!state) return;\n\t\t\t\tconst input = asString(item.input) ?? state.buffer.input;\n\t\t\t\tconst delta = appendOpenAICodexGrammarInputJsonDelta(state.buffer, state.inputProperty, input, true);\n\t\t\t\tif (delta) controller.enqueue({ type: \"tool-input-delta\", id: state.toolCallId, delta });\n\t\t\t\thasToolCalls = true;\n\t\t\t\tcontroller.enqueue({ type: \"tool-input-end\", id: state.toolCallId });\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId: state.toolCallId,\n\t\t\t\t\ttoolName: state.toolName,\n\t\t\t\t\tinput: JSON.stringify({ [state.inputProperty]: input }),\n\t\t\t\t\t...(asString(item.namespace)\n\t\t\t\t\t\t? { providerMetadata: { \"openai-codex\": { namespace: asString(item.namespace)! } } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\tcustomToolInputsByItemId.delete(itemId);\n\t\t\t}\n\t\t};\n\n\t\treturn new TransformStream<CodexEvent, LanguageModelV3StreamPart>({\n\t\t\tstart(controller) {\n\t\t\t\tcontroller.enqueue({ type: \"stream-start\", warnings });\n\t\t\t},\n\n\t\t\ttransform(event, controller) {\n\t\t\t\tif (includeRawChunks) {\n\t\t\t\t\tcontroller.enqueue({ type: \"raw\", rawValue: event });\n\t\t\t\t}\n\n\t\t\t\tconst type = asString(event.type);\n\t\t\t\tif (!type) return;\n\n\t\t\t\tswitch (type) {\n\t\t\t\t\tcase \"response.created\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tconst id = asString(response?.id);\n\t\t\t\t\t\tconst modelId = asString(response?.model);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"response-metadata\",\n\t\t\t\t\t\t\t...(id !== undefined && { id }),\n\t\t\t\t\t\t\t...(modelId !== undefined && { modelId }),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_item.added\": {\n\t\t\t\t\t\tconst item = asRecord(event.item);\n\t\t\t\t\t\tif (item) handleOutputItemAdded(item, controller);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_text.delta\": {\n\t\t\t\t\t\tconst itemId = asString(event.item_id);\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (itemId && delta) controller.enqueue({ type: \"text-delta\", id: itemId, delta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.reasoning_text.delta\":\n\t\t\t\t\tcase \"response.reasoning_summary_text.delta\": {\n\t\t\t\t\t\tconst itemId = asString(event.item_id);\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tif (itemId && delta) controller.enqueue({ type: \"reasoning-delta\", id: itemId, delta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.function_call_arguments.delta\": {\n\t\t\t\t\t\tconst itemId = asString(event.item_id);\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tconst toolCallId = itemId ? toolCallIdsByItemId.get(itemId) : undefined;\n\t\t\t\t\t\tif (toolCallId && delta) controller.enqueue({ type: \"tool-input-delta\", id: toolCallId, delta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.custom_tool_call_input.delta\": {\n\t\t\t\t\t\tconst itemId = asString(event.item_id);\n\t\t\t\t\t\tconst delta = asString(event.delta);\n\t\t\t\t\t\tconst state = itemId ? customToolInputsByItemId.get(itemId) : undefined;\n\t\t\t\t\t\tif (!state || delta === undefined) break;\n\t\t\t\t\t\tconst jsonDelta = appendOpenAICodexGrammarInputJsonDelta(\n\t\t\t\t\t\t\tstate.buffer,\n\t\t\t\t\t\t\tstate.inputProperty,\n\t\t\t\t\t\t\tstate.buffer.input + delta,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (jsonDelta)\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"tool-input-delta\", id: state.toolCallId, delta: jsonDelta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.custom_tool_call_input.done\": {\n\t\t\t\t\t\tconst itemId = asString(event.item_id);\n\t\t\t\t\t\tconst input = asString(event.input);\n\t\t\t\t\t\tconst state = itemId ? customToolInputsByItemId.get(itemId) : undefined;\n\t\t\t\t\t\tif (!state || input === undefined) break;\n\t\t\t\t\t\tconst jsonDelta = appendOpenAICodexGrammarInputJsonDelta(\n\t\t\t\t\t\t\tstate.buffer,\n\t\t\t\t\t\t\tstate.inputProperty,\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (jsonDelta)\n\t\t\t\t\t\t\tcontroller.enqueue({ type: \"tool-input-delta\", id: state.toolCallId, delta: jsonDelta });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.output_item.done\": {\n\t\t\t\t\t\tconst item = asRecord(event.item);\n\t\t\t\t\t\tif (item) handleOutputItemDone(item, controller);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.completed\":\n\t\t\t\t\tcase \"response.incomplete\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tusage = (response?.usage as OpenAICodexUsage | undefined) ?? usage;\n\t\t\t\t\t\tservedServiceTier = asString(response?.service_tier) ?? servedServiceTier;\n\t\t\t\t\t\tconst status =\n\t\t\t\t\t\t\tasString(response?.status) ?? (type === \"response.incomplete\" ? \"incomplete\" : \"completed\");\n\t\t\t\t\t\tconst incompleteReason = asString(asRecord(response?.incomplete_details)?.reason);\n\t\t\t\t\t\tfinishReason = mapOpenAICodexFinishReason(status, hasToolCalls, incompleteReason);\n\t\t\t\t\t\tfinish(controller);\n\t\t\t\t\t\tcontroller.terminate();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"response.failed\": {\n\t\t\t\t\t\tconst response = asRecord(event.response);\n\t\t\t\t\t\tconst error = asRecord(response?.error);\n\t\t\t\t\t\tfinishReason = { unified: \"error\", raw: \"failed\" };\n\t\t\t\t\t\tfail(\n\t\t\t\t\t\t\tcontroller,\n\t\t\t\t\t\t\tcreateOpenAICodexStreamError({\n\t\t\t\t\t\t\t\terror: error ?? { message: \"OpenAI Codex response failed\" },\n\t\t\t\t\t\t\t\t...request,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tconst code = asString(event.code);\n\t\t\t\t\t\tfinishReason = { unified: \"error\", raw: code ?? \"error\" };\n\t\t\t\t\t\tfail(controller, createOpenAICodexStreamError({ error: event, ...request }));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// Ignore lifecycle events we do not surface (content_part, in_progress, ...).\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tflush(controller) {\n\t\t\t\tif (!finished) {\n\t\t\t\t\tfinished = true;\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terror: createOpenAICodexPrematureCloseError(request),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t}\n}\n","import { LoadAPIKeyError, NoSuchModelError, type LanguageModelV3, type ProviderV3 } from \"@ai-sdk/provider\";\nimport { getOpenAICodexAccountId } from \"../../oauth/openai/codex.ts\";\nimport {\n\tOPENAI_CODEX_DEFAULT_BASE_URL,\n\tOpenAICodexLanguageModel,\n\tclampOpenAICodexPromptCacheKey,\n\ttype OpenAICodexModelId,\n\ttype OpenAICodexCompatibility,\n\ttype OpenAICodexServiceTier,\n} from \"./codex-language-model.ts\";\n\nexport const OPENAI_CODEX_API_KEY_ENV = \"OPENAI_CODEX_API_KEY\";\n\nconst DEFAULT_ORIGINATOR = \"codework\";\n\nexport interface OpenAICodexProvider extends ProviderV3 {\n\t(modelId: OpenAICodexModelId): LanguageModelV3;\n\n\tlanguageModel(modelId: OpenAICodexModelId): LanguageModelV3;\n\n\t/** Alias for `languageModel`; the Codex API only speaks the Responses protocol. */\n\tresponses(modelId: OpenAICodexModelId): LanguageModelV3;\n}\n\nexport interface OpenAICodexProviderSettings {\n\t/**\n\t * Base URL for the Codex backend.\n\t * Defaults to `https://chatgpt.com/backend-api`.\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * ChatGPT OAuth access token (JWT) used as the API key.\n\t * Defaults to the `OPENAI_CODEX_API_KEY` environment variable.\n\t * A function can be passed to resolve a fresh token per request.\n\t */\n\tapiKey?: string | (() => string | PromiseLike<string>);\n\n\t/**\n\t * ChatGPT account id sent as the `chatgpt-account-id` header.\n\t * Extracted from the JWT access token when omitted.\n\t */\n\taccountId?: string;\n\n\t/** Custom headers merged into every request. */\n\theaders?: Record<string, string>;\n\n\t/** Custom fetch implementation. */\n\tfetch?: typeof globalThis.fetch;\n\n\t/** Session id used for request identity, the `session-id` header, and prompt cache affinity. */\n\tsessionId?: string;\n\n\t/** Default service tier for requests. */\n\tserviceTier?: OpenAICodexServiceTier;\n\n\t/** `originator` header value; defaults to `codework`. */\n\toriginator?: string;\n\n\t/** Model capabilities supplied by aikit or the direct caller; absent flags are disabled. */\n\tcompat?: OpenAICodexCompatibility;\n}\n\nasync function resolveApiKey(settings: OpenAICodexProviderSettings): Promise<string> {\n\tconst apiKey =\n\t\ttypeof settings.apiKey === \"function\"\n\t\t\t? await settings.apiKey()\n\t\t\t: (settings.apiKey ?? (typeof process === \"undefined\" ? undefined : process.env[OPENAI_CODEX_API_KEY_ENV]));\n\n\tif (!apiKey) {\n\t\tthrow new LoadAPIKeyError({\n\t\t\tmessage: `OpenAI Codex API key is missing. Pass it using the 'apiKey' option or the ${OPENAI_CODEX_API_KEY_ENV} environment variable.`,\n\t\t});\n\t}\n\n\treturn apiKey;\n}\n\nfunction resolveAccountId(settings: OpenAICodexProviderSettings, apiKey: string): string {\n\tconst accountId = settings.accountId ?? getOpenAICodexAccountId(apiKey);\n\tif (!accountId) {\n\t\tthrow new LoadAPIKeyError({\n\t\t\tmessage:\n\t\t\t\t\"Failed to extract the ChatGPT account id from the OpenAI Codex access token. \" +\n\t\t\t\t\"Provide it using the 'accountId' option or pass a valid ChatGPT OAuth JWT as the API key.\",\n\t\t});\n\t}\n\treturn accountId;\n}\n\nexport function createOpenAICodex(options: OpenAICodexProviderSettings = {}): OpenAICodexProvider {\n\tconst baseURL = options.baseURL?.replace(/\\/+$/, \"\") || OPENAI_CODEX_DEFAULT_BASE_URL;\n\tconst sessionId = clampOpenAICodexPromptCacheKey(options.sessionId);\n\n\tconst getHeaders = async (): Promise<Record<string, string | undefined>> => {\n\t\tconst apiKey = await resolveApiKey(options);\n\t\tconst accountId = resolveAccountId(options, apiKey);\n\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\"OpenAI-Beta\": \"responses=experimental\",\n\t\t\toriginator: options.originator ?? DEFAULT_ORIGINATOR,\n\t\t\taccept: \"text/event-stream\",\n\t\t\t\"content-type\": \"application/json\",\n\t\t\t...(sessionId ? { \"session-id\": sessionId, \"x-client-request-id\": sessionId } : {}),\n\t\t\t...options.headers,\n\t\t};\n\t};\n\n\tconst createLanguageModel = (modelId: OpenAICodexModelId) =>\n\t\tnew OpenAICodexLanguageModel(modelId, {\n\t\t\tprovider: \"openai-codex\",\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\t...(options.fetch !== undefined && { fetch: options.fetch }),\n\t\t\t...(sessionId !== undefined && { sessionId }),\n\t\t\t...(options.serviceTier !== undefined && { serviceTier: options.serviceTier }),\n\t\t\t...(options.compat !== undefined && { compat: options.compat }),\n\t\t});\n\n\tconst provider = function (modelId: OpenAICodexModelId) {\n\t\tif (new.target) {\n\t\t\tthrow new Error(\"openAI codex model function cannot be called with the new keyword.\");\n\t\t}\n\t\treturn createLanguageModel(modelId);\n\t};\n\n\tprovider.specificationVersion = \"v3\" as const;\n\tprovider.languageModel = createLanguageModel;\n\tprovider.responses = createLanguageModel;\n\n\tprovider.embeddingModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n\t};\n\tprovider.textEmbeddingModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n\t};\n\tprovider.imageModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n\t};\n\n\treturn provider as OpenAICodexProvider;\n}\n\n/**\n * Default provider instance using `OPENAI_CODEX_API_KEY`.\n */\nexport const openaiCodex = createOpenAICodex();\n"],"mappings":";;;;;;;;;;;;;;;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AC;CAChE;CAEA,OAAO;AACR;;;;AAKA,MAAa,cAAc,kBAAkB"}
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as KnownProviderEnum, t as APIMethodEnum } from "./model-
|
|
1
|
+
import { i as KnownProviderEnum, t as APIMethodEnum } from "./model-D-FoGzVN.mjs";
|
|
2
2
|
//#region src/llm/registry.ts
|
|
3
3
|
const DEFAULT_AI_SDK_FALLBACK = "@ai-sdk/openai-compatible";
|
|
4
4
|
const AI_SDK_PACKAGE_TO_PROTOCOL = {
|
|
@@ -22,8 +22,8 @@ const PROVIDER_LOADERS = {
|
|
|
22
22
|
"@ai-sdk/openai-compatible": () => import("@ai-sdk/openai-compatible").then((m) => m.createOpenAICompatible),
|
|
23
23
|
"@openrouter/ai-sdk-provider": () => import("@openrouter/ai-sdk-provider").then((m) => m.createOpenRouter),
|
|
24
24
|
"@ai-sdk/xai": () => import("@ai-sdk/xai").then((m) => m.createXai),
|
|
25
|
-
"@codeworksh/ai-sdk-openai-codex": () => import("./openai-codex-
|
|
26
|
-
"@codeworksh/ai-sdk-github-copilot": () => import("./github-copilot-
|
|
25
|
+
"@codeworksh/ai-sdk-openai-codex": () => import("./openai-codex-CIBVNhQx.mjs").then((m) => m.createOpenAICodex),
|
|
26
|
+
"@codeworksh/ai-sdk-github-copilot": () => import("./github-copilot-CLJx-bcP.mjs").then((m) => m.createGitHubCopilot)
|
|
27
27
|
};
|
|
28
28
|
function isAISDKPackage(value) {
|
|
29
29
|
return value in AI_SDK_PACKAGE_TO_PROTOCOL;
|
|
@@ -64,4 +64,4 @@ function resolveLanguageModel(provider, model, methodOverride) {
|
|
|
64
64
|
//#endregion
|
|
65
65
|
export { protocolForPackage as a, packageForModel as i, isAISDKPackage as n, resolveLanguageModel as o, loadProviderFactory as r, DEFAULT_AI_SDK_FALLBACK as t };
|
|
66
66
|
|
|
67
|
-
//# sourceMappingURL=registry-
|
|
67
|
+
//# sourceMappingURL=registry-CfGgGfSs.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry-
|
|
1
|
+
{"version":3,"file":"registry-CfGgGfSs.mjs","names":[],"sources":["../../src/llm/registry.ts"],"sourcesContent":["import type { LanguageModel } from \"ai\";\nimport * as Model from \"../model/model.ts\";\n\nexport const DEFAULT_AI_SDK_FALLBACK = \"@ai-sdk/openai-compatible\";\n\nexport const AI_SDK_PACKAGE_TO_PROTOCOL = {\n\t\"@ai-sdk/anthropic\": Model.KnownProviderEnum.anthropic,\n\t\"@ai-sdk/google\": Model.KnownProviderEnum.google,\n\t\"@ai-sdk/google-vertex\": Model.KnownProviderEnum.googleVertex,\n\t\"@ai-sdk/google-vertex/anthropic\": Model.KnownProviderEnum.googleVertexAnthropic,\n\t\"@ai-sdk/openai\": Model.KnownProviderEnum.openai,\n\t\"@ai-sdk/openai-compatible\": Model.KnownProviderEnum.openaiCompatible,\n\t\"@codeworksh/ai-sdk-openai-codex\": Model.KnownProviderEnum.openaiCodex, // custom provider npm ID\n\t\"@codeworksh/ai-sdk-github-copilot\": Model.KnownProviderEnum.githubCopilot, // custom provider npm ID\n\t\"@openrouter/ai-sdk-provider\": Model.KnownProviderEnum.openrouter,\n\t\"@ai-sdk/xai\": Model.KnownProviderEnum.xai,\n} as const;\n\nexport type AISDKPackage = keyof typeof AI_SDK_PACKAGE_TO_PROTOCOL;\nexport type AISDKProtocol = (typeof AI_SDK_PACKAGE_TO_PROTOCOL)[AISDKPackage];\n\ntype ProviderFactory = (options?: Record<string, unknown>) => unknown;\n\nconst PROVIDER_LOADERS: Record<AISDKPackage, () => Promise<ProviderFactory>> = {\n\t\"@ai-sdk/anthropic\": () => import(\"@ai-sdk/anthropic\").then((m) => m.createAnthropic as ProviderFactory),\n\t\"@ai-sdk/google\": () => import(\"@ai-sdk/google\").then((m) => m.createGoogleGenerativeAI as ProviderFactory),\n\t\"@ai-sdk/google-vertex\": () => import(\"@ai-sdk/google-vertex\").then((m) => m.createVertex as ProviderFactory),\n\t\"@ai-sdk/google-vertex/anthropic\": () =>\n\t\timport(\"@ai-sdk/google-vertex/anthropic\").then((m) => m.createVertexAnthropic as ProviderFactory),\n\t\"@ai-sdk/openai\": () => import(\"@ai-sdk/openai\").then((m) => m.createOpenAI as ProviderFactory),\n\t\"@ai-sdk/openai-compatible\": () =>\n\t\timport(\"@ai-sdk/openai-compatible\").then((m) => m.createOpenAICompatible as unknown as ProviderFactory),\n\t\"@openrouter/ai-sdk-provider\": () =>\n\t\timport(\"@openrouter/ai-sdk-provider\").then((m) => m.createOpenRouter as ProviderFactory),\n\t\"@ai-sdk/xai\": () => import(\"@ai-sdk/xai\").then((m) => m.createXai as ProviderFactory),\n\t// Local provider for OpenAI Codex subscriptions (ChatGPT OAuth); the package\n\t// name is virtual and resolves to src/providers/openai-codex.\n\t\"@codeworksh/ai-sdk-openai-codex\": () =>\n\t\timport(\"../providers/openai-codex/index.ts\").then((m) => m.createOpenAICodex as ProviderFactory),\n\t// Local provider for GitHub Copilot; the package name is virtual and resolves\n\t// to src/providers/github-copilot.\n\t\"@codeworksh/ai-sdk-github-copilot\": () =>\n\t\timport(\"../providers/github-copilot/index.ts\").then((m) => m.createGitHubCopilot as ProviderFactory),\n};\n\nexport function isAISDKPackage(value: string): value is AISDKPackage {\n\treturn value in AI_SDK_PACKAGE_TO_PROTOCOL;\n}\n\nexport function packageForModel(model: Model.Info): AISDKPackage {\n\tconst npm = model.npm ?? DEFAULT_AI_SDK_FALLBACK;\n\treturn isAISDKPackage(npm) ? npm : DEFAULT_AI_SDK_FALLBACK;\n}\n\nexport function protocolForPackage(npm: string | undefined): AISDKProtocol {\n\tconst resolved = npm && isAISDKPackage(npm) ? npm : DEFAULT_AI_SDK_FALLBACK;\n\treturn AI_SDK_PACKAGE_TO_PROTOCOL[resolved];\n}\n\nexport async function loadProviderFactory(npm: AISDKPackage): Promise<ProviderFactory> {\n\treturn PROVIDER_LOADERS[npm]();\n}\n\ntype ProviderWithMethods = {\n\t(modelId: string): LanguageModel;\n\tlanguageModel?: (modelId: string) => LanguageModel;\n\tchat?: (modelId: string) => LanguageModel;\n\tchatModel?: (modelId: string) => LanguageModel;\n\tcompletion?: (modelId: string) => LanguageModel;\n\tcompletionModel?: (modelId: string) => LanguageModel;\n\tmessages?: (modelId: string) => LanguageModel;\n\tresponses?: (modelId: string) => LanguageModel;\n};\n\nfunction defaultMethodForModel(model: Model.Info): Model.APIMethodEnum {\n\tif (\n\t\tmodel.protocol === Model.KnownProviderEnum.openai ||\n\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex ||\n\t\tmodel.protocol === Model.KnownProviderEnum.xai\n\t) {\n\t\treturn Model.APIMethodEnum.responses;\n\t}\n\treturn Model.APIMethodEnum.languageModel;\n}\n\nexport function resolveLanguageModel(\n\tprovider: unknown,\n\tmodel: Model.Info,\n\tmethodOverride?: Model.APIMethodEnum,\n): LanguageModel {\n\tconst modelId = model.api?.id ?? model.id;\n\tconst method = methodOverride ?? model.api?.method ?? defaultMethodForModel(model);\n\tconst callable = provider as ProviderWithMethods;\n\n\tif (method === Model.APIMethodEnum.responses && callable.responses) return callable.responses(modelId);\n\tif (method === Model.APIMethodEnum.messages && callable.messages) return callable.messages(modelId);\n\tif (method === Model.APIMethodEnum.chat) {\n\t\tif (callable.chat) return callable.chat(modelId);\n\t\tif (callable.chatModel) return callable.chatModel(modelId);\n\t}\n\tif (method === Model.APIMethodEnum.completion) {\n\t\tif (callable.completion) return callable.completion(modelId);\n\t\tif (callable.completionModel) return callable.completionModel(modelId);\n\t}\n\tif (method === Model.APIMethodEnum.completionModel && callable.completionModel) {\n\t\treturn callable.completionModel(modelId);\n\t}\n\tif (callable.languageModel) return callable.languageModel(modelId);\n\treturn callable(modelId);\n}\n"],"mappings":";;AAGA,MAAa,0BAA0B;AAEvC,MAAa,6BAA6B;CACzC,qBAAA,kBAA6C;CAC7C,kBAAA,kBAA0C;CAC1C,yBAAA,kBAAiD;CACjD,mCAAA,kBAA2D;CAC3D,kBA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A2B;AAC5B;AAEA,SAAgB,qBACf,UACA,OACA,gBACgB;CAChB,MAAM,UAAU,MAAM,KAAK,MAAM,MAAM;CACvC,MAAM,SAAS,kBAAkB,MAAM,KAAK,UAAU,sBAAsB,KAAK;CACjF,MAAM,WAAW;CAEjB,IAAI,WAAA,cAA+B,aAAa,SAAS,WAAW,OAAO,SAAS,UAAU,OAAO;CACrG,IAAI,WAAA,cAA+B,YAAY,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO;CAClG,IAAI,WAAA,cAA+B,MAAM;EACxC,IAAI,SAAS,MAAM,OAAO,SAAS,KAAK,OAAO;EAC/C,IAAI,SAAS,WAAW,OAAO,SAAS,UAAU,OAAO;CAC1D;CACA,IAAI,WAAA,cAA+B,YAAY;EAC9C,IAAI,SAAS,YAAY,OAAO,SAAS,WAAW,OAAO;EAC3D,IAAI,SAAS,iBAAiB,OAAO,SAAS,gBAAgB,OAAO;CACtE;CACA,IAAI,WAAA,cAA+B,mBAAmB,SAAS,iBAC9D,OAAO,SAAS,gBAAgB,OAAO;CAExC,IAAI,SAAS,eAAe,OAAO,SAAS,cAAc,OAAO;CACjE,OAAO,SAAS,OAAO;AACxB"}
|
package/failure-CN0horoO.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"failure-CN0horoO.mjs","names":[],"sources":["../../src/llm/failure.ts"],"sourcesContent":["import {\n\tAPICallError,\n\tEmptyResponseBodyError,\n\tInvalidArgumentError,\n\tInvalidPromptError,\n\tInvalidResponseDataError,\n\tJSONParseError,\n\tLoadAPIKeyError,\n\tLoadSettingError,\n\tNoContentGeneratedError,\n\tNoSuchModelError,\n\tTypeValidationError,\n\tUnsupportedFunctionalityError,\n} from \"@ai-sdk/provider\";\nimport { RetryError, StreamProviderError } from \"ai\";\nimport type { Failure } from \"./failure/schema.ts\";\n\nexport * from \"./failure/schema.ts\";\n\ntype Metadata = Omit<Failure, \"_tag\" | \"reason\">;\n\nconst record = (value: unknown): Record<string, unknown> | undefined =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n\nconst nonEmptyString = (value: unknown): string | undefined =>\n\ttypeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n\nconst normalizeMessage = (message: string): string => {\n\tconst trimmed = message.trim().replace(/[.!?]+$/u, \"\");\n\treturn trimmed.replace(/^[A-Za-z]+/u, (word) => word.toLowerCase());\n};\n\nconst errorMessage = (error: unknown): string => {\n\tconst value = record(error);\n\tconst data = record(value?.data);\n\tif (value?.name === \"ProtocolAuthError\") {\n\t\treturn normalizeMessage(nonEmptyString(data?.message) ?? \"provider credentials are missing\");\n\t}\n\tif (error instanceof Error) return normalizeMessage(nonEmptyString(error.message) ?? error.name);\n\treturn normalizeMessage(nonEmptyString(error) ?? \"the provider request failed for an unknown reason\");\n};\n\nconst isProtocolAuthError = (error: unknown): boolean => {\n\tconst value = record(error);\n\treturn value?.name === \"ProtocolAuthError\";\n};\n\nconst errorCode = (data: unknown): string | undefined => {\n\tconst top = record(data);\n\tconst nested = record(top?.error);\n\treturn (\n\t\tnonEmptyString(top?.code) ??\n\t\tnonEmptyString(top?.type) ??\n\t\tnonEmptyString(nested?.code) ??\n\t\tnonEmptyString(nested?.type)\n\t);\n};\n\nconst header = (headers: Record<string, string> | undefined, name: string): string | undefined => {\n\tif (headers === undefined) return undefined;\n\tconst expected = name.toLowerCase();\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() === expected) return nonEmptyString(value);\n\t}\n};\n\n/** The server's requested wait, in the three forms providers send: `retry-after-ms`, seconds, or an HTTP date. */\nconst retryAfter = (headers: Record<string, string> | undefined): number | undefined => {\n\tconst millis = Number(header(headers, \"retry-after-ms\"));\n\tif (Number.isFinite(millis) && millis >= 0) return millis;\n\tconst value = header(headers, \"retry-after\");\n\tif (value === undefined) return undefined;\n\tconst seconds = Number(value);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1_000;\n\tconst date = Date.parse(value);\n\tif (Number.isFinite(date)) return Math.max(0, date - Date.now());\n};\n\nconst apiMetadata = (error: APICallError): Metadata => {\n\tconst code = errorCode(error.data);\n\tconst data = record(error.data);\n\tconst nested = record(data?.error);\n\tconst structuredMessage = nonEmptyString(data?.message) ?? nonEmptyString(nested?.message);\n\tconst message = normalizeMessage(\n\t\tstructuredMessage ??\n\t\t\t(error.responseBody !== undefined && error.message.includes(error.responseBody)\n\t\t\t\t? `provider request failed${error.statusCode === undefined ? \"\" : ` with http ${error.statusCode}`}`\n\t\t\t\t: errorMessage(error)),\n\t);\n\tconst requestId =\n\t\theader(error.responseHeaders, \"x-request-id\") ??\n\t\theader(error.responseHeaders, \"x-oai-request-id\") ??\n\t\theader(error.responseHeaders, \"request-id\") ??\n\t\theader(error.responseHeaders, \"cf-ray\");\n\tconst retryAfterMs = retryAfter(error.responseHeaders);\n\treturn {\n\t\tmessage,\n\t\tretryable: error.isRetryable,\n\t\t...(error.statusCode === undefined ? {} : { status: error.statusCode }),\n\t\t...(code === undefined ? {} : { code }),\n\t\t...(requestId === undefined ? {} : { requestId }),\n\t\t...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n\t};\n};\n\nconst includes = (value: string | undefined, terms: ReadonlyArray<string>): boolean =>\n\tvalue !== undefined && terms.some((term) => value.toLowerCase().includes(term));\n\n/** Classify by provider error code, then HTTP status; shared by request and in-stream failures. */\nconst classify = (statusCode: number | undefined, details: Metadata): Failure => {\n\tif (includes(details.code, [\"quota\", \"billing\", \"credit\"])) return { _tag: \"Quota\", ...details };\n\tif (\n\t\tincludes(details.code, [\n\t\t\t\"content_filter\",\n\t\t\t\"content_policy\",\n\t\t\t\"safety\",\n\t\t\t\"cyber_policy\",\n\t\t\t\"bio_policy\",\n\t\t\t\"misalignment_policy\",\n\t\t])\n\t) {\n\t\treturn { _tag: \"ContentPolicy\", ...details };\n\t}\n\tif (statusCode === 401) return { _tag: \"Authentication\", reason: \"invalid\", ...details };\n\tif (statusCode === 403) return { _tag: \"Authorization\", ...details };\n\tif (statusCode === 404) return { _tag: \"ModelUnavailable\", ...details };\n\tif (statusCode === 408) return { _tag: \"Timeout\", ...details };\n\tif (statusCode === 429) return { _tag: \"RateLimit\", ...details };\n\tif (statusCode !== undefined && statusCode >= 500) return { _tag: \"Unavailable\", ...details };\n\tif (statusCode === undefined) return { _tag: \"Transport\", ...details };\n\tif (statusCode >= 400 && statusCode < 500) return { _tag: \"InvalidRequest\", ...details };\n\treturn { _tag: \"Unknown\", ...details };\n};\n\n/**\n * A failure the provider reported after the stream started, e.g. OpenAI's\n * `context_length_exceeded` event, which it sends instead of an HTTP 400 at random.\n */\nconst fromStreamProvider = (error: StreamProviderError): Failure => {\n\t// Like apiMetadata: providers put the discriminator in `code`, or only in `type`.\n\tconst code = error.code === undefined ? error.type : String(error.code);\n\treturn classify(error.statusCode, {\n\t\tmessage: normalizeMessage(errorMessage(error)),\n\t\tretryable: error.isRetryable,\n\t\t...(error.statusCode === undefined ? {} : { status: error.statusCode }),\n\t\t...(code === undefined ? {} : { code }),\n\t});\n};\n\nconst resemblesTimeout = (error: unknown): boolean => {\n\tconst value = error instanceof Error ? `${error.name} ${error.message}` : String(error);\n\treturn /timeout|timed out/i.test(value);\n};\n\nconst resemblesTransportFailure = (error: unknown): boolean => {\n\tif (error instanceof TypeError) return true;\n\tconst value = error instanceof Error ? `${error.name} ${error.message}` : String(error);\n\treturn /fetch|network|socket|connection|econn|dns/i.test(value);\n};\n\n/** Normalize AI SDK and provider exceptions without retaining request bodies, response bodies, or headers. */\nexport function normalize(error: unknown): Failure {\n\tif (RetryError.isInstance(error) && error.lastError !== undefined && error.lastError !== error) {\n\t\treturn normalize(error.lastError);\n\t}\n\tif (LoadAPIKeyError.isInstance(error) || isProtocolAuthError(error)) {\n\t\treturn { _tag: \"Authentication\", reason: \"missing\", message: errorMessage(error), retryable: false };\n\t}\n\tif (LoadSettingError.isInstance(error)) {\n\t\treturn { _tag: \"Configuration\", message: errorMessage(error), retryable: false };\n\t}\n\tif (NoSuchModelError.isInstance(error)) {\n\t\treturn { _tag: \"ModelUnavailable\", message: errorMessage(error), retryable: false };\n\t}\n\tif (APICallError.isInstance(error)) return classify(error.statusCode, apiMetadata(error));\n\tif (StreamProviderError.isInstance(error)) return fromStreamProvider(error);\n\tif (\n\t\tInvalidPromptError.isInstance(error) ||\n\t\tInvalidArgumentError.isInstance(error) ||\n\t\tUnsupportedFunctionalityError.isInstance(error)\n\t) {\n\t\treturn { _tag: \"InvalidRequest\", message: errorMessage(error), retryable: false };\n\t}\n\tif (\n\t\tInvalidResponseDataError.isInstance(error) ||\n\t\tJSONParseError.isInstance(error) ||\n\t\tEmptyResponseBodyError.isInstance(error) ||\n\t\tNoContentGeneratedError.isInstance(error) ||\n\t\tTypeValidationError.isInstance(error)\n\t) {\n\t\treturn { _tag: \"InvalidResponse\", message: errorMessage(error), retryable: false };\n\t}\n\tif (resemblesTimeout(error)) return { _tag: \"Timeout\", message: errorMessage(error), retryable: true };\n\tif (resemblesTransportFailure(error)) {\n\t\treturn { _tag: \"Transport\", message: errorMessage(error), retryable: true };\n\t}\n\treturn { _tag: \"Unknown\", message: errorMessage(error), retryable: false };\n}\n\n/** Best-effort compatibility for terminal messages written before structured failures existed. */\nexport function fromMessage(message: string): Failure {\n\tconst normalized = normalizeMessage(message);\n\tif (/api key/i.test(normalized) && /missing|required|not set/i.test(normalized)) {\n\t\treturn { _tag: \"Authentication\", reason: \"missing\", message: normalized, retryable: false };\n\t}\n\tif (/api key|credential|token/i.test(normalized) && /invalid|expired|unauthorized/i.test(normalized)) {\n\t\treturn {\n\t\t\t_tag: \"Authentication\",\n\t\t\treason: /expired/i.test(normalized) ? \"expired\" : \"invalid\",\n\t\t\tmessage: normalized,\n\t\t\tretryable: false,\n\t\t};\n\t}\n\treturn { _tag: \"Unknown\", message: normalized, retryable: false };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,UAAU,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,KAAK,GAEpC,OAAO;EAAE,MAAM;EAAmB,SAAS,aAAa,KAAK;EAAG,WAAW;CAAM;CAElF,IAAI,iBAAiB,KAAK,GAAG,OAAO;EAAE,MAAM;EAAW,SAAS,aAAa,KAAK;EAAG,WAAW;CAAK;CACrG,IAAI,0BAA0B,KAAK,GAClC,OAAO;EAAE,MAAM;EAAa,SAAS,aAAa,KAAK;EAAG,WAAW;CAAK;CAE3E,OAAO;EAAE,MAAM;EAAW,SAAS,aAAa,KAAK;EAAG,WAAW;CAAM;AAC1E;;AAGA,SAAgB,YAAY,SAA0B;CACrD,MAAM,aAAa,iBAAiB,OAAO;CAC3C,IAAI,WAAW,KAAK,UAAU,KAAK,4BAA4B,KAAK,UAAU,GAC7E,OAAO;EAAE,MAAM;EAAkB,QAAQ;EAAW,SAAS;EAAY,WAAW;CAAM;CAE3F,IAAI,4BAA4B,KAAK,UAAU,KAAK,gCAAgC,KAAK,UAAU,GAClG,OAAO;EACN,MAAM;EACN,QAAQ,WAAW,KAAK,UAAU,IAAI,YAAY;EAClD,SAAS;EACT,WAAW;CACZ;CAED,OAAO;EAAE,MAAM;EAAW,SAAS;EAAY,WAAW;CAAM;AACjE"}
|
package/model-Czo0SKj0.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"model-Czo0SKj0.mjs","names":["KnownProviderEnum","KnownProviderEnumSchema","Type","ModelCatalogLoadError","Filesystem.readText","ModelCatalog.KnownProviderEnum","ModelCatalog.KnownProviderEnumSchema","ModelCatalog.ModelCatalogLoadError","Type","ModelCatalog.path","ModelCatalog.get"],"sources":["../../src/utils/lazy.ts","../../src/utils/error.ts","../../src/utils/filesystem.ts","../../src/model/catalog.ts","../../src/model/model.ts"],"sourcesContent":["export function lazy<T>(fn: () => T) {\n\tlet value: T | undefined;\n\tlet loaded = false;\n\n\tconst result = (): T => {\n\t\tif (loaded) return value as T;\n\t\tvalue = fn();\n\t\tloaded = true;\n\t\treturn value as T;\n\t};\n\n\tresult.reset = () => {\n\t\tloaded = false;\n\t\tvalue = undefined;\n\t};\n\n\treturn result;\n}\n","import type { Static, TSchema } from \"typebox\";\n\ntype SchemaLike = TSchema;\ntype StaticData<Data extends SchemaLike> = Static<Data>;\n\nexport abstract class NamedError extends Error {\n\tabstract schema(): SchemaLike;\n\tabstract toObject(): { name: string; data: unknown };\n\n\tstatic create<Name extends string, Data extends SchemaLike>(name: Name, data: Data) {\n\t\tconst schema = {\n\t\t\t$id: name,\n\t\t\ttype: \"object\",\n\t\t\trequired: [\"name\", \"data\"],\n\t\t\tproperties: {\n\t\t\t\tname: {\n\t\t\t\t\tconst: name,\n\t\t\t\t},\n\t\t\t\tdata,\n\t\t\t},\n\t\t} as const;\n\n\t\tconst result = class extends NamedError {\n\t\t\tpublic static readonly Schema = schema;\n\n\t\t\tpublic override readonly name = name as Name;\n\n\t\t\tpublic readonly data: StaticData<Data>;\n\n\t\t\tconstructor(data: StaticData<Data>, options?: ErrorOptions) {\n\t\t\t\tsuper(name, options);\n\t\t\t\tthis.data = data;\n\t\t\t\tthis.name = name;\n\t\t\t}\n\n\t\t\tstatic isInstance(input: unknown): input is InstanceType<typeof result> {\n\t\t\t\treturn typeof input === \"object\" && input !== null && \"name\" in input && input.name === name;\n\t\t\t}\n\n\t\t\tschema() {\n\t\t\t\treturn schema;\n\t\t\t}\n\n\t\t\ttoObject() {\n\t\t\t\treturn {\n\t\t\t\t\tname,\n\t\t\t\t\tdata: this.data,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tObject.defineProperty(result, \"name\", { value: name });\n\t\treturn result;\n\t}\n\n\tpublic static readonly Unknown = NamedError.create(\"UnknownError\", {\n\t\ttype: \"object\",\n\t\trequired: [\"message\"],\n\t\tproperties: {\n\t\t\tmessage: {\n\t\t\t\ttype: \"string\",\n\t\t\t},\n\t\t},\n\t});\n}\n","import { mkdir, readFile, rename, rm, writeFile } from \"fs/promises\";\nimport { dirname } from \"path\";\n\nexport async function readText(path: string): Promise<string> {\n\treturn readFile(path, \"utf-8\");\n}\n\nexport async function readJson<T = unknown>(path: string): Promise<T> {\n\treturn JSON.parse(await readFile(path, \"utf-8\"));\n}\n\nfunction isEnoent(error: unknown): error is { code: \"ENOENT\" } {\n\treturn (\n\t\ttypeof error === \"object\" && error !== null && \"code\" in error && (error as { code: string }).code === \"ENOENT\"\n\t);\n}\n\nexport async function write(path: string, content: string | Buffer | Uint8Array, mode?: number): Promise<void> {\n\ttry {\n\t\tif (mode) {\n\t\t\tawait writeFile(path, content, { mode });\n\t\t} else {\n\t\t\tawait writeFile(path, content);\n\t\t}\n\t} catch (error) {\n\t\tif (isEnoent(error)) {\n\t\t\tawait mkdir(dirname(path), { recursive: true });\n\t\t\tif (mode) {\n\t\t\t\tawait writeFile(path, content, { mode });\n\t\t\t} else {\n\t\t\t\tawait writeFile(path, content);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport async function writeJson(path: string, data: unknown, mode?: number): Promise<void> {\n\treturn write(path, JSON.stringify(data, null, 2), mode);\n}\n\n/**\n * Write through a temp file and rename it into place, so a concurrent reader\n * sees either the old content or the new, never a partial file.\n */\nexport async function writeJsonAtomic(path: string, data: unknown): Promise<void> {\n\tconst temp = `${path}.${process.pid}.${Date.now()}.tmp`;\n\ttry {\n\t\tawait writeJson(temp, data);\n\t\tawait rename(temp, path);\n\t} catch (error) {\n\t\tawait rm(temp, { force: true });\n\t\tthrow error;\n\t}\n}\n","import { join, resolve } from \"node:path\";\nimport Type, { type Static } from \"typebox\";\nimport { NamedError } from \"../utils/error.ts\";\nimport * as Filesystem from \"../utils/filesystem.ts\";\nimport { lazy } from \"../utils/lazy.ts\";\n\n// known AI SDK LLM providers\n// used as the public protocol discriminator for the AI SDK transport layer\nexport const KnownProviderEnum = {\n\tanthropic: \"anthropic\",\n\tgoogle: \"google\",\n\tgoogleVertex: \"google-vertex\",\n\tgoogleVertexAnthropic: \"google-vertex-anthropic\",\n\tgithubCopilot: \"github-copilot\",\n\topenai: \"openai\",\n\topenaiCompatible: \"openai-compatible\",\n\topenaiCodex: \"openai-codex\",\n\topenrouter: \"openrouter\",\n\txai: \"xai\",\n} as const;\nexport const KnownProviderEnumSchema = Type.Union([\n\tType.Literal(KnownProviderEnum.anthropic),\n\tType.Literal(KnownProviderEnum.google),\n\tType.Literal(KnownProviderEnum.googleVertex),\n\tType.Literal(KnownProviderEnum.googleVertexAnthropic),\n\tType.Literal(KnownProviderEnum.githubCopilot),\n\tType.Literal(KnownProviderEnum.openai),\n\tType.Literal(KnownProviderEnum.openaiCompatible),\n\tType.Literal(KnownProviderEnum.openaiCodex),\n\tType.Literal(KnownProviderEnum.openrouter),\n\tType.Literal(KnownProviderEnum.xai),\n]);\nexport type KnownProviderEnum = Static<typeof KnownProviderEnumSchema>;\n\nexport type GeneratedCatalog = Partial<Record<string, Record<string, unknown>>>;\ntype LazyGeneratedCatalog = ReturnType<typeof lazy<Promise<GeneratedCatalog>>>;\n\nexport const ModelCatalogLoadError = NamedError.create(\n\t\"ModelCatalogLoadError\",\n\tType.Object({\n\t\tpath: Type.String(),\n\t\treason: Type.Union([\n\t\t\tType.Literal(\"missing\"),\n\t\t\tType.Literal(\"unreadable\"),\n\t\t\tType.Literal(\"empty\"),\n\t\t\tType.Literal(\"invalid\"),\n\t\t]),\n\t\tmessage: Type.String(),\n\t}),\n);\nexport type ModelCatalogLoadError = InstanceType<typeof ModelCatalogLoadError>;\n\nexport function projectRoot(): string {\n\treturn process.cwd();\n}\n\nexport const filename = \"models.gen.json\";\n\nlet configured: string | undefined;\n\n/**\n * Read the catalog from `catalogPath` instead of `./models.gen.json`, for an\n * embedder that keeps it elsewhere. `CODEWORK_MODELS_FILE` still wins.\n */\nexport function configure(catalogPath: string): void {\n\tconfigured = resolve(catalogPath);\n\tdata.reset();\n}\n\nexport function path(): string {\n\treturn resolve(process.env.CODEWORK_MODELS_FILE ?? configured ?? join(projectRoot(), filename));\n}\n\nexport async function load(catalogPath = path()): Promise<GeneratedCatalog> {\n\tlet content: string;\n\ttry {\n\t\tcontent = await Filesystem.readText(catalogPath);\n\t} catch (cause) {\n\t\tconst value =\n\t\t\ttypeof cause === \"object\" && cause !== null && \"code\" in cause && typeof cause.code === \"string\"\n\t\t\t\t? cause.code\n\t\t\t\t: undefined;\n\t\tconst reason = value === \"ENOENT\" ? \"missing\" : \"unreadable\";\n\t\tthrow new ModelCatalogLoadError(\n\t\t\t{\n\t\t\t\tpath: catalogPath,\n\t\t\t\treason,\n\t\t\t\tmessage:\n\t\t\t\t\treason === \"missing\"\n\t\t\t\t\t\t? `model catalog not found at ${catalogPath}`\n\t\t\t\t\t\t: `model catalog could not be read at ${catalogPath}`,\n\t\t\t},\n\t\t\t{ cause },\n\t\t);\n\t}\n\tif (!content.trim()) {\n\t\tthrow new ModelCatalogLoadError({\n\t\t\tpath: catalogPath,\n\t\t\treason: \"empty\",\n\t\t\tmessage: `model catalog is empty at ${catalogPath}`,\n\t\t});\n\t}\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(content);\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) throw new Error(\"expected an object\");\n\t\treturn parsed as GeneratedCatalog;\n\t} catch (cause) {\n\t\tthrow new ModelCatalogLoadError(\n\t\t\t{\n\t\t\t\tpath: catalogPath,\n\t\t\t\treason: \"invalid\",\n\t\t\t\tmessage: `model catalog contains invalid json at ${catalogPath}`,\n\t\t\t},\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n\nexport const data: LazyGeneratedCatalog = lazy(() => load());\n\nexport async function get(): Promise<GeneratedCatalog> {\n\treturn data();\n}\n","import Type, { type Static } from \"typebox\";\nimport { lazy } from \"../utils/lazy.ts\";\nimport * as ModelCatalog from \"./catalog.ts\";\n\n// re-export\nexport const KnownProviderEnum = ModelCatalog.KnownProviderEnum;\nexport const KnownProviderEnumSchema = ModelCatalog.KnownProviderEnumSchema;\nexport type KnownProviderEnum = ModelCatalog.KnownProviderEnum;\n\nexport const ModelCatalogLoadError = ModelCatalog.ModelCatalogLoadError;\nexport type ModelCatalogLoadError = ModelCatalog.ModelCatalogLoadError;\n\n// Common reasoning-effort levels used by adapters that expose model reasoning,\n// thinking, or deliberation controls. Protocol-specific layers can map these\n// values to native fields like OpenAI `reasoning_effort`, Anthropic `thinking`,\n// or Gemini `thinkingConfig`.\nexport const ThinkingLevelEnum = {\n\t// Disable explicit reasoning controls when the provider supports turning them off.\n\toff: \"off\",\n\t// Smallest reasoning budget/effort above off; useful for fastest low-cost responses.\n\tminimal: \"minimal\",\n\t// Light reasoning for simple tasks that still benefit from some deliberation.\n\tlow: \"low\",\n\t// Balanced default for general tasks.\n\tmedium: \"medium\",\n\t// Higher reasoning effort for complex coding, analysis, or planning.\n\thigh: \"high\",\n\t// Extra-high reasoning effort for difficult tasks when supported by the model.\n\txhigh: \"xhigh\",\n\t// Maximum provider-defined effort above xhigh when explicitly supported by the model.\n\tmax: \"max\",\n} as const;\n\nexport const ThinkingLevel = Type.Union([\n\tType.Literal(ThinkingLevelEnum.off),\n\tType.Literal(ThinkingLevelEnum.minimal),\n\tType.Literal(ThinkingLevelEnum.low),\n\tType.Literal(ThinkingLevelEnum.medium),\n\tType.Literal(ThinkingLevelEnum.high),\n\tType.Literal(ThinkingLevelEnum.xhigh),\n\tType.Literal(ThinkingLevelEnum.max),\n]);\nexport type ThinkingLevel = Static<typeof ThinkingLevel>;\n\nexport const ActiveThinkingLevel = Type.Union([\n\tType.Literal(ThinkingLevelEnum.minimal),\n\tType.Literal(ThinkingLevelEnum.low),\n\tType.Literal(ThinkingLevelEnum.medium),\n\tType.Literal(ThinkingLevelEnum.high),\n\tType.Literal(ThinkingLevelEnum.xhigh),\n\tType.Literal(ThinkingLevelEnum.max),\n]);\nexport type ActiveThinkingLevel = Static<typeof ActiveThinkingLevel>;\n\nexport const ThinkingBudgets = Type.Partial(Type.Record(ActiveThinkingLevel, Type.Number()));\nexport type ThinkingBudgets = Static<typeof ThinkingBudgets>;\n\n// Note: order of entries matters!\nconst ACTIVE_THINKING_LEVELS = [\n\tThinkingLevelEnum.minimal,\n\tThinkingLevelEnum.low,\n\tThinkingLevelEnum.medium,\n\tThinkingLevelEnum.high,\n\tThinkingLevelEnum.xhigh,\n\tThinkingLevelEnum.max,\n] as const satisfies readonly ActiveThinkingLevel[];\nconst MODEL_THINKING_LEVELS = [\n\tThinkingLevelEnum.off,\n\t...ACTIVE_THINKING_LEVELS,\n] as const satisfies readonly ThinkingLevel[];\n\nexport const ProviderInfo = Type.Object({\n\tid: Type.String(),\n\tname: Type.String(),\n\tsource: Type.Enum([\"env\", \"config\", \"custom\", \"api\", \"unknown\"]),\n\tenv: Type.Array(Type.String()),\n\tkey: Type.Optional(Type.String()), // runtime api/oauth key\n\toptions: Type.Optional(Type.Record(Type.String(), Type.Any())),\n});\nexport type ProviderInfo = Static<typeof ProviderInfo>;\n\nconst InputSchema = Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]));\nconst CostRatesSchema = Type.Object({\n\tinput: Type.Number(),\n\toutput: Type.Number(),\n\tcacheRead: Type.Number(),\n\tcacheWrite: Type.Number(),\n});\nconst CostTierSchema = Type.Object({\n\t...CostRatesSchema.properties,\n\tinputTokensAbove: Type.Number(),\n});\nconst CostSchema = Type.Object({\n\t...CostRatesSchema.properties,\n\ttiers: Type.Optional(Type.Array(CostTierSchema)),\n\tserviceTierMultipliers: Type.Optional(Type.Record(Type.String(), Type.Number())),\n});\nconst SupportedProtocolsSchema = Type.Partial(\n\tType.Object({\n\t\tanthropic: KnownProviderEnumSchema,\n\t\tgoogle: KnownProviderEnumSchema,\n\t\tgoogleVertex: KnownProviderEnumSchema,\n\t\tgoogleVertexAnthropic: KnownProviderEnumSchema,\n\t\tgithubCopilot: KnownProviderEnumSchema,\n\t\topenai: KnownProviderEnumSchema,\n\t\topenaiCompatible: KnownProviderEnumSchema,\n\t\topenaiCodex: KnownProviderEnumSchema,\n\t\topenrouter: KnownProviderEnumSchema,\n\t\txai: KnownProviderEnumSchema,\n\t}),\n);\n\nexport const APIMethodEnum = {\n\tlanguageModel: \"languageModel\",\n\tchat: \"chat\",\n\tcompletion: \"completion\",\n\tcompletionModel: \"completionModel\",\n\tmessages: \"messages\",\n\tresponses: \"responses\",\n} as const;\nexport const APIMethodEnumSchema = Type.Union([\n\tType.Literal(APIMethodEnum.languageModel),\n\tType.Literal(APIMethodEnum.chat),\n\tType.Literal(APIMethodEnum.completion),\n\tType.Literal(APIMethodEnum.completionModel),\n\tType.Literal(APIMethodEnum.messages),\n\tType.Literal(APIMethodEnum.responses),\n]);\nexport type APIMethodEnum = Static<typeof APIMethodEnumSchema>;\n\nexport const APIMetadataSchema = Type.Object({\n\tid: Type.Optional(Type.String()),\n\turl: Type.Optional(Type.String()),\n\tmethod: Type.Optional(APIMethodEnumSchema),\n});\nexport type APIMetadata = Static<typeof APIMetadataSchema>;\n\nexport const ThinkingLevelMapSchema = Type.Partial(\n\tType.Record(\n\t\tThinkingLevel, // Safe key validation\n\t\tType.Union([Type.String(), Type.Null()]), // Allowed values\n\t),\n);\nexport type ThinkingLevelMap = Static<typeof ThinkingLevelMapSchema>;\n\nexport const CompatibilitySchema = Type.Object({\n\t/** The Google protocol accepts thinking levels rather than a token budget. */\n\tsupportsThinkingLevel: Type.Optional(Type.Boolean()),\n\tsupportsToolSearch: Type.Optional(Type.Boolean()),\n\tsupportsAdditionalTools: Type.Optional(Type.Boolean()),\n\tsupportsStrictMode: Type.Optional(Type.Boolean()),\n\tsupportsOpenAIGrammarTools: Type.Optional(Type.Boolean()),\n\t/** The model takes a thinking-token budget as a top-level request field. */\n\tsupportsThinkingTokenBudget: Type.Optional(Type.Boolean()),\n\t/** Claude model that sizes its own thinking, driven by `effort` instead of a token budget. */\n\tforceAdaptiveThinking: Type.Optional(Type.Boolean()),\n\t/** Name of that field, when it is not the conventional `thinking_token_budget`. */\n\tthinkingTokenBudgetField: Type.Optional(Type.String()),\n});\nexport type Compatibility = Static<typeof CompatibilitySchema>;\n\n/**\n * Claude models that decide their own thinking depth.\n *\n * These take an `effort` level and let the model size each turn's reasoning; the\n * older models take a fixed `budget_tokens` instead. Sending a budget to an\n * adaptive model pins it to one depth for every turn, which is the thing adaptive\n * thinking exists to avoid.\n */\nexport function isAnthropicAdaptiveThinkingModel(modelId: string): boolean {\n\treturn [\n\t\t\"opus-4-6\",\n\t\t\"opus-4.6\",\n\t\t\"opus-4-7\",\n\t\t\"opus-4.7\",\n\t\t\"opus-4-8\",\n\t\t\"opus-4.8\",\n\t\t\"opus-5\",\n\t\t\"opus.5\",\n\t\t\"sonnet-4-6\",\n\t\t\"sonnet-4.6\",\n\t\t\"sonnet-5\",\n\t\t\"sonnet.5\",\n\t\t\"fable-5\",\n\t].some((needle) => modelId.includes(needle));\n}\n\nexport const Schema = Type.Object({\n\tid: Type.String(),\n\tname: Type.String(),\n\tprovider: ProviderInfo,\n\tbaseUrl: Type.String(),\n\treasoning: Type.Boolean(),\n\tthinkingLevelMap: Type.Optional(ThinkingLevelMapSchema),\n\t/** Default budgets; request-level thinkingBudgets take precedence. */\n\tthinkingBudgets: Type.Optional(ThinkingBudgets),\n\tinput: InputSchema,\n\tcost: CostSchema,\n\tcontextWindow: Type.Number(),\n\tmaxTokens: Type.Number(),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tnpm: Type.Optional(Type.String()),\n\tapi: Type.Optional(APIMetadataSchema),\n\tproviderOptionsKey: Type.Optional(Type.String()),\n\toptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\tproviderOptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\tcompat: Type.Optional(CompatibilitySchema),\n\tprotocol: KnownProviderEnumSchema, // provider as the underlying protocol\n\tsupportedProtocols: Type.Optional(SupportedProtocolsSchema), // provider as the underlying supported protocols\n});\n\nexport const ExtrasSchema = Type.Object({});\n\nexport const Info = Type.Evaluate(Type.Intersect([Schema, ExtrasSchema]));\nexport type Info = Static<typeof Info>;\nexport type TModel<TProtocol extends KnownProviderEnum> = Omit<Info, \"protocol\"> & { protocol: TProtocol };\n\nexport function calculateCost(\n\tmodel: Info,\n\tusage: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcacheWrite1h?: number;\n\t\tcost: {\n\t\t\tinput: number;\n\t\t\toutput: number;\n\t\t\tcacheRead: number;\n\t\t\tcacheWrite: number;\n\t\t\ttotal: number;\n\t\t};\n\t},\n): void {\n\tconst inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\tlet rates = model.cost;\n\tlet matchedThreshold = -1;\n\tfor (const tier of model.cost.tiers ?? []) {\n\t\tif (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {\n\t\t\trates = tier;\n\t\t\tmatchedThreshold = tier.inputTokensAbove;\n\t\t}\n\t}\n\n\t// Anthropic charges 2x base input for 1h cache writes; `cost.cacheWrite` is the 5m rate.\n\tconst longWrite = usage.cacheWrite1h ?? 0;\n\tconst shortWrite = usage.cacheWrite - longWrite;\n\n\tusage.cost.input = (usage.input / 1_000_000) * rates.input;\n\tusage.cost.output = (usage.output / 1_000_000) * rates.output;\n\tusage.cost.cacheRead = (usage.cacheRead / 1_000_000) * rates.cacheRead;\n\tusage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1_000_000;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n\nexport type BuiltInModels = Partial<Record<string, Record<string, Info>>>;\n\nexport function normalizeInput(input?: string[]): Array<\"text\" | \"image\"> {\n\tconst normalized = new Set<\"text\" | \"image\">();\n\tfor (const modality of input ?? [\"text\"]) {\n\t\tif (modality === \"text\" || modality === \"image\") {\n\t\t\tnormalized.add(modality);\n\t\t}\n\t}\n\tif (normalized.size === 0) normalized.add(\"text\");\n\treturn [...normalized];\n}\n\n/** Where the catalog is read from: `CODEWORK_MODELS_FILE`, the configured path, or `./models.gen.json`. */\nexport const catalogPath = ModelCatalog.path;\n\n/** Read the catalog from `path` from now on, dropping whatever was already loaded. */\nexport function configureCatalog(path: string): void {\n\tModelCatalog.configure(path);\n\tregistry.reset();\n}\n\n/** Drop the loaded catalog, so the next lookup re-reads the file -- after it was regenerated. */\nexport function reloadCatalog(): void {\n\tModelCatalog.data.reset();\n\tregistry.reset();\n}\n\nexport async function getBuiltInModels(): Promise<BuiltInModels> {\n\treturn (await ModelCatalog.get()) as BuiltInModels;\n}\n\nexport const registry = lazy(async () => {\n\tconst registry: Map<string, Map<string, Info>> = new Map();\n\tconst models = await getBuiltInModels();\n\tfor (const [provider, value] of Object.entries(models) as Array<[string, Record<string, Info>]>) {\n\t\tconst providerModels = new Map<string, Info>();\n\t\tfor (const [id, model] of Object.entries(value)) {\n\t\t\tproviderModels.set(id, model);\n\t\t}\n\t\tregistry.set(provider, providerModels);\n\t}\n\treturn registry;\n});\n\n/**\n * The key a provider's own option bag is filed under.\n *\n * Providers that speak another provider's protocol still carry their own option\n * namespace, so this is not always the protocol.\n */\n/**\n * The request-body field a model takes its thinking-token budget in, if any.\n *\n * OpenAI-compatible endpoints have no standard place for this, so each one names\n * its own field; a bare `supportsThinkingTokenBudget` means the conventional name.\n */\nexport function thinkingTokenBudgetField(model: Info): string | undefined {\n\tif (model.compat?.thinkingTokenBudgetField) return model.compat.thinkingTokenBudgetField;\n\treturn model.compat?.supportsThinkingTokenBudget ? \"thinking_token_budget\" : undefined;\n}\n\nexport function optionsKey(model: Info): string {\n\treturn model.providerOptionsKey ?? model.protocol;\n}\n\nexport function supportsProtocol(model: Info, protocol: KnownProviderEnum): boolean {\n\tif (model.protocol === protocol) return true;\n\treturn Object.values(model.supportedProtocols ?? {}).includes(protocol);\n}\n\nexport type ProviderToProtocol<TProvider extends string> = TProvider extends KnownProviderEnum\n\t? TProvider\n\t: KnownProviderEnum;\n\nexport async function getModel<\n\tTProvider extends string,\n\tTProtocol extends KnownProviderEnum = ProviderToProtocol<TProvider>,\n>(\n\tprovider: TProvider,\n\tmodel: string,\n\toverrides?: Partial<Info> & { protocol?: TProtocol },\n): Promise<TModel<TProtocol> | undefined> {\n\tconst data = await registry();\n\tconst providerModels = data.get(provider);\n\tconst result = providerModels?.get(model);\n\tif (result && overrides) {\n\t\tif (overrides.protocol && !supportsProtocol(result, overrides.protocol)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\t...result,\n\t\t\t...overrides,\n\t\t} as TModel<TProtocol>;\n\t}\n\treturn result as TModel<TProtocol> | undefined;\n}\n\nexport async function getProviders(): Promise<string[]> {\n\tconst data = await registry();\n\treturn Array.from(data.keys());\n}\n\nexport async function getModels<TProvider extends string>(provider: TProvider): Promise<Info[]> {\n\tconst data = await registry();\n\tconst models = data.get(provider);\n\treturn models ? Array.from(models.values()) : [];\n}\n\n/**\n * Check if two models are equal by comparing both their id and provider id.\n * Returns false if either model is null or undefined.\n */\nexport function modelsAreEqual(a: Info | null | undefined, b: Info | null | undefined): boolean {\n\tif (!a || !b) return false;\n\treturn a.id === b.id && a.provider.id === b.provider.id;\n}\n\nexport function getSupportedThinkingLevels<TProtocol extends KnownProviderEnum>(\n\tmodel: TModel<TProtocol>,\n): ThinkingLevel[] {\n\tif (!model.reasoning) return [\"off\"];\n\n\treturn MODEL_THINKING_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\nexport function clampThinkingLevel<TProtocol extends KnownProviderEnum>(\n\tmodel: TModel<TProtocol>,\n\tlevel: ThinkingLevel,\n): ThinkingLevel {\n\tconst availableLevels = getSupportedThinkingLevels(model);\n\tif (availableLevels.includes(level)) return level;\n\n\tconst requestedIndex = MODEL_THINKING_LEVELS.indexOf(level);\n\tif (requestedIndex === -1) return availableLevels[0] ?? \"off\";\n\n\t// walk up the ladder from the point and pick first supported\n\t// biased to avail more thinking, then less not round to nearest.\n\tfor (let i = requestedIndex; i < MODEL_THINKING_LEVELS.length; i++) {\n\t\tconst candidate = MODEL_THINKING_LEVELS[i]!;\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\t// otherwise walk down from the point\n\tfor (let i = requestedIndex - 1; i >= 0; i--) {\n\t\tconst candidate = MODEL_THINKING_LEVELS[i]!;\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\treturn availableLevels[0] ?? \"off\";\n}\n"],"mappings":";;;;;;AAAA,SAAgB,KAAQ,IAAa;CACpC,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,eAAkB;EACvB,IAAI,QAAQ,OAAO;EACnB,QAAQ,GAAG;EACX,SAAS;EACT,OAAO;CACR;CAEA,OAAO,cAAc;EACpB,SAAS;EACT,QAAQ,KAAA;CACT;CAEA,OAAO;AACR;;;ACZA,IAAsB,aAAtB,MAAsB,mBAAmB,MAAM;CAI9C,OAAO,OAAqD,MAAY,MAAY;EACnF,MAAM,SAAS;GACd,KAAK;GACL,MAAM;GACN,UAAU,CAAC,QAAQ,MAAM;GACzB,YAAY;IACX,MAAM,EACL,OAAO,KACR;IACA;GACD;EACD;EAEA,MAAM,SAAS,cAAc,WAAW;GACvC,OAAuB,SAAS;GAEhC,OAAgC;GAEhC;GAEA,YAAY,MAAwB,SAAwB;IAC3D,MAAM,MAAM,OAAO;IACnB,KAAK,OAAO;IACZ,KAAK,OAAO;GACb;GAEA,OAAO,WAAW,OAAsD;IACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,MAAM,SAAS;GACzF;GAEA,SAAS;IACR,OAAO;GACR;GAEA,WAAW;IACV,OAAO;KACN;KACA,MAAM,KAAK;IACZ;GACD;EACD;EAEA,OAAO,eAAe,QAAQ,QAAQ,EAAE,OAAO,KAAK,CAAC;EACrD,OAAO;CACR;CAEA,OAAuB,UAAU,WAAW,OAAO,gBAAgB;EAClE,MAAM;EACN,UAAU,CAAC,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U,OAAO,OAAO,WAAW,KAAA;EAC5D,OAAO;CACR,CAAC;AACF;AAEA,SAAgB,mBACf,OACA,OACgB;CAChB,MAAM,kBAAkB,2BAA2B,KAAK;CACxD,IAAI,gBAAgB,SAAS,KAAK,GAAG,OAAO;CAE5C,MAAM,iBAAiB,sBAAsB,QAAQ,KAAK;CAC1D,IAAI,mBAAmB,IAAI,OAAO,gBAAgB,MAAM;CAIxD,KAAK,IAAI,IAAI,gBAAgB,IAAI,sBAAsB,QAAQ,KAAK;EACnE,MAAM,YAAY,sBAAsB;EACxC,IAAI,gBAAgB,SAAS,SAAS,GAAG,OAAO;CACjD;CAEA,KAAK,IAAI,IAAI,iBAAiB,GAAG,KAAK,GAAG,KAAK;EAC7C,MAAM,YAAY,sBAAsB;EACxC,IAAI,gBAAgB,SAAS,SAAS,GAAG,OAAO;CACjD;CACA,OAAO,gBAAgB,MAAM;AAC9B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"modelgen-BHm-jA64.mjs","names":["Filesystem.readJson","Model.isAnthropicAdaptiveThinkingModel","path","ModelCatalog.path","Filesystem.writeJsonAtomic","Model.normalizeInput"],"sources":["../../src/cli/modelgen.ts"],"sourcesContent":["import { resolve } from \"node:path\";\nimport { mapValues, pickBy, pipe } from \"remeda\";\nimport type { CommandModule } from \"yargs\";\nimport { DEFAULT_AI_SDK_FALLBACK, isAISDKPackage, protocolForPackage } from \"../llm/registry.ts\";\nimport * as ModelCatalog from \"../model/catalog.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { GITHUB_COPILOT_STATIC_HEADERS } from \"../providers/github-copilot/copilot-headers.ts\";\nimport * as Filesystem from \"../utils/filesystem.ts\";\n\nconst DEFAULT_PROVIDER_BASE_URLS: Partial<Record<Model.KnownProviderEnum, string>> = {\n\t[Model.KnownProviderEnum.anthropic]: \"https://api.anthropic.com/v1\",\n\t[Model.KnownProviderEnum.openai]: \"https://api.openai.com/v1\",\n\t[Model.KnownProviderEnum.openrouter]: \"https://openrouter.ai/api/v1\",\n\t[Model.KnownProviderEnum.xai]: \"https://api.x.ai/v1\",\n};\n\ninterface ModelsDevModel {\n\tid: string;\n\tname: string;\n\tfamily: string;\n\tattachment: boolean;\n\treasoning?: boolean;\n\ttool_call?: boolean;\n\ttemperature?: boolean;\n\tknowledge?: string | boolean;\n\trelease_date: string;\n\tlast_updated: string;\n\tmodalities: {\n\t\tinput?: string[];\n\t\toutput: string[];\n\t};\n\topen_weights: boolean;\n\tbaseUrl?: string;\n\theaders?: Record<string, string>;\n\tcost?: {\n\t\tinput?: number;\n\t\toutput?: number;\n\t\tcache_read?: number;\n\t\tcache_write?: number;\n\t\ttiers?: Array<{\n\t\t\tinput?: number;\n\t\t\toutput?: number;\n\t\t\tcache_read?: number;\n\t\t\tcache_write?: number;\n\t\t\ttier?: { type?: string; size?: number };\n\t\t}>;\n\t};\n\treasoning_options?: Array<{\n\t\ttype?: string;\n\t\tvalues?: string[];\n\t\tmin?: number;\n\t\tmax?: number;\n\t}>;\n\tstatus?: string;\n\tlimit?: {\n\t\tcontext?: number;\n\t\toutput?: number;\n\t};\n\tstructured_output?: boolean;\n\tprovider?: {\n\t\tnpm?: string;\n\t\tapi?: string;\n\t\theaders?: Record<string, string>;\n\t};\n}\n\ninterface ModelsDevProvider {\n\tid: string;\n\tenv: string[];\n\tnpm?: string;\n\tapi?: string;\n\tname: string;\n\tdoc?: string; // reference documentation link\n\tkey?: string; // runtime placeholder for api/oauth key\n\theaders?: Record<string, string>; // custom overrides at provider level\n\tmodels: Record<string, ModelsDevModel>;\n}\n\nexport type BuiltInModels = Model.BuiltInModels;\n\n// Doesn't represent the full spec from models.dev.\n// Represents the provider entries on a best-effort basis.\ntype ModelsDevCatalog = Record<string, ModelsDevProvider>;\n\nfunction modelsDevURL(): string {\n\treturn process.env.OPENCODE_MODELS_URL || \"https://models.dev\";\n}\n\nfunction modelsDevPath(): string | undefined {\n\treturn process.env.OPENCODE_MODELS_DEV_FILE;\n}\n\nasync function pullModelsDevData(): Promise<ModelsDevCatalog> {\n\tconst path = modelsDevPath();\n\tif (path) {\n\t\tconst result = await Filesystem.readJson<ModelsDevCatalog>(path).catch(() => undefined);\n\t\tif (result) return result;\n\t}\n\n\tconst response = await fetch(`${modelsDevURL()}/api.json`);\n\tif (!response.ok) throw new Error(`models.dev responded ${response.status} ${response.statusText}`);\n\treturn (await response.json()) as ModelsDevCatalog;\n}\n\nfunction toModelValue(providerId: string, provider: ModelsDevProvider, model: ModelsDevModel): Model.Info | undefined {\n\treturn applyModification(providerId, provider, model);\n}\n\nfunction loadBuiltInFromModelsDev(catalog: ModelsDevCatalog) {\n\treturn pipe(\n\t\tcatalog,\n\t\tpickBy((provider) =>\n\t\t\tObject.values(provider.models).some(\n\t\t\t\t// If `resolveModelNpm` fallbacks to `@ai-sdk/openai-compatible`\n\t\t\t\t// isAISDKPakage will be truthy, modify resolveModelNpm for custom logic if needed.\n\t\t\t\t// Keep `isAISDKPackage` as readonly for supported implemenatations key check\n\t\t\t\t(model) => Boolean(model.tool_call) && isAISDKPackage(resolveModelNpm(provider, model)),\n\t\t\t),\n\t\t),\n\t\tmapValues((provider, providerId) =>\n\t\t\tpipe(\n\t\t\t\tprovider.models,\n\t\t\t\tpickBy((model) => Boolean(model.tool_call) && isAISDKPackage(resolveModelNpm(provider, model))),\n\t\t\t\tmapValues((model) => toModelValue(providerId, provider, model)),\n\t\t\t\tpickBy((model): model is Model.Info => model !== undefined),\n\t\t\t),\n\t\t),\n\t) as BuiltInModels;\n}\n\ntype ThinkingLevelMap = NonNullable<Model.Info[\"thinkingLevelMap\"]>;\n\nfunction resolveModelNpm(provider: ModelsDevProvider, model: ModelsDevModel): string {\n\treturn model.provider?.npm ?? provider.npm ?? DEFAULT_AI_SDK_FALLBACK;\n}\n\nfunction resolveModelBaseUrl(provider: ModelsDevProvider, model: ModelsDevModel): string {\n\tconst npm = resolveModelNpm(provider, model);\n\tconst protocol = protocolForPackage(npm);\n\treturn model.baseUrl ?? model.provider?.api ?? provider.api ?? DEFAULT_PROVIDER_BASE_URLS[protocol] ?? \"\";\n}\n\nfunction resolveModelAPIMethod(npm: string): Model.APIMethodEnum {\n\tconst protocol = protocolForPackage(npm);\n\t// `By default, xai(modelId) uses the Chat API.\n\t// To use the Responses API with server-side agentic tools, explicitly use xai.responses(modelId).`\n\t// References: https://ai-sdk.dev/providers/ai-sdk-providers/xai\n\tif (protocol === Model.KnownProviderEnum.openai || protocol === Model.KnownProviderEnum.xai) {\n\t\treturn Model.APIMethodEnum.responses;\n\t}\n\treturn Model.APIMethodEnum.languageModel;\n}\n\nfunction resolveProviderOptionsKey(protocol: Model.KnownProviderEnum): string {\n\tif (protocol === Model.KnownProviderEnum.openaiCompatible) return \"openai-compatible\";\n\tif (protocol === Model.KnownProviderEnum.googleVertex) return \"google-vertex\";\n\tif (protocol === Model.KnownProviderEnum.googleVertexAnthropic) return \"google-vertex-anthropic\";\n\treturn protocol;\n}\n\n//\n// adhoc helpers variations\nconst OPENAI_RESPONSES_NONE_REASONING_MODELS = new Set([\n\t\"gpt-5.1\",\n\t\"gpt-5.2\",\n\t\"gpt-5.3-codex\",\n\t\"gpt-5.4\",\n\t\"gpt-5.4-mini\",\n\t\"gpt-5.4-nano\",\n\t\"gpt-5.5\",\n\t\"gpt-5.6-luna\",\n\t\"gpt-5.6-sol\",\n\t\"gpt-5.6-terra\",\n\t\"gpt-6-luna\",\n\t\"gpt-6-sol\",\n]);\n\n// Checked live against the Responses and Codex APIs: these families reject\n// reasoning.effort \"minimal\".\nconst OPENAI_NO_MINIMAL_REASONING = /gpt-5\\.[456]|gpt-6/;\n\nfunction isOpenAiResponses(model: Model.Info): boolean {\n\treturn model.protocol === Model.KnownProviderEnum.openai || model.protocol === Model.KnownProviderEnum.openaiCodex;\n}\n\nfunction supportsOpenAiXhigh(model: Model.Info): boolean {\n\treturn /gpt-5\\.[2-5]/.test(model.id) || supportsOpenAiMax(model);\n}\n\nfunction supportsOpenAiMax(model: Model.Info): boolean {\n\treturn isOpenAiResponses(model) && /gpt-5\\.6|gpt-6/.test(model.id);\n}\n\nfunction mergeThinkingLevelMap(model: Model.Info, map: ThinkingLevelMap): void {\n\tmodel.thinkingLevelMap = { ...model.thinkingLevelMap, ...map };\n}\n\nfunction mergeCompat(model: Model.Info, compat: Model.Compatibility): void {\n\tmodel.compat = { ...model.compat, ...compat };\n}\n\nfunction applyGoogleThinkingMetadata(model: Model.Info): void {\n\tconst id = model.id.toLowerCase();\n\tconst supportsThinkingLevel =\n\t\t/gemini-3(?:\\.\\d+)?-(?:pro|flash)|gemma-?4/.test(id) ||\n\t\tid === \"gemini-flash-latest\" ||\n\t\tid === \"gemini-flash-lite-latest\";\n\tmergeCompat(model, { supportsThinkingLevel });\n\tif (supportsThinkingLevel) return;\n\n\t// Unknown budget-based families ask the provider to size thinking dynamically.\n\tconst defaults: Array<[string, Model.ThinkingBudgets]> = [\n\t\t[\"2.5-pro\", { minimal: 128, low: 2048, medium: 8192, high: 32768 }],\n\t\t[\"2.5-flash-lite\", { minimal: 512, low: 2048, medium: 8192, high: 24576 }],\n\t\t[\"2.5-flash\", { minimal: 128, low: 2048, medium: 8192, high: 24576 }],\n\t];\n\tmodel.thinkingBudgets = defaults.find(([family]) => id.includes(family))?.[1] ?? {\n\t\tminimal: -1,\n\t\tlow: -1,\n\t\tmedium: -1,\n\t\thigh: -1,\n\t};\n}\n\nfunction applyModelMetadata(model: Model.Info): void {\n\tif (model.protocol === Model.KnownProviderEnum.google || model.protocol === Model.KnownProviderEnum.googleVertex) {\n\t\tapplyGoogleThinkingMetadata(model);\n\t}\n\tif (model.protocol === Model.KnownProviderEnum.openai || model.protocol === Model.KnownProviderEnum.openaiCodex) {\n\t\tmodel.cost.serviceTierMultipliers = { flex: 0.5, priority: model.id === \"gpt-5.5\" ? 2.5 : 2 };\n\t}\n\tif (\n\t\t(model.protocol === Model.KnownProviderEnum.google || model.protocol === Model.KnownProviderEnum.googleVertex) &&\n\t\t/gemini-3(?:\\.\\d+)?-pro|gemini-3\\.[78]-flash/.test(model.id.toLowerCase())\n\t) {\n\t\t// These models cannot disable thinking or accept minimal. Expose supported\n\t\t// levels to callers and let the shared clamp promote minimal to low.\n\t\tmergeThinkingLevelMap(model, { off: \"low\", minimal: null });\n\t}\n\tif (\n\t\t(model.protocol === Model.KnownProviderEnum.anthropic ||\n\t\t\tmodel.protocol === Model.KnownProviderEnum.googleVertexAnthropic) &&\n\t\tModel.isAnthropicAdaptiveThinkingModel(model.id)\n\t) {\n\t\tmergeCompat(model, { forceAdaptiveThinking: true });\n\t}\n\tif (model.protocol === Model.KnownProviderEnum.openai && model.id.startsWith(\"gpt-5\")) {\n\t\tmergeThinkingLevelMap(model, { off: null });\n\t}\n\tif (\n\t\tmodel.protocol === Model.KnownProviderEnum.openai &&\n\t\tmodel.provider.id === \"openai\" &&\n\t\tOPENAI_RESPONSES_NONE_REASONING_MODELS.has(model.id)\n\t) {\n\t\tmergeThinkingLevelMap(model, { off: \"none\" });\n\t}\n\tif (supportsOpenAiXhigh(model)) {\n\t\tmergeThinkingLevelMap(model, { xhigh: \"xhigh\" });\n\t}\n\tif (isOpenAiResponses(model) && OPENAI_NO_MINIMAL_REASONING.test(model.id)) {\n\t\tmergeThinkingLevelMap(model, { minimal: null });\n\t}\n\tif (supportsOpenAiMax(model)) {\n\t\tmergeThinkingLevelMap(model, { max: \"max\" });\n\t}\n\tif (model.id.includes(\"opus-4-6\") || model.id.includes(\"opus-4.6\")) {\n\t\tmergeThinkingLevelMap(model, { xhigh: \"max\" });\n\t}\n\tif (model.id.includes(\"opus-4-7\") || model.id.includes(\"opus-4.7\")) {\n\t\tmergeThinkingLevelMap(model, { xhigh: \"xhigh\" });\n\t}\n\tif (isAnthropicMessages(model)) applyAnthropicMetadata(model);\n}\n\nfunction isAnthropicMessages(model: Model.Info): boolean {\n\treturn (\n\t\tmodel.protocol === Model.KnownProviderEnum.anthropic ||\n\t\tmodel.protocol === Model.KnownProviderEnum.googleVertexAnthropic\n\t);\n}\n\n// Checked live against the Messages API: effort levels each adaptive family\n// accepts, the 5.5 and Fable models that reject `thinking: {type: \"disabled\"}`, and\n// Sonnet 4.5's window, which is 1M only behind a beta header.\nfunction applyAnthropicMetadata(model: Model.Info): void {\n\tconst id = model.id;\n\tif (/sonnet-4[-.]5/.test(id)) model.contextWindow = 200_000;\n\tif (/(opus|sonnet)-4[-.]6/.test(id)) {\n\t\tmergeThinkingLevelMap(model, { max: \"max\" });\n\t}\n\tif (/opus-4[-.][78]|(opus|sonnet|fable)-5/.test(id)) {\n\t\tmergeThinkingLevelMap(model, { xhigh: \"xhigh\", max: \"max\" });\n\t}\n\tif (/(opus|sonnet)-5[-.]5/.test(id)) {\n\t\tmergeThinkingLevelMap(model, { off: null, minimal: null });\n\t}\n\tif (/fable-5/.test(id)) {\n\t\tmergeThinkingLevelMap(model, { off: null });\n\t}\n}\n\n//\n// OpenAI Codex (ChatGPT OAuth) models.\n// NOTE: These are not fetched from models.dev; we keep a small, explicit list to avoid aliases.\n// Context window is based on observed server limits (400s above ~272k), not marketing numbers.\nconst OPENAI_CODEX_PROVIDER_ID = \"openai-codex\";\nconst OPENAI_CODEX_NPM = \"@codeworksh/ai-sdk-openai-codex\";\nconst OPENAI_CODEX_BASE_URL = \"https://chatgpt.com/backend-api\";\nconst OPENAI_CODEX_CONTEXT = 272_000;\nconst OPENAI_CODEX_GPT_56_CONTEXT = 272_000;\nconst OPENAI_CODEX_SPARK_CONTEXT = 128_000;\nconst OPENAI_CODEX_MAX_TOKENS = 128_000;\nconst OPENAI_LONG_CONTEXT_INPUT_THRESHOLD = 272_000;\nconst OPENAI_CODEX_TOOL_SEARCH_MODEL_IDS = new Set([\n\t\"gpt-5.4\",\n\t\"gpt-5.4-mini\",\n\t\"gpt-5.5\",\n\t\"gpt-5.6-luna\",\n\t\"gpt-5.6-sol\",\n\t\"gpt-5.6-terra\",\n\t\"gpt-6-luna\",\n]);\nconst OPENAI_CODEX_ADDITIONAL_TOOLS_MODEL_IDS = new Set([\"gpt-5.6-luna\", \"gpt-5.6-sol\", \"gpt-5.6-terra\", \"gpt-6-luna\"]);\n// Checked live: the Codex backend accepts reasoning.effort \"none\" for these.\nconst OPENAI_CODEX_NONE_REASONING_MODEL_IDS = new Set([\"gpt-5.5\", \"gpt-5.6-luna\", \"gpt-6-luna\"]);\n\ntype OpenAICodexModelSeed = Pick<Model.Info, \"id\" | \"name\" | \"input\" | \"cost\" | \"contextWindow\" | \"thinkingLevelMap\">;\n\nfunction roundCost(value: number): number {\n\treturn Number(value.toFixed(6));\n}\n\nfunction withOpenAiLongContextPricing(cost: Model.Info[\"cost\"]): Model.Info[\"cost\"] {\n\treturn {\n\t\t...cost,\n\t\ttiers: [\n\t\t\t{\n\t\t\t\tinputTokensAbove: OPENAI_LONG_CONTEXT_INPUT_THRESHOLD,\n\t\t\t\tinput: roundCost(cost.input * 2),\n\t\t\t\toutput: roundCost(cost.output * 1.5),\n\t\t\t\tcacheRead: roundCost(cost.cacheRead * 2),\n\t\t\t\tcacheWrite: roundCost(cost.cacheWrite * 2),\n\t\t\t},\n\t\t],\n\t};\n}\n\nconst OPENAI_CODEX_COSTS = {\n\t\"gpt-5.6-luna\": { input: 0.2, output: 1.2, cacheRead: 0.02, cacheWrite: 0.25 },\n\t\"gpt-5.6-terra\": { input: 2, output: 12, cacheRead: 0.2, cacheWrite: 2.5 },\n\t\"gpt-6-luna\": { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125 },\n} satisfies Record<string, Model.Info[\"cost\"]>;\n\nconst OPENAI_CODEX_MODELS: OpenAICodexModelSeed[] = [\n\t{\n\t\tid: \"gpt-5.3-codex-spark\",\n\t\tname: \"GPT-5.3 Codex Spark\",\n\t\tinput: [\"text\"],\n\t\tcost: { input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 },\n\t\tcontextWindow: OPENAI_CODEX_SPARK_CONTEXT,\n\t},\n\t{\n\t\tid: \"gpt-5.4\",\n\t\tname: \"GPT-5.4\",\n\t\tinput: [\"text\", \"image\"],\n\t\tcost: withOpenAiLongContextPricing({ input: 2.5, output: 15, cacheRead: 0.25, cacheWrite: 0 }),\n\t\tcontextWindow: OPENAI_CODEX_CONTEXT,\n\t},\n\t{\n\t\tid: \"gpt-5.4-mini\",\n\t\tname: \"GPT-5.4 mini\",\n\t\tinput: [\"text\", \"image\"],\n\t\tcost: { input: 0.75, output: 4.5, cacheRead: 0.075, cacheWrite: 0 },\n\t\tcontextWindow: OPENAI_CODEX_CONTEXT,\n\t},\n\t{\n\t\tid: \"gpt-5.5\",\n\t\tname: \"GPT-5.5\",\n\t\tinput: [\"text\", \"image\"],\n\t\tcost: withOpenAiLongContextPricing({ input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0 }),\n\t\tcontextWindow: OPENAI_CODEX_CONTEXT,\n\t},\n\t{\n\t\tid: \"gpt-5.6-luna\",\n\t\tname: \"GPT-5.6 Luna\",\n\t\tinput: [\"text\", \"image\"],\n\t\tcost: withOpenAiLongContextPricing(OPENAI_CODEX_COSTS[\"gpt-5.6-luna\"]),\n\t\tcontextWindow: OPENAI_CODEX_GPT_56_CONTEXT,\n\t\tthinkingLevelMap: { minimal: null },\n\t},\n\t{\n\t\tid: \"gpt-5.6-sol\",\n\t\tname: \"GPT-5.6 Sol\",\n\t\tinput: [\"text\", \"image\"],\n\t\tcost: withOpenAiLongContextPricing({ input: 5, output: 30, cacheRead: 0.5, cacheWrite: 6.25 }),\n\t\tcontextWindow: OPENAI_CODEX_GPT_56_CONTEXT,\n\t\tthinkingLevelMap: { minimal: null },\n\t},\n\t{\n\t\tid: \"gpt-5.6-terra\",\n\t\tname: \"GPT-5.6 Terra\",\n\t\tinput: [\"text\", \"image\"],\n\t\tcost: withOpenAiLongContextPricing(OPENAI_CODEX_COSTS[\"gpt-5.6-terra\"]),\n\t\tcontextWindow: OPENAI_CODEX_GPT_56_CONTEXT,\n\t\tthinkingLevelMap: { minimal: null },\n\t},\n\t{\n\t\tid: \"gpt-6-luna\",\n\t\tname: \"GPT-6 Luna\",\n\t\tinput: [\"text\", \"image\"],\n\t\tcost: withOpenAiLongContextPricing(OPENAI_CODEX_COSTS[\"gpt-6-luna\"]),\n\t\tcontextWindow: OPENAI_CODEX_GPT_56_CONTEXT,\n\t},\n];\n\nexport function openAICodexBuiltInModels(): Record<string, Model.Info> {\n\tconst models: Record<string, Model.Info> = {};\n\tfor (const seed of OPENAI_CODEX_MODELS) {\n\t\tconst supportsToolSearch = OPENAI_CODEX_TOOL_SEARCH_MODEL_IDS.has(seed.id);\n\t\tconst supportsAdditionalTools = OPENAI_CODEX_ADDITIONAL_TOOLS_MODEL_IDS.has(seed.id);\n\t\tconst info: Model.Info = {\n\t\t\t...seed,\n\t\t\tprovider: {\n\t\t\t\tid: OPENAI_CODEX_PROVIDER_ID,\n\t\t\t\tname: \"OpenAI Codex (ChatGPT)\",\n\t\t\t\tsource: \"custom\",\n\t\t\t\tenv: [\"OPENAI_CODEX_API_KEY\"],\n\t\t\t},\n\t\t\tbaseUrl: OPENAI_CODEX_BASE_URL,\n\t\t\treasoning: true,\n\t\t\t// Codex models reason unless verified to accept \"none\".\n\t\t\tthinkingLevelMap: {\n\t\t\t\toff: OPENAI_CODEX_NONE_REASONING_MODEL_IDS.has(seed.id) ? \"none\" : null,\n\t\t\t\t...seed.thinkingLevelMap,\n\t\t\t},\n\t\t\tmaxTokens: OPENAI_CODEX_MAX_TOKENS,\n\t\t\tnpm: OPENAI_CODEX_NPM,\n\t\t\tapi: {\n\t\t\t\tid: seed.id,\n\t\t\t\turl: OPENAI_CODEX_BASE_URL,\n\t\t\t\tmethod: Model.APIMethodEnum.responses,\n\t\t\t},\n\t\t\tproviderOptionsKey: OPENAI_CODEX_PROVIDER_ID,\n\t\t\tcompat: {\n\t\t\t\tsupportsOpenAIGrammarTools: true,\n\t\t\t\t...(supportsToolSearch ? { supportsToolSearch: true } : {}),\n\t\t\t\t...(supportsAdditionalTools ? { supportsAdditionalTools: true } : {}),\n\t\t\t},\n\t\t\tprotocol: Model.KnownProviderEnum.openaiCodex,\n\t\t};\n\t\tapplyModelMetadata(info);\n\t\tmodels[seed.id] = info;\n\t}\n\treturn models;\n}\n\n//\n// GitHub Copilot models.\n// Sourced from models.dev, then rewritten onto the bundled provider: one\n// `github-copilot` protocol whose `api.method` selects between Chat\n// Completions, Responses, and Anthropic Messages.\nconst GITHUB_COPILOT_PROVIDER_ID = \"github-copilot\";\nconst GITHUB_COPILOT_NPM = \"@codeworksh/ai-sdk-github-copilot\";\nconst GITHUB_COPILOT_BASE_URL = \"https://api.githubcopilot.com\";\nconst GITHUB_COPILOT_EXTENDED_CONTEXT = 1_000_000;\n\n// GitHub's \"Models with extended capabilities\" table lists these Copilot\n// models as supporting the extended 1 million token context window (pi).\nconst GITHUB_COPILOT_EXTENDED_CONTEXT_MODELS = new Set([\n\t\"claude-fable-5\",\n\t\"claude-opus-4.6\",\n\t\"claude-opus-4.7\",\n\t\"claude-opus-4.8\",\n\t\"claude-opus-5\",\n\t\"claude-sonnet-4.6\",\n\t\"claude-sonnet-5\",\n\t\"gpt-5.3-codex\",\n\t\"gpt-5.4\",\n\t\"gpt-5.5\",\n]);\n\n// Checked manually against the authenticated GitHub Copilot /models endpoint\n// (pi). Narrow corrections over models.dev metadata, not a catalog snapshot.\nconst GITHUB_COPILOT_THINKING_LEVEL_OVERRIDES: Record<string, ThinkingLevelMap> = {\n\t\"claude-opus-4.7\": { minimal: \"low\" },\n\t\"claude-opus-4.8\": { minimal: \"low\" },\n\t\"claude-opus-5\": { minimal: \"low\" },\n\t\"claude-sonnet-4.6\": { minimal: \"low\", max: \"max\" },\n};\n\n/**\n * The offline routing approximation (pi). The live `/models` response's\n * `supported_endpoints` is authoritative at runtime.\n *\n * - `claude-(haiku|sonnet|opus|fable)-[45]` → Anthropic Messages\n * - `gpt-*`, `grok-*`, `oswe*`, `mai-*` → OpenAI Responses\n * - everything else → OpenAI Chat Completions\n */\nexport function githubCopilotApiMethod(modelId: string): Model.APIMethodEnum {\n\tif (/^claude-(haiku|sonnet|opus|fable)-[45]([.-]|$)/.test(modelId)) {\n\t\treturn Model.APIMethodEnum.messages;\n\t}\n\tconst gpt = /^gpt-(\\d+)/.exec(modelId);\n\tif (\n\t\t(gpt !== null && Number(gpt[1]) >= 5) ||\n\t\tmodelId.startsWith(\"grok-\") ||\n\t\tmodelId.startsWith(\"oswe\") ||\n\t\tmodelId.startsWith(\"mai-\")\n\t) {\n\t\treturn Model.APIMethodEnum.responses;\n\t}\n\treturn Model.APIMethodEnum.chat;\n}\n\n/** Effort values models.dev advertises for a model, when it lists any. */\nfunction githubCopilotEffortValues(model: ModelsDevModel): Set<string> | undefined {\n\tfor (const option of model.reasoning_options ?? []) {\n\t\tif (option.type === \"effort\" && Array.isArray(option.values)) return new Set(option.values);\n\t}\n\treturn undefined;\n}\n\n/**\n * Derive the level map from models.dev `reasoning_options`: a level maps to\n * itself only when the endpoint actually advertises it. `minimal` degrades to\n * `low` — the lowest effort every reasoning model accepts.\n */\nfunction githubCopilotThinkingLevels(model: ModelsDevModel, method: Model.APIMethodEnum): ThinkingLevelMap | undefined {\n\tconst efforts = githubCopilotEffortValues(model);\n\tconst map: ThinkingLevelMap = {};\n\t// Copilot rejects `reasoningEffort: \"none\"` (pi), and the chat route has no\n\t// reasoning control, so only Messages models can disable thinking.\n\tif (method !== Model.APIMethodEnum.messages) map.off = null;\n\tif (!efforts) return Object.keys(map).length > 0 ? map : undefined;\n\n\tif (efforts.has(\"minimal\")) map.minimal = \"minimal\";\n\telse if (efforts.has(\"low\")) map.minimal = \"low\";\n\tfor (const level of [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const) {\n\t\tmap[level] = efforts.has(level) ? level : null;\n\t}\n\treturn map;\n}\n\nfunction githubCopilotCostTiers(model: ModelsDevModel): Model.Info[\"cost\"][\"tiers\"] | undefined {\n\tconst tiers = model.cost?.tiers?.flatMap((tier) => {\n\t\tconst context = tier.tier;\n\t\tif (context?.type !== \"context\" || context.size === undefined) return [];\n\t\treturn [\n\t\t\t{\n\t\t\t\tinputTokensAbove: context.size,\n\t\t\t\tinput: tier.input ?? 0,\n\t\t\t\toutput: tier.output ?? 0,\n\t\t\t\tcacheRead: tier.cache_read ?? 0,\n\t\t\t\tcacheWrite: tier.cache_write ?? 0,\n\t\t\t},\n\t\t];\n\t});\n\treturn tiers && tiers.length > 0 ? tiers : undefined;\n}\n\nexport function githubCopilotBuiltInModels(provider: ModelsDevProvider | undefined): Record<string, Model.Info> {\n\tconst models: Record<string, Model.Info> = {};\n\tif (!provider) return models;\n\tfor (const [id, source] of Object.entries(provider.models)) {\n\t\tif (source.tool_call !== true) continue;\n\t\tif (source.status === \"deprecated\") continue;\n\t\t// The chat-latest alias races the Responses route for gpt-5 models.\n\t\tif (id === \"gpt-5-chat-latest\") continue;\n\n\t\tconst base = applyModification(GITHUB_COPILOT_PROVIDER_ID, provider, source);\n\t\tif (!base) continue;\n\n\t\tconst method = githubCopilotApiMethod(id);\n\t\tconst tiers = githubCopilotCostTiers(source);\n\t\tconst info: Model.Info = {\n\t\t\t...base,\n\t\t\tprovider: {\n\t\t\t\tid: GITHUB_COPILOT_PROVIDER_ID,\n\t\t\t\tname: \"GitHub Copilot\",\n\t\t\t\tsource: \"custom\",\n\t\t\t\tenv: [\"COPILOT_GITHUB_TOKEN\"],\n\t\t\t},\n\t\t\tbaseUrl: GITHUB_COPILOT_BASE_URL,\n\t\t\theaders: { ...GITHUB_COPILOT_STATIC_HEADERS },\n\t\t\tcost: { ...base.cost, ...(tiers ? { tiers } : {}) },\n\t\t\tnpm: GITHUB_COPILOT_NPM,\n\t\t\tapi: { id, url: GITHUB_COPILOT_BASE_URL, method },\n\t\t\tproviderOptionsKey: GITHUB_COPILOT_PROVIDER_ID,\n\t\t\tprotocol: Model.KnownProviderEnum.githubCopilot,\n\t\t\t// Copilot's Responses route requires store=false + encrypted reasoning\n\t\t\t// content for thinking to round-trip.\n\t\t\t...(method === Model.APIMethodEnum.responses\n\t\t\t\t? {\n\t\t\t\t\t\tproviderOptions: {\n\t\t\t\t\t\t\t...base.providerOptions,\n\t\t\t\t\t\t\t[GITHUB_COPILOT_PROVIDER_ID]: {\n\t\t\t\t\t\t\t\tstore: false,\n\t\t\t\t\t\t\t\tinclude: [\"reasoning.encrypted_content\"],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\n\t\tif (GITHUB_COPILOT_EXTENDED_CONTEXT_MODELS.has(id)) info.contextWindow = GITHUB_COPILOT_EXTENDED_CONTEXT;\n\t\tif (method === Model.APIMethodEnum.messages && Model.isAnthropicAdaptiveThinkingModel(id)) {\n\t\t\tmergeCompat(info, { forceAdaptiveThinking: true });\n\t\t}\n\t\t// Copilot's Responses endpoint passes OpenAI custom grammar tools through\n\t\t// for GPT-5+ (verified by pi).\n\t\tconst gpt = /^gpt-(\\d+)/.exec(id);\n\t\tif (method === Model.APIMethodEnum.responses && gpt !== null && Number(gpt[1]) >= 5) {\n\t\t\tmergeCompat(info, { supportsOpenAIGrammarTools: true });\n\t\t}\n\t\tif (id.startsWith(\"gpt-5\")) mergeThinkingLevelMap(info, { off: null, minimal: \"low\" });\n\t\tif (id.includes(\"fable-5\")) mergeThinkingLevelMap(info, { off: null, xhigh: \"xhigh\", max: \"max\" });\n\n\t\tconst levels = githubCopilotThinkingLevels(source, method);\n\t\tif (levels) mergeThinkingLevelMap(info, levels);\n\t\tconst override = GITHUB_COPILOT_THINKING_LEVEL_OVERRIDES[id];\n\t\tif (override) mergeThinkingLevelMap(info, override);\n\n\t\tmodels[id] = info;\n\t}\n\treturn models;\n}\n\nexport async function generateModels(args: { path?: string | undefined } = {}): Promise<string> {\n\tconst path = resolve(args.path ?? ModelCatalog.path());\n\tconst catalog = await pullModelsDevData();\n\tconst modelsDev = loadBuiltInFromModelsDev(catalog);\n\tconst customCodexModels = openAICodexBuiltInModels();\n\tconst copilotProvider = catalog[GITHUB_COPILOT_PROVIDER_ID];\n\n\tconst allModels = {\n\t\t...modelsDev,\n\t\t[OPENAI_CODEX_PROVIDER_ID]: customCodexModels,\n\t\t...(copilotProvider ? { [GITHUB_COPILOT_PROVIDER_ID]: githubCopilotBuiltInModels(copilotProvider) } : {}),\n\t};\n\tawait Filesystem.writeJsonAtomic(path, allModels);\n\treturn path;\n}\n\n//\n// CLI entry\nexport const ModelgenCommand: CommandModule<object, { path?: string | undefined }> = {\n\tcommand: \"modelgen [path]\",\n\tdescribe: \"generate models.gen.json\",\n\tbuilder: (yargs) =>\n\t\tyargs.positional(\"path\", {\n\t\t\ttype: \"string\",\n\t\t\tdescribe: \"output path (defaults to CODEWORK_MODELS_FILE or ./models.gen.json)\",\n\t\t}),\n\thandler: async (args) => {\n\t\tconst path = await generateModels(args);\n\t\tconsole.log(`Generated model catalog at ${path}`);\n\t},\n};\n\nexport function applyModification(\n\tproviderId: string,\n\tprovider: ModelsDevProvider,\n\tmodel: ModelsDevModel,\n): Model.Info | undefined {\n\tconst npm = resolveModelNpm(provider, model);\n\tif (!isAISDKPackage(npm)) return;\n\n\tconst protocol = protocolForPackage(npm);\n\tconst baseUrl = resolveModelBaseUrl(provider, model);\n\tconst providerInfo: Model.ProviderInfo = {\n\t\tid: providerId,\n\t\tname: provider.name,\n\t\tsource: \"api\",\n\t\tenv: provider.env,\n\t};\n\tif (provider.key) providerInfo.key = provider.key;\n\tconst api: Model.APIMetadata = {\n\t\tid: model.id,\n\t\tmethod: resolveModelAPIMethod(npm),\n\t};\n\tif (baseUrl) api.url = baseUrl;\n\n\tconst info: Model.Info = {\n\t\tid: model.id,\n\t\tname: model.name,\n\t\tprovider: providerInfo,\n\t\tbaseUrl,\n\t\treasoning: Boolean(model.reasoning),\n\t\tinput: Model.normalizeInput(model.modalities.input),\n\t\tcost: {\n\t\t\tinput: model.cost?.input ?? 0,\n\t\t\toutput: model.cost?.output ?? 0,\n\t\t\tcacheRead: model.cost?.cache_read ?? 0,\n\t\t\tcacheWrite: model.cost?.cache_write ?? 0,\n\t\t},\n\t\tcontextWindow: model.limit?.context ?? 4096,\n\t\tmaxTokens: model.limit?.output ?? 4096,\n\t\theaders: {\n\t\t\t...provider.headers,\n\t\t\t...model.provider?.headers,\n\t\t\t...model.headers,\n\t\t},\n\t\tnpm,\n\t\tapi,\n\t\tproviderOptionsKey: resolveProviderOptionsKey(protocol),\n\t\tprotocol,\n\t};\n\tif (Object.keys(info.headers ?? {}).length === 0) delete info.headers;\n\tapplyModelMetadata(info);\n\treturn info;\n}\n"],"mappings":";;;;;;AASA,MAAM,6BAA+E;EAC3D,kBAAA,YAAY;EACZ,kBAAA,SAAS;EACT,kBAAA,aAAa;EACb,kBAAA,MAAM;AAChC;AAsEA,SAAS,eAAuB;CAC/B,OAAO,QAAQ,IAAI,uBAAuB;AAC3C;AAEA,SAAS,gBAAoC;CAC5C,OAAO,QAAQ,IAAI;AACpB;AAEA,eAAe,oBAA+C;CAC7D,MAAM,OAAO,cAAc;CAC3B,IAAI,MAAM;EACT,MAAM,SAAS,MAAMA,SAAsC,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;EACtF,IAAI,QAAQ,OAAO;CACpB;CAEA,MAAM,WAAW,MAAM,MAAM,GAAG,aAAa,EAAE,UAAU;CACzD,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,wBAAwB,SAAS,OAAO,GAAG,SAAS,YAAY;CAClG,OAAQ,MAAM,SAAS,KAAK;AAC7B;AAEA,SAAS,aAAa,YAAoB,UAA6B,OAA+C;CACrH,OAAO,kBAAkB,YAAY,UAAU,KAAK;AACrD;AAEA,SAAS,yBAAyB,SAA2B;CAC5D,OAAO,KACN,SACA,QAAQ,aACP,OAAO,OAAO,SAAS,MAAM,CAAC,CAAC,MAI7B,UAAU,QAAQ,MAAM,SAAS,KAAK,eAAe,gBAAgB,UAAU,KAAK,CAAC,CACvF,CACD,GACA,WAAW,UAAU,eACpB,KACC,SAAS,QACT,QAAQ,UAAU,QAAQ,MAAM,SAA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