@codeworksh/aikit 0.7.0 → 0.7.1-dev.20260824182047
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 +1 -1
- package/index.mjs +27 -2
- package/index.mjs.map +1 -1
- package/package.json +1 -1
package/cli.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { t as ModelgenCommand } from "./modelgen-BcsqB44a.mjs";
|
|
|
4
4
|
import yargs from "yargs";
|
|
5
5
|
import { hideBin } from "yargs/helpers";
|
|
6
6
|
//#region package.json
|
|
7
|
-
var version = "0.7.
|
|
7
|
+
var version = "0.7.1";
|
|
8
8
|
//#endregion
|
|
9
9
|
//#region src/cli/oauth.ts
|
|
10
10
|
async function promptLine(message) {
|
package/index.mjs
CHANGED
|
@@ -1040,6 +1040,27 @@ function normalizeOpenAICodexToolCallId(id, model, source) {
|
|
|
1040
1040
|
if (!normalizedItemId.startsWith("fc_") && !normalizedItemId.startsWith("ctc_")) normalizedItemId = normalizeOpenAICodexIdPart(`fc_${normalizedItemId}`);
|
|
1041
1041
|
return `${normalizedCallId}|${normalizedItemId}`;
|
|
1042
1042
|
}
|
|
1043
|
+
function isRecord(value) {
|
|
1044
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1045
|
+
}
|
|
1046
|
+
function encodeOpenAIReasoningSignature(providerMetadata) {
|
|
1047
|
+
if (!isRecord(providerMetadata)) return;
|
|
1048
|
+
const metadata = providerMetadata.openai;
|
|
1049
|
+
if (!isRecord(metadata) || typeof metadata.itemId !== "string") return;
|
|
1050
|
+
const signature = { itemId: metadata.itemId };
|
|
1051
|
+
if (typeof metadata.reasoningEncryptedContent === "string" || metadata.reasoningEncryptedContent === null) signature.reasoningEncryptedContent = metadata.reasoningEncryptedContent;
|
|
1052
|
+
return JSON.stringify(signature);
|
|
1053
|
+
}
|
|
1054
|
+
function decodeOpenAIReasoningSignature(signature) {
|
|
1055
|
+
try {
|
|
1056
|
+
const parsed = JSON.parse(signature);
|
|
1057
|
+
if (isRecord(parsed) && typeof parsed.itemId === "string") return {
|
|
1058
|
+
itemId: parsed.itemId,
|
|
1059
|
+
...typeof parsed.reasoningEncryptedContent === "string" || parsed.reasoningEncryptedContent === null ? { reasoningEncryptedContent: parsed.reasoningEncryptedContent } : {}
|
|
1060
|
+
};
|
|
1061
|
+
} catch {}
|
|
1062
|
+
return { itemId: signature };
|
|
1063
|
+
}
|
|
1043
1064
|
function assistantMessages(message, model) {
|
|
1044
1065
|
if (message.stopReason === "error" || message.stopReason === "aborted") return [];
|
|
1045
1066
|
const assistantContent = [];
|
|
@@ -1062,7 +1083,10 @@ function assistantMessages(message, model) {
|
|
|
1062
1083
|
type: "reasoning",
|
|
1063
1084
|
text: thinking
|
|
1064
1085
|
};
|
|
1065
|
-
if (
|
|
1086
|
+
if (message.protocol === KnownProviderEnum.openai) {
|
|
1087
|
+
if (!part.thinkingSignature) continue;
|
|
1088
|
+
reasoning.providerOptions = { openai: decodeOpenAIReasoningSignature(part.thinkingSignature) };
|
|
1089
|
+
} else if (part.thinkingSignature) reasoning.providerOptions = message.protocol === KnownProviderEnum.openaiCodex ? { "openai-codex": { reasoningItem: part.thinkingSignature } } : { anthropic: { signature: part.thinkingSignature } };
|
|
1066
1090
|
assistantContent.push(reasoning);
|
|
1067
1091
|
continue;
|
|
1068
1092
|
}
|
|
@@ -1434,7 +1458,8 @@ function handlePart(part, output, model, stream, costMultiplier) {
|
|
|
1434
1458
|
}
|
|
1435
1459
|
case "reasoning-end": {
|
|
1436
1460
|
const reasoningItem = openAICodexMetadata(part.providerMetadata)?.reasoningItem;
|
|
1437
|
-
|
|
1461
|
+
const openAISignature = encodeOpenAIReasoningSignature(part.providerMetadata);
|
|
1462
|
+
finishThinkingBlock(output, part.id, stream, typeof reasoningItem === "string" ? reasoningItem : openAISignature);
|
|
1438
1463
|
break;
|
|
1439
1464
|
}
|
|
1440
1465
|
case "tool-input-start":
|
package/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Type","Model.KnownProviderEnumSchema","Model.ProviderInfo","createAssistantMessage","Type","Message.AssistantMessageSchema","Message.ToolCallSchema","Message.TextContentSchema","Message.ImageContentSchema","Message.ThinkingContentSchema","Message.UserMessageSchema","Message.ToolCallPendingPartSchema","Message.ToolCallRunningPartSchema","Message.ToolCallTerminalPartSchema","Message.MessageSchema","Model.getModel","Model.getModels","Model.getProviders","Model.registry","Model.modelsAreEqual","Type","Model.KnownProviderEnumSchema","stream","Type","Type","Model.APIMethodEnumSchema","Model.ActiveThinkingLevel","Protocol.ProtocolAuthError","partialParse","Message.createAssistantMessage","Message.transformMessages","Model.clampThinkingLevel","stream","Protocol.stream","Protocol.complete","Protocol.resolveProtocolProvider"],"sources":["../../src/message/message.ts","../../src/event/event.ts","../../src/llm.ts","../../src/llm/protocol.ts","../../src/llm/shared.ts","../../src/llm/options.ts","../../src/utils/eventstream.ts","../../src/utils/helpers.ts","../../src/llm/runtime.ts","../../src/llm/provider.ts","../../src/utils/jsonparse.ts","../../src/utils/sanitize.ts","../../src/llm/transform.ts","../../src/llm/stream.ts","../../src/llm/index.ts","../../src/llm/register.ts","../../src/stream.ts","../../src/utils/validation.ts"],"sourcesContent":["import Type, { type Static, type TSchema } from \"typebox\";\nimport { uuidv7 } from \"uuidv7\";\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\tthinkingSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the reasoning item ID\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\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\tusage: UsageSchema,\n\tstopReason: StopReasonSchema,\n\terrorMessage: Type.Optional(Type.String()),\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\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\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\n\tconst transformed: Message[] = [];\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\ttransformed.push(msg);\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\" && isUnresolvedToolCall(block)) {\n\t\t\t\treturn syntheticSkippedToolCall(block);\n\t\t\t}\n\t\t\treturn block;\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, { type Static } from \"typebox\";\nimport * as Message from \"../message/message.ts\";\n\n// TODO @sanchitrk:\n// for delta events we can have metadata KV that a provider can use for internal state\n// similar to index what anthropic does\nexport const LLMMessageEventType = {\n\tstart: \"start\",\n\n\ttextStart: \"text.start\",\n\ttextDelta: \"text.delta\",\n\ttextEnd: \"text.end\",\n\n\tthinkingStart: \"thinking.start\",\n\tthinkingDelta: \"thinking.delta\",\n\tthinkingEnd: \"thinking.end\",\n\n\ttoolcallStart: \"toolcall.start\",\n\ttoolcallDelta: \"toolcall.delta\",\n\ttoolcallEnd: \"toolcall.end\",\n\ttoolcallFinal: \"toolcall.final\",\n\n\tdone: \"done\",\n\terror: \"error\",\n} as const;\nexport type LLMMessageEventType = (typeof LLMMessageEventType)[keyof typeof LLMMessageEventType];\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Streams should emit `start` before partial updates, then terminate with either:\n * - `done` carrying the final successful AssistantMessage, or\n * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n * and errorMessage.\n */\nexport const LLMMessageEventSchema = Type.Union([\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.start),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallEnd),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallFinal),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.done),\n\t\treason: Type.Union([Type.Literal(\"stop\"), Type.Literal(\"length\"), Type.Literal(\"toolUse\")]),\n\t\tmessage: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.error),\n\t\treason: Type.Union([Type.Literal(\"aborted\"), Type.Literal(\"error\")]),\n\t\terror: Message.AssistantMessageSchema,\n\t}),\n]);\nexport type LLMMessageEvent = Static<typeof LLMMessageEventSchema>;\n\nexport const AgentEventType = {\n\t// Agent lifecycle\n\tagentStart: \"agent.start\",\n\tagentEnd: \"agent.end\",\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\tturnStart: \"turn.start\",\n\tturnEnd: \"turn.end\",\n\t// Message lifecycle - emitted for user, assistant message and corresponding parts\n\tmessageStart: \"message.start\",\n\n\tmessagePartStart: \"message.part.start\",\n\tmessagePartUpdate: \"message.part.update\",\n\tmessagePartEnd: \"message.part.end\",\n\n\tmessageUpdate: \"message.update\",\n\tmessageEnd: \"message.end\",\n\t// Tool execution lifecycle\n\ttoolExecutionStart: \"tool.execution.start\",\n\ttoolExecutionUpdate: \"tool.execution.update\",\n\ttoolExecutionEnd: \"tool.execution.end\",\n} as const;\nexport type AgentEventType = (typeof AgentEventType)[keyof typeof AgentEventType];\n\n//\n// message parts\nconst UserMessagePart = Type.Union([Message.TextContentSchema, Message.ImageContentSchema]);\nconst AssistantMessagePart = Type.Union([\n\tMessage.TextContentSchema,\n\tMessage.ImageContentSchema,\n\tMessage.ThinkingContentSchema,\n\tMessage.ToolCallSchema,\n]);\n\n//\n// user message part\n// part start\nconst UserMessagePartStart = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartStart),\n\tmessage: Message.UserMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: UserMessagePart,\n});\n// part end\nconst UserMessagePartEnd = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\tmessage: Message.UserMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: UserMessagePart,\n});\n\n//\n// assistant message part\n// part start\nconst AssistantMessagePartStart = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartStart),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n});\n// part update llm\nconst AssistantMessagePartLLMUpdate = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n\tsource: Type.Literal(\"llm\"),\n});\n// part update tool\nconst AssistantMessagePartToolUpdate = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n\tsource: Type.Literal(\"tool\"),\n});\n// part end\nconst AssistantMessagePartEnd = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n});\n\n//\n// tool exection\nconst ToolExecutionStartSchema = Type.Object({\n\ttype: Type.Literal(AgentEventType.toolExecutionStart),\n\tmessageId: Type.String(),\n\tpartIndex: Type.Number(),\n\ttoolCall: Message.ToolCallPendingPartSchema,\n});\nexport type ToolExecutionStart = Static<typeof ToolExecutionStartSchema>;\n\nconst ToolExecutionUpdateSchema = Type.Object({\n\ttype: Type.Literal(AgentEventType.toolExecutionUpdate),\n\tmessageId: Type.String(),\n\tpartIndex: Type.Number(),\n\ttoolCall: Message.ToolCallRunningPartSchema,\n});\nexport type ToolExecutionUpdate = Static<typeof ToolExecutionUpdateSchema>;\n\nconst ToolExecutionEndSchema = Type.Object({\n\ttype: Type.Literal(AgentEventType.toolExecutionEnd),\n\tmessageId: Type.String(),\n\tpartIndex: Type.Number(),\n\ttoolCall: Message.ToolCallTerminalPartSchema,\n});\nexport type ToolExecutionEnd = Static<typeof ToolExecutionEndSchema>;\n\n/**\n * Events emitted by the Agent lifecycle\n * These events provide fine-grained lifecycle information for messages, turns, and tool execution.\n */\nexport const AgentEventSchema = Type.Union([\n\t//\n\t// Agent lifecycle\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.agentStart),\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.agentEnd),\n\t\tmessages: Type.Array(Message.MessageSchema),\n\t}),\n\t//\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.turnStart),\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.turnEnd),\n\t\tmessage: Message.AssistantMessageSchema,\n\t}),\n\t//\n\t// Message lifecycle - emitted for user, assistant and corresponding parts\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.messageStart),\n\t\tmessage: Message.MessageSchema,\n\t}),\n\t// user message parts lifecycle\n\tType.Union([UserMessagePartStart, UserMessagePartEnd]),\n\t//\n\t// assistant message parts lifecycle\n\tType.Union([\n\t\tAssistantMessagePartStart,\n\t\tAssistantMessagePartLLMUpdate,\n\t\tAssistantMessagePartToolUpdate,\n\t\tAssistantMessagePartEnd,\n\t]),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.messageUpdate),\n\t\tmessage: Message.MessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.messageEnd),\n\t\tmessage: Message.MessageSchema,\n\t}),\n\t//\n\t// Tool execution lifecycle\n\tToolExecutionStartSchema,\n\tToolExecutionUpdateSchema,\n\tToolExecutionEndSchema,\n]);\nexport type AgentEvent = Static<typeof AgentEventSchema>;\n","import * as Model from \"./model/model.ts\";\n\ntype LLM = {\n\t<TProvider extends string, TProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>>(\n\t\tprovider: TProvider,\n\t\tmodel: string,\n\t\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n\t): Promise<Model.TModel<TProtocol> | undefined>;\n\tmodel: typeof Model.getModel;\n\tmodels: typeof Model.getModels;\n\tproviders: typeof Model.getProviders;\n\tregistry: typeof Model.registry;\n\tmodelsAreEqual: typeof Model.modelsAreEqual;\n};\n\nconst llmImpl = async <\n\tTProvider extends string,\n\tTProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>,\n>(\n\tprovider: TProvider,\n\tmodel: string,\n\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n): Promise<Model.TModel<TProtocol> | undefined> => Model.getModel(provider, model, overrides as any);\n\nexport const llm = Object.assign(llmImpl, {\n\tmodel: Model.getModel,\n\tmodels: Model.getModels,\n\tproviders: Model.getProviders,\n\tregistry: Model.registry,\n\tmodelsAreEqual: Model.modelsAreEqual,\n}) as LLM;\n","import { NamedError } from \"@codeworksh/utils\";\nimport type { Static, TSchema } from \"typebox\";\nimport Type from \"typebox\";\nimport type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport type {\n\tAnthropicOptions,\n\tGoogleOptions,\n\tGoogleVertexAnthropicOptions,\n\tGoogleVertexOptions,\n\tOpenAICodexOptions,\n\tOpenAICompatibleOptions,\n\tOpenAIOptions,\n\tOpenRouterOptions,\n\tXaiOptions,\n} from \"./options.ts\";\nimport type { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\nexport const ProviderProtocolNotFoundError = NamedError.create(\n\t\"ProviderProtocolNotFoundError\",\n\tType.Object({\n\t\tprotocol: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProviderProtocolNotFoundError = InstanceType<typeof ProviderProtocolNotFoundError>;\n\nexport const ProtocolMismatchError = NamedError.create(\n\t\"ProtocolMismatchError\",\n\tType.Object({\n\t\tactual: Model.KnownProviderEnumSchema,\n\t\texpected: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\nexport const ProtocolAuthError = NamedError.create(\n\t\"ProtocolAuthError\",\n\tType.Object({\n\t\tmessage: Type.String(),\n\t\tprotocol: Type.String(),\n\t}),\n);\nexport type ProtocolAuthError = InstanceType<typeof ProtocolAuthError>;\n\nexport type CommonOptions = SharedOptions & {\n\treasoning?: Model.ActiveThinkingLevel;\n\tthinkingBudgets?: ThinkingBudgets;\n};\nexport interface OptionsByProtocol {\n\t[Model.KnownProviderEnum.openai]: OpenAIOptions;\n\t[Model.KnownProviderEnum.anthropic]: AnthropicOptions;\n\t[Model.KnownProviderEnum.google]: GoogleOptions;\n\t[Model.KnownProviderEnum.googleVertex]: GoogleVertexOptions;\n\t[Model.KnownProviderEnum.googleVertexAnthropic]: GoogleVertexAnthropicOptions;\n\t[Model.KnownProviderEnum.openaiCompatible]: OpenAICompatibleOptions;\n\t[Model.KnownProviderEnum.openaiCodex]: OpenAICodexOptions;\n\t[Model.KnownProviderEnum.openrouter]: OpenRouterOptions;\n\t[Model.KnownProviderEnum.xai]: XaiOptions;\n}\nexport type ProtocolWithOptions = keyof OptionsByProtocol & Model.KnownProviderEnum;\nexport type OptionsFor<TProtocol extends ProtocolWithOptions> = OptionsByProtocol[TProtocol];\n\nexport type StreamFunction<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: Static<S>) => AssistantMessageEventStream;\n\nexport type ProtocolStreamFunction<S extends TSchema = TSchema> = (\n\tmodel: Model.Info,\n\tcontext: Message.Context,\n\toptions?: Static<S>,\n) => AssistantMessageEventStream;\n\nexport interface Protocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: StreamFunction<TProtocol, S>;\n}\n\nexport interface RegisteredProtocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: ProtocolStreamFunction<S>;\n}\n\ntype AnyRegisteredProtocol = RegisteredProtocol<Model.KnownProviderEnum, TSchema>;\n\ntype RegistryEntry = {\n\tprovider: AnyRegisteredProtocol;\n\tsourceId?: string;\n};\n\nconst protocolRegistry = new Map<Model.KnownProviderEnum, RegistryEntry>();\n\nfunction wrapStream<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprotocol: TProtocol,\n\tstream: StreamFunction<TProtocol, S>,\n): ProtocolStreamFunction<S> {\n\treturn (model, context, options) => {\n\t\tif (model.protocol !== protocol) {\n\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\tactual: model.protocol,\n\t\t\t\texpected: protocol,\n\t\t\t});\n\t\t}\n\n\t\treturn stream(model as Model.TModel<TProtocol>, context, options);\n\t};\n}\n\nexport function registerProtocolProvider<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprovider: Protocol<TProtocol, S>,\n\tsourceId?: string,\n): void {\n\tconst registered: RegisteredProtocol<TProtocol, S> = {\n\t\tprotocol: provider.protocol,\n\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t};\n\n\tprotocolRegistry.set(provider.protocol, {\n\t\tprovider: registered as AnyRegisteredProtocol,\n\t\t...(sourceId !== undefined && { sourceId }),\n\t});\n}\n\nexport function getProtocolProvider(protocol: Model.KnownProviderEnum): AnyRegisteredProtocol | undefined {\n\treturn protocolRegistry.get(protocol)?.provider;\n}\n\nexport function resolveProtocolProvider(model: Model.Info): AnyRegisteredProtocol {\n\tconst provider = getProtocolProvider(model.protocol);\n\tif (!provider) {\n\t\tthrow new ProviderProtocolNotFoundError({\n\t\t\tprotocol: model.protocol,\n\t\t});\n\t}\n\n\treturn provider;\n}\n\nexport function getProtocolProviders(): AnyRegisteredProtocol[] {\n\treturn Array.from(protocolRegistry.values(), (entry) => entry.provider);\n}\n\nexport function stream<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): AssistantMessageEventStream {\n\tconst provider = resolveProtocolProvider(model);\n\treturn provider.stream(model, context, options);\n}\n\nexport async function complete<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): Promise<Message.AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function unregisterProtocolProviders(sourceId: string): void {\n\tfor (const [protocol, entry] of protocolRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tprotocolRegistry.delete(protocol);\n\t\t}\n\t}\n}\n\nexport function clearProtocolProviders(): void {\n\tprotocolRegistry.clear();\n}\n","import { Type, type Static } from \"typebox\";\nimport type * as Model from \"../model/model.ts\";\n\nexport const CacheRetention = Type.Union([Type.Literal(\"none\"), Type.Literal(\"short\"), Type.Literal(\"long\")]);\nexport type CacheRetention = Static<typeof CacheRetention>;\n\nexport const GenerationOptions = Type.Object({\n\tmaxTokens: Type.Optional(Type.Number()),\n\ttemperature: Type.Optional(Type.Number()),\n\tcacheRetention: Type.Optional(CacheRetention),\n});\n\nexport const HelperOptions = Type.Object({\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tsessionId: Type.Optional(Type.String()),\n\tapiKey: Type.Optional(Type.String()),\n\ttimeoutMs: Type.Optional(Type.Number()),\n\tmaxRetries: Type.Optional(Type.Number()),\n\tsignal: Type.Optional(Type.Unsafe<AbortSignal>({})),\n\tonPayload: Type.Optional(\n\t\tType.Unsafe<(payload: unknown, model: Model.TModel<Model.KnownProviderEnum>) => Promise<unknown>>({}),\n\t),\n\tmetadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\n\nexport const ThinkingBudgets = Type.Object({\n\tminimal: Type.Optional(Type.Number()),\n\tlow: Type.Optional(Type.Number()),\n\tmedium: Type.Optional(Type.Number()),\n\thigh: Type.Optional(Type.Number()),\n\txhigh: Type.Optional(Type.Number()),\n\tmax: Type.Optional(Type.Number()),\n});\nexport type ThinkingBudgets = Static<typeof ThinkingBudgets>;\n\nexport const SharedOptions = Type.Evaluate(Type.Intersect([GenerationOptions, HelperOptions]));\nexport type SharedOptions = Static<typeof SharedOptions>;\n\nconst DEFAULT_MAX_OUTPUT_TOKENS = 32000;\nconst CONTEXT_WINDOW_OUTPUT_TOLERANCE = 1024;\n\nexport function applyDefaultMaxTokens<TOptions extends SharedOptions = SharedOptions>(\n\tmodel: Model.TModel<Model.KnownProviderEnum>,\n\toptions?: TOptions,\n): TOptions & Pick<SharedOptions, \"maxTokens\"> {\n\tconst defaultMaxTokens =\n\t\tmodel.maxTokens > 0\n\t\t\t? model.maxTokens >= model.contextWindow - CONTEXT_WINDOW_OUTPUT_TOLERANCE\n\t\t\t\t? Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS)\n\t\t\t\t: model.maxTokens\n\t\t\t: undefined;\n\n\treturn {\n\t\t...options,\n\t\tmaxTokens: options?.maxTokens ?? defaultMaxTokens,\n\t} as TOptions & Pick<SharedOptions, \"maxTokens\">;\n}\n","import type { AnthropicLanguageModelOptions, AnthropicProviderSettings } from \"@ai-sdk/anthropic\";\nimport type { GoogleGenerativeAIProviderSettings, GoogleLanguageModelOptions } from \"@ai-sdk/google\";\nimport type { GoogleVertexProviderSettings } from \"@ai-sdk/google-vertex\";\nimport type { GoogleVertexAnthropicProviderSettings } from \"@ai-sdk/google-vertex/anthropic\";\nimport type {\n\tOpenAILanguageModelChatOptions,\n\tOpenAILanguageModelCompletionOptions,\n\tOpenAILanguageModelResponsesOptions,\n\tOpenAIProviderSettings,\n} from \"@ai-sdk/openai\";\nimport type {\n\tOpenAICompatibleLanguageModelChatOptions,\n\tOpenAICompatibleLanguageModelCompletionOptions,\n\tOpenAICompatibleProviderSettings,\n} from \"@ai-sdk/openai-compatible\";\nimport type { XaiLanguageModelChatOptions, XaiLanguageModelResponsesOptions, XaiProviderSettings } from \"@ai-sdk/xai\";\nimport type { OpenRouterProviderOptions, OpenRouterProviderSettings } from \"@openrouter/ai-sdk-provider\";\nimport type { OpenAICodexLanguageModelOptions, OpenAICodexProviderSettings } from \"../providers/openai-codex/index.ts\";\nimport { Type, type Static } from \"typebox\";\nimport * as Model from \"../model/model.ts\";\nimport type * as Protocol from \"./protocol.ts\";\nimport { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\n\nexport const Options = Type.Evaluate(\n\tType.Intersect([\n\t\tSharedOptions,\n\t\tType.Object({\n\t\t\tbaseURL: Type.Optional(Type.String()),\n\t\t\tmethod: Type.Optional(Model.APIMethodEnumSchema),\n\t\t\tmodelId: Type.Optional(Type.String()),\n\t\t\treasoning: Type.Optional(Model.ActiveThinkingLevel),\n\t\t\tthinkingBudgets: Type.Optional(ThinkingBudgets),\n\t\t\ttoolChoice: Type.Optional(Type.Any()),\n\t\t\tactiveTools: Type.Optional(Type.Array(Type.String())),\n\t\t\tfactoryOptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\t\t\tproviderOptions: Type.Optional(Type.Record(Type.String(), Type.Record(Type.String(), Type.Unknown()))),\n\t\t}),\n\t]),\n);\n\ntype ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\n\nexport type AISDKOptions<\n\tTFactoryOptions,\n\tTProviderOptions extends ProviderOptionBag = ProviderOptionBag,\n> = Protocol.CommonOptions & {\n\tbaseURL?: string;\n\tmethod?: Model.APIMethodEnum;\n\tmodelId?: string;\n\ttoolChoice?: unknown;\n\tactiveTools?: string[];\n\tfactoryOptions?: Partial<TFactoryOptions> & Record<string, unknown>;\n\tproviderOptions?: TProviderOptions & ProviderOptionBag;\n};\n\ntype OpenAILanguageOptions =\n\t| OpenAILanguageModelResponsesOptions\n\t| OpenAILanguageModelChatOptions\n\t| OpenAILanguageModelCompletionOptions;\ntype OpenAICompatibleLanguageOptions =\n\t| OpenAICompatibleLanguageModelChatOptions\n\t| OpenAICompatibleLanguageModelCompletionOptions;\ntype XaiLanguageOptions = XaiLanguageModelResponsesOptions | XaiLanguageModelChatOptions;\n\nexport type OpenAIOptions = AISDKOptions<OpenAIProviderSettings, { openai?: OpenAILanguageOptions }>;\nexport type AnthropicOptions = AISDKOptions<AnthropicProviderSettings, { anthropic?: AnthropicLanguageModelOptions }>;\nexport type GoogleOptions = AISDKOptions<GoogleGenerativeAIProviderSettings, { google?: GoogleLanguageModelOptions }>;\nexport type GoogleVertexOptions = AISDKOptions<GoogleVertexProviderSettings>;\nexport type GoogleVertexAnthropicOptions = AISDKOptions<GoogleVertexAnthropicProviderSettings>;\nexport type OpenAICompatibleOptions = AISDKOptions<\n\tOpenAICompatibleProviderSettings,\n\t{ \"openai-compatible\"?: OpenAICompatibleLanguageOptions }\n>;\nexport type OpenAICodexOptions = AISDKOptions<\n\tOpenAICodexProviderSettings,\n\t{ \"openai-codex\"?: OpenAICodexLanguageModelOptions }\n>;\nexport type OpenRouterOptions = AISDKOptions<OpenRouterProviderSettings, { openrouter?: OpenRouterProviderOptions }>;\nexport type XaiOptions = AISDKOptions<XaiProviderSettings, { xai?: XaiLanguageOptions }>;\n\nexport type Options = Static<typeof Options>;\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type * as Event from \"../event/event.ts\";\nimport type * as Message from \"../message/message.ts\";\n\n// Implements the async iterator pattern\n// LLM output are streams of events for consuming\n// This class helps with that by acting like buffer data structure to manage the streams\n// for producer and consumer\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate readonly finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\tprivate readonly isComplete: (event: T) => boolean;\n\tprivate readonly extractResult: (event: T) => R;\n\n\tconstructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R) {\n\t\tthis.isComplete = isComplete;\n\t\tthis.extractResult = extractResult;\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<Event.LLMMessageEvent, Message.AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n","import Type, { type TUnsafe } from \"typebox\";\n\n/**\n * `T` with every `undefined`-valued key turned into an optional key.\n */\ntype Compact<T> = {\n\t[K in keyof T as undefined extends T[K] ? never : K]: T[K];\n} & {\n\t[K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined>;\n};\n\n/**\n * Drops keys whose value is `undefined`.\n *\n * Under `exactOptionalPropertyTypes` an explicit `undefined` is not assignable to an optional\n * property, so a literal built from optional inputs has to omit the key rather than pass it\n * through. Only worth reaching for when a literal forwards many optional values at once — for a\n * handful of keys a conditional spread reads better.\n */\nexport function compact<T extends object>(value: T): Compact<T> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tif (entry !== undefined) result[key] = entry;\n\t}\n\treturn result as Compact<T>;\n}\n\n/**\n * Creates a string enum schema compatible with Google's API and other providers\n * that don't support anyOf/const patterns.\n *\n * @example\n * const OperationSchema = StringEnum([\"add\", \"subtract\", \"multiply\", \"divide\"], {\n * description: \"The operation to perform\"\n * });\n *\n * type Operation = Static<typeof OperationSchema>; // \"add\" | \"subtract\" | \"multiply\" | \"divide\"\n */\nexport function StringEnum<T extends readonly string[]>(\n\tvalues: T,\n\toptions?: { description?: string; default?: T[number] },\n): TUnsafe<T[number]> {\n\treturn Type.Unsafe<T[number]>({\n\t\ttype: \"string\",\n\t\tenum: values as any,\n\t\t...(options?.description && { description: options.description }),\n\t\t...(options?.default && { default: options.default }),\n\t});\n}\n","type ApiKeyProvider = {\n\tenv?: string[];\n\tkey?: string;\n};\n\nexport function mergeHeaders(\n\t...headerSources: (Record<string, string | null> | undefined)[]\n): Record<string, string | null> {\n\tconst merged: Record<string, string | null> = {};\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\treturn merged;\n}\n\nexport function getEnvApiKey(provider: ApiKeyProvider): string | undefined {\n\tif (typeof process === \"undefined\") return;\n\n\tconst candidates = [provider.key, ...(provider.env ?? [])].filter((name): name is string => Boolean(name));\n\tfor (const name of candidates) {\n\t\tconst value = process.env[name];\n\t\tif (value) return value;\n\t}\n}\n\nexport function formatThrownError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.stack || error.message || error.name;\n\t}\n\tif (typeof error === \"string\") {\n\t\treturn error;\n\t}\n\ttry {\n\t\treturn JSON.stringify(error);\n\t} catch {\n\t\treturn String(error);\n\t}\n}\n","import type { LanguageModel } from \"ai\";\nimport * as Model from \"../model/model.ts\";\nimport type { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { loadProviderFactory, packageForModel, resolveLanguageModel } from \"./registry.ts\";\nimport { getEnvApiKey, mergeHeaders } from \"./runtime.ts\";\n\nfunction cleanHeaders(headers: Record<string, string | null>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value !== null) result[key] = value;\n\t}\n\treturn result;\n}\n\nfunction resolveBaseURL(model: Model.Info, options: Options): string | undefined {\n\treturn (options.baseURL ?? model.api?.url ?? model.baseUrl) || undefined;\n}\n\nexport async function resolveAISDKLanguageModel(model: Model.Info, options: Options): Promise<LanguageModel> {\n\tconst npm = packageForModel(model);\n\tconst createProvider = await loadProviderFactory(npm);\n\tconst apiKey = options.apiKey ?? getEnvApiKey(model.provider);\n\tconst headers = cleanHeaders(mergeHeaders(model.headers, options.headers));\n\tconst baseURL = resolveBaseURL(model, options);\n\n\tconst factoryOptions: Record<string, unknown> = {\n\t\t...model.options,\n\t\t...options.factoryOptions,\n\t};\n\n\tif (apiKey) factoryOptions.apiKey = apiKey;\n\tif (Object.keys(headers).length > 0) factoryOptions.headers = headers;\n\tif (baseURL) factoryOptions.baseURL = baseURL;\n\n\tif (npm === \"@ai-sdk/openai-compatible\") {\n\t\tif (!baseURL) {\n\t\t\tthrow new Protocol.ProtocolAuthError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t\tmessage: \"AI SDK openai-compatible transport requires model.baseUrl, model.api.url, or options.baseURL\",\n\t\t\t});\n\t\t}\n\t\tfactoryOptions.name ??= model.provider.id;\n\t\tfactoryOptions.includeUsage ??= true;\n\t}\n\n\tif (npm === \"@codeworksh/ai-sdk-openai-codex\") {\n\t\t// Codex uses the session id for the session-id header and prompt cache key.\n\t\tconst cacheDisabled =\n\t\t\toptions.cacheRetention === \"none\" ||\n\t\t\t(typeof process !== \"undefined\" && process.env.CODEWORK_CACHE_RETENTION === \"none\");\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;\n\t\tfactoryOptions.compat ??= {\n\t\t\t...model.compat,\n\t\t\tsupportsImages: model.input.includes(\"image\"),\n\t\t};\n\t}\n\n\tconst provider = createProvider(factoryOptions);\n\treturn resolveLanguageModel(provider, model, options.method);\n}\n","/**\n * @description Helper function to parse partial jsons during LLM streaming.\n */\n\nimport { parse as partialParse } from \"partial-json\";\n\n/**\n * Attempts to parse potentially incomplete JSON during streaming.\n * Always returns a valid object, even if the JSON is incomplete.\n *\n * @param partialJson The partial JSON string from streaming\n * @returns Parsed object or empty object if parsing fails\n */\nexport function parseStreamingJson<T = any>(partialJson: string | undefined): T {\n\tif (!partialJson || partialJson.trim() === \"\") {\n\t\treturn {} as T;\n\t}\n\n\t// Try standard parsing first (fastest for complete JSON)\n\ttry {\n\t\treturn JSON.parse(partialJson) as T;\n\t} catch {\n\t\tconst repaired = repairInvalidJsonStringContent(partialJson);\n\t\tif (repaired !== partialJson) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(repaired) as T;\n\t\t\t} catch {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = partialParse(repaired);\n\t\t\t\t\treturn (result ?? {}) as T;\n\t\t\t\t} catch {\n\t\t\t\t\t// Fall through to the original partial parser.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Try partial-json for incomplete JSON\n\t\ttry {\n\t\t\tconst result = partialParse(partialJson);\n\t\t\treturn (result ?? {}) as T;\n\t\t} catch {\n\t\t\t// If all parsing fails, return empty object\n\t\t\treturn {} as T;\n\t\t}\n\t}\n}\n\nfunction repairInvalidJsonStringContent(input: string): string {\n\tlet output = \"\";\n\tlet inString = false;\n\tlet escaping = false;\n\n\tfor (const char of input) {\n\t\tif (!inString) {\n\t\t\toutput += char;\n\t\t\tif (char === '\"') inString = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (escaping) {\n\t\t\tif (`\"\\\\/bfnrtu`.includes(char)) {\n\t\t\t\toutput += `\\\\${char}`;\n\t\t\t} else {\n\t\t\t\toutput += `\\\\\\\\${char}`;\n\t\t\t}\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"\\\\\") {\n\t\t\tescaping = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinString = false;\n\t\t\toutput += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (char) {\n\t\t\tcase \"\\b\":\n\t\t\t\toutput += \"\\\\b\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\f\":\n\t\t\t\toutput += \"\\\\f\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\n\":\n\t\t\t\toutput += \"\\\\n\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\r\":\n\t\t\t\toutput += \"\\\\r\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\t\":\n\t\t\t\toutput += \"\\\\t\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += char;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (escaping) output += \"\\\\\\\\\";\n\treturn output;\n}\n","/**\n * Removes unpaired Unicode surrogate characters from a string.\n *\n * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,\n * or vice versa) cause JSON serialization errors in many API providers.\n *\n * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired\n * surrogates and will NOT be affected by this function.\n *\n * @param text - The text to sanitize\n * @returns The sanitized text with unpaired surrogates removed\n *\n * @example\n * // Valid emoji (properly paired surrogates) are preserved\n * sanitizeSurrogates(\"Hello 🙈 World\") // => \"Hello 🙈 World\"\n *\n * // Unpaired high surrogate is removed\n * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low\n * sanitizeSurrogates(`Text ${unpaired} here`) // => \"Text here\"\n */\nexport function sanitizeSurrogates(text: string): string {\n\t// Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate)\n\t// Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate)\n\treturn text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\");\n}\n","import {\n\tjsonSchema,\n\ttype AssistantModelMessage,\n\ttype FinishReason,\n\ttype LanguageModelUsage,\n\ttype ModelMessage,\n\ttype TextStreamPart,\n\ttype ToolModelMessage,\n\ttype ToolSet,\n\ttype UserModelMessage,\n} from \"ai\";\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { resolveOpenAICodexToolConstraint } from \"../providers/openai-codex/codex-tools.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/jsonparse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize.ts\";\n\ntype ToolCallPart = Extract<Message.AssistantMessage[\"parts\"][number], { type: \"toolCall\" }>;\ntype TerminalToolCall = Exclude<ToolCallPart, Message.ToolCallPendingPart | Message.ToolCallRunningPart>;\n\nexport function createAssistantMessage(model: Model.Info): Message.AssistantMessage {\n\treturn Message.createAssistantMessage({\n\t\trole: \"assistant\",\n\t\tparts: [],\n\t\tprotocol: model.protocol,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttime: {\n\t\t\tcreated: Date.now(),\n\t\t\tcompleted: Date.now(),\n\t\t},\n\t});\n}\n\nfunction userContent(parts: Message.UserMessage[\"parts\"], supportsImages: boolean): ModelMessage[] {\n\tconst content: Exclude<UserModelMessage[\"content\"], string> = [];\n\tfor (const part of parts) {\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length > 0) {\n\t\t\t\tcontent.push({ type: \"text\", text });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (supportsImages) {\n\t\t\tcontent.push({ type: \"file\", data: part.data, mediaType: part.mimeType });\n\t\t}\n\t}\n\n\tif (content.length === 0) return [];\n\treturn [{ role: \"user\", content }];\n}\n\nfunction sanitizeValue(value: unknown): unknown {\n\tif (typeof value === \"string\") return sanitizeSurrogates(value);\n\tif (Array.isArray(value)) return value.map((item) => sanitizeValue(item));\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, item] of Object.entries(value)) {\n\t\t\tresult[key] = sanitizeValue(item);\n\t\t}\n\t\treturn result;\n\t}\n\treturn value;\n}\n\nfunction sanitizeRecord(value: Record<string, unknown>): Record<string, unknown> {\n\treturn sanitizeValue(value) as Record<string, unknown>;\n}\n\nfunction toolResultOutput(toolCall: TerminalToolCall) {\n\tconst text = toolCall.result.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => sanitizeSurrogates(content.text))\n\t\t.join(\"\\n\");\n\tconst images = toolCall.result.content.filter((content) => content.type === \"image\");\n\n\tif (toolCall.result.isError) {\n\t\treturn {\n\t\t\ttype: \"error-text\" as const,\n\t\t\tvalue: text || \"Tool returned an error\",\n\t\t};\n\t}\n\n\tif (images.length === 0) {\n\t\treturn {\n\t\t\ttype: \"text\" as const,\n\t\t\tvalue: text,\n\t\t};\n\t}\n\n\treturn {\n\t\ttype: \"content\" as const,\n\t\tvalue: [\n\t\t\t...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n\t\t\t...images.map((image) => ({\n\t\t\t\ttype: \"file\" as const,\n\t\t\t\tdata: { type: \"data\" as const, data: image.data },\n\t\t\t\tmediaType: image.mimeType,\n\t\t\t})),\n\t\t],\n\t};\n}\n\nfunction normalizeOpenAICodexIdPart(value: string): string {\n\treturn value\n\t\t.replace(/[^a-zA-Z0-9_-]/g, \"_\")\n\t\t.slice(0, 64)\n\t\t.replace(/_+$/, \"\");\n}\n\nexport function normalizeOpenAICodexToolCallId(\n\tid: string,\n\tmodel: Model.Info,\n\tsource: Message.AssistantMessage,\n): string {\n\tif (!id.includes(\"|\")) return normalizeOpenAICodexIdPart(id);\n\tconst [callId, itemId = \"\"] = id.split(\"|\");\n\tconst normalizedCallId = normalizeOpenAICodexIdPart(callId ?? \"\");\n\tconst isForeignToolCall = source.provider.id !== model.provider.id || source.protocol !== model.protocol;\n\tlet normalizedItemId = isForeignToolCall ? `fc_${shortHash(itemId)}` : normalizeOpenAICodexIdPart(itemId);\n\tif (!normalizedItemId.startsWith(\"fc_\") && !normalizedItemId.startsWith(\"ctc_\")) {\n\t\tnormalizedItemId = normalizeOpenAICodexIdPart(`fc_${normalizedItemId}`);\n\t}\n\treturn `${normalizedCallId}|${normalizedItemId}`;\n}\n\nfunction assistantMessages(message: Message.AssistantMessage, model: Model.Info): ModelMessage[] {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") return [];\n\n\tconst assistantContent: Exclude<AssistantModelMessage[\"content\"], string> = [];\n\tconst toolResults: ToolModelMessage[\"content\"] = [];\n\n\tfor (const part of message.parts) {\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length === 0) continue;\n\t\t\tassistantContent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext,\n\t\t\t\t...(part.textSignature && message.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t? { providerOptions: { \"openai-codex\": { messageId: part.textSignature } } }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type === \"thinking\") {\n\t\t\tconst thinking = sanitizeSurrogates(part.thinking);\n\t\t\tif (thinking.trim().length === 0 && !part.thinkingSignature) continue;\n\t\t\tconst reasoning: Record<string, unknown> = { type: \"reasoning\", text: thinking };\n\t\t\t// Include the provider signature for faithful replay (e.g. Anthropic extended thinking).\n\t\t\tif (part.thinkingSignature) {\n\t\t\t\treasoning.providerOptions =\n\t\t\t\t\tmessage.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t\t? { \"openai-codex\": { reasoningItem: part.thinkingSignature } }\n\t\t\t\t\t\t: { anthropic: { signature: part.thinkingSignature } };\n\t\t\t}\n\t\t\tassistantContent.push(reasoning as (typeof assistantContent)[number]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type !== \"toolCall\") continue;\n\n\t\tconst codexToolMetadata: { namespace?: string; omitItemId?: boolean } = {};\n\t\tif (part.namespace && message.protocol === Model.KnownProviderEnum.openaiCodex) {\n\t\t\tcodexToolMetadata.namespace = part.namespace;\n\t\t}\n\t\tif (\n\t\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex &&\n\t\t\tmessage.protocol === model.protocol &&\n\t\t\tmessage.provider.id === model.provider.id &&\n\t\t\tmessage.model !== model.id\n\t\t) {\n\t\t\tcodexToolMetadata.omitItemId = true;\n\t\t}\n\t\tassistantContent.push({\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\tinput: sanitizeRecord(part.arguments ?? {}),\n\t\t\t...(Object.keys(codexToolMetadata).length > 0\n\t\t\t\t? { providerOptions: { \"openai-codex\": codexToolMetadata } }\n\t\t\t\t: {}),\n\t\t});\n\n\t\tconst terminal = part.status === \"pending\" || part.status === \"running\" ? undefined : part;\n\t\ttoolResults.push({\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\t...(terminal?.addedToolNames?.length\n\t\t\t\t? { providerOptions: { \"openai-codex\": { addedToolNames: terminal.addedToolNames } } }\n\t\t\t\t: {}),\n\t\t\toutput: terminal\n\t\t\t\t? toolResultOutput(terminal)\n\t\t\t\t: {\n\t\t\t\t\t\ttype: \"error-text\",\n\t\t\t\t\t\tvalue: \"No result provided\",\n\t\t\t\t\t},\n\t\t});\n\t}\n\n\tconst result: ModelMessage[] = [];\n\tif (assistantContent.length > 0) {\n\t\tresult.push({ role: \"assistant\", content: assistantContent });\n\t}\n\tif (toolResults.length > 0) {\n\t\tresult.push({ role: \"tool\", content: toolResults });\n\t}\n\treturn result;\n}\n\nexport function convertMessages(context: Message.Context, model: Model.Info): ModelMessage[] {\n\tconst messages: ModelMessage[] = [];\n\tconst transformedMessages = Message.transformMessages(\n\t\tcontext.messages,\n\t\tmodel,\n\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex ? normalizeOpenAICodexToolCallId : undefined,\n\t);\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tmessages.push(...userContent(msg.parts, model.input.includes(\"image\")));\n\t\t\tcontinue;\n\t\t}\n\t\tmessages.push(...assistantMessages(msg, model));\n\t}\n\n\treturn messages;\n}\n\nexport function convertTools(tools?: Message.Tool[], model?: Model.Info): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tconst constraint =\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t? resolveOpenAICodexToolConstraint(tool, model.compat)\n\t\t\t\t: undefined;\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(tool.parameters as any),\n\t\t\t...(constraint?.type === \"json_schema\" ? { strict: true } : {}),\n\t\t\t...(constraint?.type === \"grammar\" ? { providerOptions: { \"openai-codex\": { grammar: constraint } } } : {}),\n\t\t};\n\t}\n\treturn result;\n}\n\nexport function mapFinishReason(reason: FinishReason | undefined): Message.StopReason {\n\tswitch (reason) {\n\t\tcase \"length\":\n\t\t\treturn \"length\";\n\t\tcase \"tool-calls\":\n\t\t\treturn \"toolUse\";\n\t\tcase \"content-filter\":\n\t\tcase \"error\":\n\t\tcase \"other\":\n\t\t\treturn \"error\";\n\t\tcase \"stop\":\n\t\tdefault:\n\t\t\treturn \"stop\";\n\t}\n}\n\nexport function mapUsage(\n\tusage: LanguageModelUsage | undefined,\n\tmodel: Model.Info,\n\tcostMultiplier = 1,\n): Message.AssistantMessage[\"usage\"] {\n\tconst cacheRead = usage?.inputTokenDetails.cacheReadTokens ?? 0;\n\tconst cacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;\n\tconst input =\n\t\tusage?.inputTokenDetails?.noCacheTokens ?? Math.max((usage?.inputTokens ?? 0) - cacheRead - cacheWrite, 0);\n\tconst output = usage?.outputTokens ?? 0;\n\tconst totalTokens = usage?.totalTokens ?? input + cacheRead + cacheWrite + output;\n\tconst result: Message.AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\t...(usage?.outputTokenDetails?.reasoningTokens !== undefined\n\t\t\t? { reasoning: usage.outputTokenDetails.reasoningTokens }\n\t\t\t: {}),\n\t\ttotalTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, result);\n\tif (costMultiplier !== 1) {\n\t\tresult.cost.input *= costMultiplier;\n\t\tresult.cost.output *= costMultiplier;\n\t\tresult.cost.cacheRead *= costMultiplier;\n\t\tresult.cost.cacheWrite *= costMultiplier;\n\t\tresult.cost.total = result.cost.input + result.cost.output + result.cost.cacheRead + result.cost.cacheWrite;\n\t}\n\treturn result;\n}\n\nexport type StreamingToolCallBlock = Message.ToolCallPendingPart & {\n\tpartialJson?: string;\n};\n\nexport function toolCallFromPart(\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n): StreamingToolCallBlock {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tcallID: part.toolCallId,\n\t\tname: part.toolName,\n\t\targuments: typeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n}\n\nexport function updateToolCallFromInput(block: StreamingToolCallBlock, partialJson: string): void {\n\tblock.partialJson = partialJson;\n\tblock.arguments = parseStreamingJson<Record<string, unknown>>(partialJson);\n\tblock.time.end = Date.now();\n}\n","import { streamText, type TextStreamPart, type ToolSet } from \"ai\";\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport { compact } from \"../utils/helpers.ts\";\nimport { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { resolveAISDKLanguageModel } from \"./provider.ts\";\nimport { formatThrownError } from \"./runtime.ts\";\nimport { applyDefaultMaxTokens } from \"./shared.ts\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tcreateAssistantMessage,\n\tmapFinishReason,\n\tmapUsage,\n\ttoolCallFromPart,\n\tupdateToolCallFromInput,\n\ttype StreamingToolCallBlock,\n} from \"./transform.ts\";\n\ntype TextBlock = Message.TextContent & { streamId?: string };\ntype ThinkingBlock = Message.ThinkingContent & { streamId?: string };\n\ntype StreamBlock = TextBlock | ThinkingBlock | StreamingToolCallBlock;\ntype RuntimeOptions = Options & Protocol.CommonOptions;\ntype ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\n\nfunction providerOptionsKey(model: Model.Info): string {\n\treturn model.providerOptionsKey ?? model.protocol;\n}\n\nfunction mergeProviderOptions(...sources: Array<ProviderOptionBag | undefined>): ProviderOptionBag {\n\tconst result: ProviderOptionBag = {};\n\tfor (const source of sources) {\n\t\tif (!source) continue;\n\t\tfor (const [key, value] of Object.entries(source)) {\n\t\t\tif (!value) continue;\n\t\t\tresult[key] = {\n\t\t\t\t...result[key],\n\t\t\t\t...value,\n\t\t\t};\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction configuredCacheRetention(options: RuntimeOptions): \"none\" | \"short\" | \"long\" | undefined {\n\tif (options.cacheRetention) return options.cacheRetention;\n\tconst env = process.env.CODEWORK_CACHE_RETENTION;\n\tif (env === \"none\" || env === \"short\" || env === \"long\") return env;\n}\n\nfunction cacheProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\tconst retention = configuredCacheRetention(options);\n\tconst key = providerOptionsKey(model);\n\n\tif (retention === \"none\") return {};\n\n\tif (key === \"openai\") {\n\t\tconst openai: Record<string, unknown> = {};\n\t\tif (options.sessionId) openai.promptCacheKey = options.sessionId;\n\t\tif (retention === \"short\") openai.promptCacheRetention = \"in_memory\";\n\t\tif (retention === \"long\") openai.promptCacheRetention = \"24h\";\n\t\treturn Object.keys(openai).length > 0 ? { [key]: openai } : {};\n\t}\n\n\tif (key === \"openai-codex\" && options.sessionId) {\n\t\treturn { [key]: { promptCacheKey: options.sessionId } };\n\t}\n\n\tif ((key === \"anthropic\" || key === \"google-vertex-anthropic\") && retention) {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tcacheControl: {\n\t\t\t\t\ttype: \"ephemeral\",\n\t\t\t\t\t...(retention === \"long\" ? { ttl: \"1h\" } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\n// Default thinking budgets as a fraction of model.maxTokens, per level.\nconst DEFAULT_THINKING_BUDGET_FRACTIONS: Record<Model.ActiveThinkingLevel, number> = {\n\tminimal: 0.05,\n\tlow: 0.1,\n\tmedium: 0.25,\n\thigh: 0.5,\n\txhigh: 0.8,\n\tmax: 0.95,\n};\n\nconst MIN_THINKING_BUDGET = 1024;\n\nfunction resolveThinkingBudget(\n\tmodel: Model.Info,\n\toptions: RuntimeOptions,\n\tlevel: Model.ActiveThinkingLevel,\n): number | undefined {\n\t// Explicit budget from caller takes priority.\n\tconst explicit = options.thinkingBudgets?.[level];\n\tif (explicit !== undefined) return explicit;\n\n\t// Compute a sensible default so @ai-sdk/anthropic does not warn.\n\tconst key = providerOptionsKey(model);\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\tconst fraction = DEFAULT_THINKING_BUDGET_FRACTIONS[level];\n\t\treturn Math.max(Math.floor(model.maxTokens * fraction), MIN_THINKING_BUDGET);\n\t}\n\n\treturn undefined;\n}\n\nfunction reasoningProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\tconst requestedLevel = options.reasoning;\n\tif (!requestedLevel) return {};\n\n\tconst level = Model.clampThinkingLevel(model, requestedLevel);\n\tif (level === \"off\") return {};\n\n\tconst mapped = model.thinkingLevelMap?.[level] ?? level;\n\tif (!mapped) return {};\n\n\tconst key = providerOptionsKey(model);\n\tconst budget = resolveThinkingBudget(model, options, level);\n\n\tif (key === \"openai\" || key === \"xai\" || key === \"openai-codex\") {\n\t\treturn { [key]: { reasoningEffort: mapped } };\n\t}\n\n\tif (key === \"openrouter\") {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\treasoning: {\n\t\t\t\t\teffort: mapped === \"off\" ? \"none\" : mapped,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"google\" || key === \"google-vertex\") {\n\t\tconst thinkingLevel = mapped === \"xhigh\" ? \"high\" : mapped;\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinkingConfig: {\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\tincludeThoughts: true,\n\t\t\t\t\t...(budget !== undefined ? { thinkingBudget: budget } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinking: {\n\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\tbudgetTokens: budget ?? MIN_THINKING_BUDGET,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\nfunction resolveProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\treturn mergeProviderOptions(\n\t\tmodel.providerOptions as ProviderOptionBag | undefined,\n\t\tcacheProviderOptions(model, options),\n\t\treasoningProviderOptions(model, options),\n\t\toptions.providerOptions as ProviderOptionBag | undefined,\n\t);\n}\n\nfunction partIndex(output: Message.AssistantMessage, block: StreamBlock): number {\n\treturn output.parts.indexOf(block as Message.AssistantMessage[\"parts\"][number]);\n}\n\nfunction openAICodexMetadata(value: unknown): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst metadata = (value as Record<string, unknown>)[\"openai-codex\"];\n\treturn typeof metadata === \"object\" && metadata !== null && !Array.isArray(metadata)\n\t\t? (metadata as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction ensureTextBlock(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): TextBlock {\n\tconst existing = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: TextBlock = { type: \"text\", text: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"text.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n): ThinkingBlock {\n\tconst existing = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: ThinkingBlock = { type: \"thinking\", thinking: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"thinking.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureToolCallBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tname: string,\n\tstream: AssistantMessageEventStream,\n\temitStart: boolean,\n): StreamingToolCallBlock {\n\tconst existing = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (existing) {\n\t\tif (!existing.name && name) existing.name = name;\n\t\treturn existing;\n\t}\n\n\tconst block: StreamingToolCallBlock = {\n\t\ttype: \"toolCall\",\n\t\tcallID: id,\n\t\tname,\n\t\targuments: {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n\toutput.parts.push(block);\n\tif (emitStart) {\n\t\tstream.push({ type: \"toolcall.start\", partIndex: partIndex(output, block), partial: output });\n\t}\n\treturn block;\n}\n\nfunction finishTextBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\ttextSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (textSignature) block.textSignature = textSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"text.end\", partIndex: index, content: block.text, partial: output });\n}\n\nfunction finishThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\tthinkingSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (thinkingSignature) block.thinkingSignature = thinkingSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"thinking.end\", partIndex: index, content: block.thinking, partial: output });\n}\n\nfunction finishToolInput(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): void {\n\tconst block = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (!block) return;\n\tconst index = partIndex(output, block);\n\tdelete block.partialJson;\n\tstream.push({ type: \"toolcall.end\", partIndex: index, toolCall: block, partial: output });\n}\n\nfunction finalizeToolCall(\n\toutput: Message.AssistantMessage,\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst existing = output.parts.find((item) => item.type === \"toolCall\" && item.callID === part.toolCallId) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tconst block = existing ?? toolCallFromPart(part);\n\tblock.callID = part.toolCallId;\n\tblock.name = part.toolName;\n\tblock.arguments =\n\t\ttypeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {};\n\tconst namespace = openAICodexMetadata(part.providerMetadata)?.namespace;\n\tif (typeof namespace === \"string\") block.namespace = namespace;\n\tblock.time.end = Date.now();\n\tdelete block.partialJson;\n\n\tif (!existing) {\n\t\toutput.parts.push(block);\n\t}\n\n\tconst index = partIndex(output, block);\n\tstream.push({ type: \"toolcall.final\", partIndex: index, toolCall: block, partial: output });\n}\n\nfunction handlePart(\n\tpart: TextStreamPart<ToolSet>,\n\toutput: Message.AssistantMessage,\n\tmodel: Model.Info,\n\tstream: AssistantMessageEventStream,\n\tcostMultiplier: number,\n): void {\n\tswitch (part.type) {\n\t\tcase \"text-start\":\n\t\t\tensureTextBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"text-delta\": {\n\t\t\tconst block = ensureTextBlock(output, part.id, stream);\n\t\t\tblock.text += part.text;\n\t\t\tstream.push({ type: \"text.delta\", partIndex: partIndex(output, block), delta: part.text, partial: output });\n\t\t\tbreak;\n\t\t}\n\t\tcase \"text-end\": {\n\t\t\tconst messageId = openAICodexMetadata(part.providerMetadata)?.messageId;\n\t\t\tfinishTextBlock(output, part.id, stream, typeof messageId === \"string\" ? messageId : undefined);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-start\":\n\t\t\tensureThinkingBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"reasoning-delta\": {\n\t\t\tconst block = ensureThinkingBlock(output, part.id, stream);\n\t\t\tblock.thinking += part.text;\n\t\t\t// Capture the provider thinking signature for faithful multi-turn replay.\n\t\t\t// @ai-sdk/anthropic emits it as a reasoning-delta with empty text and providerMetadata.\n\t\t\tconst sig =\n\t\t\t\t(part.providerMetadata?.anthropic as Record<string, unknown> | undefined)?.signature ??\n\t\t\t\t(part.providerMetadata?.[\"google-vertex-anthropic\"] as Record<string, unknown> | undefined)?.signature;\n\t\t\tif (typeof sig === \"string\") block.thinkingSignature = sig;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-end\": {\n\t\t\tconst reasoningItem = openAICodexMetadata(part.providerMetadata)?.reasoningItem;\n\t\t\tfinishThinkingBlock(output, part.id, stream, typeof reasoningItem === \"string\" ? reasoningItem : undefined);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-start\":\n\t\t\tensureToolCallBlock(output, part.id, part.toolName, stream, true);\n\t\t\tbreak;\n\t\tcase \"tool-input-delta\": {\n\t\t\tconst block = ensureToolCallBlock(output, part.id, \"\", stream, true);\n\t\t\tconst partialJson = (block.partialJson ?? \"\") + part.delta;\n\t\t\tupdateToolCallFromInput(block, partialJson);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-end\":\n\t\t\tfinishToolInput(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"tool-call\":\n\t\t\tfinalizeToolCall(output, part, stream);\n\t\t\tbreak;\n\t\tcase \"finish-step\":\n\t\t\toutput.responseId ||= part.response.id;\n\t\t\tif (part.response.modelId && part.response.modelId !== model.id)\n\t\t\t\toutput.responseModel ||= part.response.modelId;\n\t\t\toutput.usage = mapUsage(part.usage, model, costMultiplier);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"finish\":\n\t\t\toutput.usage = mapUsage(part.totalUsage, model, costMultiplier);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"abort\":\n\t\t\toutput.stopReason = \"aborted\";\n\t\t\tif (part.reason !== undefined) output.errorMessage = part.reason;\n\t\t\tbreak;\n\t\tcase \"error\":\n\t\t\tthrow part.error instanceof Error ? part.error : new Error(formatThrownError(part.error));\n\t}\n}\n\nfunction resolveCostMultiplier(model: Model.Info, options: RuntimeOptions, providerOptions: ProviderOptionBag): number {\n\tif (providerOptionsKey(model) !== \"openai-codex\") return 1;\n\tconst providerTier = providerOptions[\"openai-codex\"]?.serviceTier;\n\tconst factoryTier = options.factoryOptions?.serviceTier;\n\tconst modelTier = model.options?.serviceTier;\n\tconst serviceTier = providerTier ?? factoryTier ?? modelTier;\n\tif (serviceTier === \"flex\") return 0.5;\n\tif (serviceTier === \"priority\") return model.id === \"gpt-5.5\" ? 2.5 : 2;\n\treturn 1;\n}\n\n/**\n * Resolve maxOutputTokens so that (maxOutputTokens + thinkingBudget) does not exceed model.maxTokens.\n * Without this adjustment @ai-sdk/anthropic logs a warning and silently caps the value.\n */\nfunction resolveMaxOutputTokens(\n\tmodel: Model.Info,\n\toptions: RuntimeOptions,\n\tproviderOptions: Record<string, unknown> | undefined,\n): number | undefined {\n\tconst maxTokens = options.maxTokens;\n\tif (maxTokens === undefined) return undefined;\n\n\tconst key = providerOptionsKey(model);\n\t// The ChatGPT Codex backend rejects max_output_tokens, so never send it.\n\tif (key === \"openai-codex\") return undefined;\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\tconst thinkingConfig = providerOptions?.[key] as Record<string, unknown> | undefined;\n\t\tconst thinking = thinkingConfig?.thinking as { budgetTokens?: number } | undefined;\n\t\tconst budgetTokens = thinking?.budgetTokens ?? 0;\n\t\tif (budgetTokens > 0 && maxTokens + budgetTokens > model.maxTokens) {\n\t\t\treturn Math.max(model.maxTokens - budgetTokens, 1);\n\t\t}\n\t}\n\n\treturn maxTokens;\n}\n\nexport const stream: Protocol.StreamFunction<Model.KnownProviderEnum, typeof Options> = (model, context, options) => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst runtimeOptions = applyDefaultMaxTokens(model, (options ?? {}) as RuntimeOptions);\n\n\tvoid (async () => {\n\t\tconst output = createAssistantMessage(model);\n\t\ttry {\n\t\t\tconst languageModel = await resolveAISDKLanguageModel(model, runtimeOptions);\n\t\t\tconst tools = convertTools(context.tools, model);\n\t\t\tconst messages = convertMessages(context, model);\n\t\t\tconst providerOptions = resolveProviderOptions(model, runtimeOptions) as Parameters<\n\t\t\t\ttypeof streamText<ToolSet>\n\t\t\t>[0][\"providerOptions\"];\n\t\t\tconst costMultiplier = resolveCostMultiplier(model, runtimeOptions, providerOptions as ProviderOptionBag);\n\t\t\tconst activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = compact({\n\t\t\t\tmodel: languageModel,\n\t\t\t\tsystem: context.systemPrompt,\n\t\t\t\tmessages,\n\t\t\t\ttools,\n\t\t\t\ttoolChoice: runtimeOptions.toolChoice as Parameters<typeof streamText<ToolSet>>[0][\"toolChoice\"],\n\t\t\t\tactiveTools,\n\t\t\t\tmaxOutputTokens: resolveMaxOutputTokens(model, runtimeOptions, providerOptions),\n\t\t\t\ttemperature: runtimeOptions.temperature,\n\t\t\t\tproviderOptions,\n\t\t\t\tabortSignal: runtimeOptions.signal,\n\t\t\t\ttimeout: runtimeOptions.timeoutMs,\n\t\t\t\tmaxRetries: runtimeOptions.maxRetries,\n\t\t\t\theaders: runtimeOptions.headers,\n\t\t\t});\n\n\t\t\tconst payload = await runtimeOptions.onPayload?.(params, model);\n\t\t\tif (payload !== undefined) {\n\t\t\t\tparams = payload as Parameters<typeof streamText<ToolSet>>[0];\n\t\t\t}\n\n\t\t\tconst result = streamText(params);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tfor await (const part of result.fullStream) {\n\t\t\t\thandlePart(part, output, model, stream, costMultiplier);\n\t\t\t}\n\n\t\t\tif (runtimeOptions.signal?.aborted || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Provider returned an error stop reason\");\n\t\t\t}\n\n\t\t\toutput.time.completed = Date.now();\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.parts) {\n\t\t\t\tdelete (block as TextBlock).streamId;\n\t\t\t\tdelete (block as ThinkingBlock).streamId;\n\t\t\t\tdelete (block as StreamingToolCallBlock).partialJson;\n\t\t\t}\n\t\t\toutput.time.completed = Date.now();\n\t\t\toutput.stopReason = runtimeOptions.signal?.aborted || output.stopReason === \"aborted\" ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatThrownError(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n","import * as Model from \"../model/model.ts\";\nimport { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { stream } from \"./stream.ts\";\n\nexport { Options } from \"./options.ts\";\nexport * from \"./registry.ts\";\nexport { stream } from \"./stream.ts\";\nexport * from \"./transform.ts\";\n\nexport function createAISDKProtocol(\n\tprotocol: Model.KnownProviderEnum,\n): Protocol.Protocol<Model.KnownProviderEnum, typeof Options> {\n\treturn {\n\t\tprotocol,\n\t\tstream,\n\t};\n}\n\nexport function registerAISDKProtocols(): void {\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.anthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.google));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertexAnthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openai));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCompatible));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCodex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openrouter));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));\n}\n","import { registerAISDKProtocols } from \"./index.ts\";\n\nregisterAISDKProtocols();\n","import \"./llm/register.ts\";\n\nimport type * as Message from \"./message/message.ts\";\nimport type * as Model from \"./model/model.ts\";\nimport * as Protocol from \"./llm/protocol.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream.ts\";\n\n/**\n * Stream assistant responses for a model and context.\n *\n * Example:\n *\n * ```ts\n * const s = stream(model, context, {\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * });\n *\n * for await (const event of s) {\n * if (event.type === \"text.delta\") {\n * process.stdout.write(event.delta);\n * }\n * }\n *\n * const message = await s.result();\n * ```\n *\n * This export also includes convenience helpers:\n *\n * ```ts\n * const message = await stream.complete(model, context, options);\n * ```\n */\ntype StreamCallable = {\n\t<TProtocol extends Protocol.ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: Protocol.OptionsFor<TProtocol>,\n\t): AssistantMessageEventStream;\n\tcomplete: typeof Protocol.complete;\n\tresolveProtocolProvider: typeof Protocol.resolveProtocolProvider;\n};\n\nconst streamImpl = <TProtocol extends Protocol.ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: Protocol.OptionsFor<TProtocol>,\n): AssistantMessageEventStream => Protocol.stream(model, context, options);\n\n/**\n * Start a streaming assistant response for a model/context pair.\n *\n * This is the main streaming entrypoint.\n * Attached helpers:\n *\n * - `stream.complete(...)` resolves the final assistant message without manually iterating events.\n * - `stream.resolveProtocolProvider(...)` exposes protocol resolution for advanced integrations.\n */\nexport const stream = Object.assign(streamImpl, {\n\tcomplete: Protocol.complete,\n\tresolveProtocolProvider: Protocol.resolveProtocolProvider,\n}) as StreamCallable;\n\n/** Resolve a streamed response directly to the final assistant message. */\nexport const complete = Protocol.complete;\n","/**\n * @description Validation powered by TypeBox's built-in schema compiler.\n */\n\nimport type { Static, TSchema } from \"typebox\";\nimport Schema from \"typebox/schema\";\nimport Value from \"typebox/value\";\n\nimport type * as Message from \"../message/message.ts\";\n\nconst validators = new WeakMap<TSchema, ReturnType<typeof Schema.Compile>>();\n\nfunction getValidator<T extends TSchema>(schema: T): ReturnType<typeof Schema.Compile<T>> {\n\tconst existing = validators.get(schema) as ReturnType<typeof Schema.Compile<T>> | undefined;\n\tif (existing) return existing;\n\n\tconst validator = Schema.Compile(schema);\n\tvalidators.set(schema, validator);\n\treturn validator;\n}\n\nfunction errorPath(error: { instancePath?: string; params?: Record<string, unknown> }): string {\n\tif (error.instancePath) return error.instancePath.substring(1);\n\n\tconst requiredProperties = error.params?.requiredProperties;\n\tif (Array.isArray(requiredProperties)) return requiredProperties.join(\", \");\n\n\treturn \"root\";\n}\n\n/**\n * Validates an arbitrary value against a TypeBox schema and returns the coerced value.\n */\nexport function validateSchema<T extends TSchema>(schema: T, value: unknown, label: string): Static<T> {\n\tconst validator = getValidator(schema);\n\tconst input = Value.Convert(schema, structuredClone(value));\n\n\ttry {\n\t\treturn validator.Parse(input);\n\t} catch {\n\t\tconst [_result, validationErrors] = validator.Errors(input);\n\t\tconst errors =\n\t\t\tvalidationErrors\n\t\t\t\t.map((err) => {\n\t\t\t\t\treturn ` - ${errorPath(err)}: ${err.message}`;\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\") || \"Unknown Validation Error\";\n\n\t\tthrow new Error(\n\t\t\t[\n\t\t\t\t`Validation Failed For ${label}`,\n\t\t\t\t`${errors}\\n`,\n\t\t\t\t\"Received Value:\",\n\t\t\t\t`${JSON.stringify(value, null, 2)}\\n`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n */\nexport function validateToolCall<T extends Message.Tool>(\n\ttools: T[],\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\tconst tool = tools.find((t) => t.name === toolExecution.name);\n\tif (!tool) {\n\t\tthrow new Error(`Tool \"${toolExecution.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolExecution);\n}\n\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n */\nexport function validateToolArguments<T extends Message.Tool>(\n\ttool: T,\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\treturn validateSchema(\n\t\ttool.parameters,\n\t\ttoolExecution.rawArgs,\n\t\t`Tool \"${toolExecution.name}\"`,\n\t) as Message.ToolArguments<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAa,oBAAoBA,OAAK,OAAO;CAC5C,MAAMA,OAAK,QAAQ,MAAM;CACzB,MAAMA,OAAK,OAAO;CAClB,eAAeA,OAAK,SAASA,OAAK,OAAO,CAAC;AAC3C,CAAC;AAGD,MAAa,qBAAqBA,OAAK,OAAO;CAC7C,MAAMA,OAAK,QAAQ,OAAO;CAC1B,MAAMA,OAAK,OAAO;CAClB,UAAUA,OAAK,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AM,aAAa,UAAU,CAAC;CAE7D,MAAM,qBAAqB,MAAM,QAAQ;CACzC,IAAI,MAAM,QAAQ,kBAAkB,GAAG,OAAO,mBAAmB,KAAK,IAAI;CAE1E,OAAO;AACR;;;;AAKA,SAAgB,eAAkC,QAAW,OAAgB,OAA0B;CACtG,MAAM,YAAY,aAAa,MAAM;CACrC,MAAM,QAAQ,MAAM,QAAQ,QAAQ,gBAAgB,KAAK,CAAC;CAE1D,IAAI;EACH,OAAO,UAAU,MAAM,KAAK;CAC7B,QAAQ;EACP,MAAM,CAAC,SAAS,oBAAoB,UAAU,OAAO,KAAK;EAC1D,MAAM,SACL,iBACE,KAAK,QAAQ;GACb,OAAO,MAAM,UAAU,GAAG,EAAE,IAAI,IAAI;EACrC,CAAC,CAAC,CACD,KAAK,IAAI,KAAK;EAEjB,MAAM,IAAI,MACT;GACC,yBAAyB;GACzB,GAAG,OAAO;GACV;GACA,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE;EACnC,CAAC,CAAC,KAAK,IAAI,CACZ;CACD;AACD;;;;AAKA,SAAgB,iBACf,OACA,eAC2B;CAC3B,MAAM,OAAO,MAAM,MAAM,MAAM,EAAE,SAAS,cAAc,IAAI;CAC5D,IAAI,CAAC,MACJ,MAAM,IAAI,MAAM,SAAS,cAAc,KAAK,YAAY;CAEzD,OAAO,sBAAsB,MAAM,aAAa;AACjD;;;;AAKA,SAAgB,sBACf,MACA,eAC2B;CAC3B,OAAO,eACN,KAAK,YACL,cAAc,SACd,SAAS,cAAc,KAAK,EAC7B;AACD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["Type","Model.KnownProviderEnumSchema","Model.ProviderInfo","createAssistantMessage","Type","Message.AssistantMessageSchema","Message.ToolCallSchema","Message.TextContentSchema","Message.ImageContentSchema","Message.ThinkingContentSchema","Message.UserMessageSchema","Message.ToolCallPendingPartSchema","Message.ToolCallRunningPartSchema","Message.ToolCallTerminalPartSchema","Message.MessageSchema","Model.getModel","Model.getModels","Model.getProviders","Model.registry","Model.modelsAreEqual","Type","Model.KnownProviderEnumSchema","stream","Type","Type","Model.APIMethodEnumSchema","Model.ActiveThinkingLevel","Protocol.ProtocolAuthError","partialParse","Message.createAssistantMessage","Message.transformMessages","Model.clampThinkingLevel","stream","Protocol.stream","Protocol.complete","Protocol.resolveProtocolProvider"],"sources":["../../src/message/message.ts","../../src/event/event.ts","../../src/llm.ts","../../src/llm/protocol.ts","../../src/llm/shared.ts","../../src/llm/options.ts","../../src/utils/eventstream.ts","../../src/utils/helpers.ts","../../src/llm/runtime.ts","../../src/llm/provider.ts","../../src/utils/jsonparse.ts","../../src/utils/sanitize.ts","../../src/llm/transform.ts","../../src/llm/stream.ts","../../src/llm/index.ts","../../src/llm/register.ts","../../src/stream.ts","../../src/utils/validation.ts"],"sourcesContent":["import Type, { type Static, type TSchema } from \"typebox\";\nimport { uuidv7 } from \"uuidv7\";\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\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\tusage: UsageSchema,\n\tstopReason: StopReasonSchema,\n\terrorMessage: Type.Optional(Type.String()),\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\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\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\n\tconst transformed: Message[] = [];\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\ttransformed.push(msg);\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\" && isUnresolvedToolCall(block)) {\n\t\t\t\treturn syntheticSkippedToolCall(block);\n\t\t\t}\n\t\t\treturn block;\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, { type Static } from \"typebox\";\nimport * as Message from \"../message/message.ts\";\n\n// TODO @sanchitrk:\n// for delta events we can have metadata KV that a provider can use for internal state\n// similar to index what anthropic does\nexport const LLMMessageEventType = {\n\tstart: \"start\",\n\n\ttextStart: \"text.start\",\n\ttextDelta: \"text.delta\",\n\ttextEnd: \"text.end\",\n\n\tthinkingStart: \"thinking.start\",\n\tthinkingDelta: \"thinking.delta\",\n\tthinkingEnd: \"thinking.end\",\n\n\ttoolcallStart: \"toolcall.start\",\n\ttoolcallDelta: \"toolcall.delta\",\n\ttoolcallEnd: \"toolcall.end\",\n\ttoolcallFinal: \"toolcall.final\",\n\n\tdone: \"done\",\n\terror: \"error\",\n} as const;\nexport type LLMMessageEventType = (typeof LLMMessageEventType)[keyof typeof LLMMessageEventType];\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Streams should emit `start` before partial updates, then terminate with either:\n * - `done` carrying the final successful AssistantMessage, or\n * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n * and errorMessage.\n */\nexport const LLMMessageEventSchema = Type.Union([\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.start),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.textEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.thinkingEnd),\n\t\tpartIndex: Type.Number(),\n\t\tcontent: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallStart),\n\t\tpartIndex: Type.Number(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallDelta),\n\t\tpartIndex: Type.Number(),\n\t\tdelta: Type.String(),\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallEnd),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.toolcallFinal),\n\t\tpartIndex: Type.Number(),\n\t\ttoolCall: Message.ToolCallSchema,\n\t\tpartial: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.done),\n\t\treason: Type.Union([Type.Literal(\"stop\"), Type.Literal(\"length\"), Type.Literal(\"toolUse\")]),\n\t\tmessage: Message.AssistantMessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(LLMMessageEventType.error),\n\t\treason: Type.Union([Type.Literal(\"aborted\"), Type.Literal(\"error\")]),\n\t\terror: Message.AssistantMessageSchema,\n\t}),\n]);\nexport type LLMMessageEvent = Static<typeof LLMMessageEventSchema>;\n\nexport const AgentEventType = {\n\t// Agent lifecycle\n\tagentStart: \"agent.start\",\n\tagentEnd: \"agent.end\",\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\tturnStart: \"turn.start\",\n\tturnEnd: \"turn.end\",\n\t// Message lifecycle - emitted for user, assistant message and corresponding parts\n\tmessageStart: \"message.start\",\n\n\tmessagePartStart: \"message.part.start\",\n\tmessagePartUpdate: \"message.part.update\",\n\tmessagePartEnd: \"message.part.end\",\n\n\tmessageUpdate: \"message.update\",\n\tmessageEnd: \"message.end\",\n\t// Tool execution lifecycle\n\ttoolExecutionStart: \"tool.execution.start\",\n\ttoolExecutionUpdate: \"tool.execution.update\",\n\ttoolExecutionEnd: \"tool.execution.end\",\n} as const;\nexport type AgentEventType = (typeof AgentEventType)[keyof typeof AgentEventType];\n\n//\n// message parts\nconst UserMessagePart = Type.Union([Message.TextContentSchema, Message.ImageContentSchema]);\nconst AssistantMessagePart = Type.Union([\n\tMessage.TextContentSchema,\n\tMessage.ImageContentSchema,\n\tMessage.ThinkingContentSchema,\n\tMessage.ToolCallSchema,\n]);\n\n//\n// user message part\n// part start\nconst UserMessagePartStart = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartStart),\n\tmessage: Message.UserMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: UserMessagePart,\n});\n// part end\nconst UserMessagePartEnd = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\tmessage: Message.UserMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: UserMessagePart,\n});\n\n//\n// assistant message part\n// part start\nconst AssistantMessagePartStart = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartStart),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n});\n// part update llm\nconst AssistantMessagePartLLMUpdate = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n\tsource: Type.Literal(\"llm\"),\n});\n// part update tool\nconst AssistantMessagePartToolUpdate = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n\tsource: Type.Literal(\"tool\"),\n});\n// part end\nconst AssistantMessagePartEnd = Type.Object({\n\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\tmessage: Message.AssistantMessageSchema,\n\tpartIndex: Type.Number(),\n\tpart: AssistantMessagePart,\n});\n\n//\n// tool exection\nconst ToolExecutionStartSchema = Type.Object({\n\ttype: Type.Literal(AgentEventType.toolExecutionStart),\n\tmessageId: Type.String(),\n\tpartIndex: Type.Number(),\n\ttoolCall: Message.ToolCallPendingPartSchema,\n});\nexport type ToolExecutionStart = Static<typeof ToolExecutionStartSchema>;\n\nconst ToolExecutionUpdateSchema = Type.Object({\n\ttype: Type.Literal(AgentEventType.toolExecutionUpdate),\n\tmessageId: Type.String(),\n\tpartIndex: Type.Number(),\n\ttoolCall: Message.ToolCallRunningPartSchema,\n});\nexport type ToolExecutionUpdate = Static<typeof ToolExecutionUpdateSchema>;\n\nconst ToolExecutionEndSchema = Type.Object({\n\ttype: Type.Literal(AgentEventType.toolExecutionEnd),\n\tmessageId: Type.String(),\n\tpartIndex: Type.Number(),\n\ttoolCall: Message.ToolCallTerminalPartSchema,\n});\nexport type ToolExecutionEnd = Static<typeof ToolExecutionEndSchema>;\n\n/**\n * Events emitted by the Agent lifecycle\n * These events provide fine-grained lifecycle information for messages, turns, and tool execution.\n */\nexport const AgentEventSchema = Type.Union([\n\t//\n\t// Agent lifecycle\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.agentStart),\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.agentEnd),\n\t\tmessages: Type.Array(Message.MessageSchema),\n\t}),\n\t//\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.turnStart),\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.turnEnd),\n\t\tmessage: Message.AssistantMessageSchema,\n\t}),\n\t//\n\t// Message lifecycle - emitted for user, assistant and corresponding parts\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.messageStart),\n\t\tmessage: Message.MessageSchema,\n\t}),\n\t// user message parts lifecycle\n\tType.Union([UserMessagePartStart, UserMessagePartEnd]),\n\t//\n\t// assistant message parts lifecycle\n\tType.Union([\n\t\tAssistantMessagePartStart,\n\t\tAssistantMessagePartLLMUpdate,\n\t\tAssistantMessagePartToolUpdate,\n\t\tAssistantMessagePartEnd,\n\t]),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.messageUpdate),\n\t\tmessage: Message.MessageSchema,\n\t}),\n\tType.Object({\n\t\ttype: Type.Literal(AgentEventType.messageEnd),\n\t\tmessage: Message.MessageSchema,\n\t}),\n\t//\n\t// Tool execution lifecycle\n\tToolExecutionStartSchema,\n\tToolExecutionUpdateSchema,\n\tToolExecutionEndSchema,\n]);\nexport type AgentEvent = Static<typeof AgentEventSchema>;\n","import * as Model from \"./model/model.ts\";\n\ntype LLM = {\n\t<TProvider extends string, TProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>>(\n\t\tprovider: TProvider,\n\t\tmodel: string,\n\t\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n\t): Promise<Model.TModel<TProtocol> | undefined>;\n\tmodel: typeof Model.getModel;\n\tmodels: typeof Model.getModels;\n\tproviders: typeof Model.getProviders;\n\tregistry: typeof Model.registry;\n\tmodelsAreEqual: typeof Model.modelsAreEqual;\n};\n\nconst llmImpl = async <\n\tTProvider extends string,\n\tTProtocol extends Model.KnownProviderEnum = Model.ProviderToProtocol<TProvider>,\n>(\n\tprovider: TProvider,\n\tmodel: string,\n\toverrides?: Partial<Model.Info> & { protocol?: TProtocol },\n): Promise<Model.TModel<TProtocol> | undefined> => Model.getModel(provider, model, overrides as any);\n\nexport const llm = Object.assign(llmImpl, {\n\tmodel: Model.getModel,\n\tmodels: Model.getModels,\n\tproviders: Model.getProviders,\n\tregistry: Model.registry,\n\tmodelsAreEqual: Model.modelsAreEqual,\n}) as LLM;\n","import { NamedError } from \"@codeworksh/utils\";\nimport type { Static, TSchema } from \"typebox\";\nimport Type from \"typebox\";\nimport type * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport type {\n\tAnthropicOptions,\n\tGoogleOptions,\n\tGoogleVertexAnthropicOptions,\n\tGoogleVertexOptions,\n\tOpenAICodexOptions,\n\tOpenAICompatibleOptions,\n\tOpenAIOptions,\n\tOpenRouterOptions,\n\tXaiOptions,\n} from \"./options.ts\";\nimport type { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\nexport const ProviderProtocolNotFoundError = NamedError.create(\n\t\"ProviderProtocolNotFoundError\",\n\tType.Object({\n\t\tprotocol: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProviderProtocolNotFoundError = InstanceType<typeof ProviderProtocolNotFoundError>;\n\nexport const ProtocolMismatchError = NamedError.create(\n\t\"ProtocolMismatchError\",\n\tType.Object({\n\t\tactual: Model.KnownProviderEnumSchema,\n\t\texpected: Model.KnownProviderEnumSchema,\n\t}),\n);\nexport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\nexport const ProtocolAuthError = NamedError.create(\n\t\"ProtocolAuthError\",\n\tType.Object({\n\t\tmessage: Type.String(),\n\t\tprotocol: Type.String(),\n\t}),\n);\nexport type ProtocolAuthError = InstanceType<typeof ProtocolAuthError>;\n\nexport type CommonOptions = SharedOptions & {\n\treasoning?: Model.ActiveThinkingLevel;\n\tthinkingBudgets?: ThinkingBudgets;\n};\nexport interface OptionsByProtocol {\n\t[Model.KnownProviderEnum.openai]: OpenAIOptions;\n\t[Model.KnownProviderEnum.anthropic]: AnthropicOptions;\n\t[Model.KnownProviderEnum.google]: GoogleOptions;\n\t[Model.KnownProviderEnum.googleVertex]: GoogleVertexOptions;\n\t[Model.KnownProviderEnum.googleVertexAnthropic]: GoogleVertexAnthropicOptions;\n\t[Model.KnownProviderEnum.openaiCompatible]: OpenAICompatibleOptions;\n\t[Model.KnownProviderEnum.openaiCodex]: OpenAICodexOptions;\n\t[Model.KnownProviderEnum.openrouter]: OpenRouterOptions;\n\t[Model.KnownProviderEnum.xai]: XaiOptions;\n}\nexport type ProtocolWithOptions = keyof OptionsByProtocol & Model.KnownProviderEnum;\nexport type OptionsFor<TProtocol extends ProtocolWithOptions> = OptionsByProtocol[TProtocol];\n\nexport type StreamFunction<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: Static<S>) => AssistantMessageEventStream;\n\nexport type ProtocolStreamFunction<S extends TSchema = TSchema> = (\n\tmodel: Model.Info,\n\tcontext: Message.Context,\n\toptions?: Static<S>,\n) => AssistantMessageEventStream;\n\nexport interface Protocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: StreamFunction<TProtocol, S>;\n}\n\nexport interface RegisteredProtocol<\n\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\tS extends TSchema = TSchema,\n> {\n\tprotocol: TProtocol;\n\tstream: ProtocolStreamFunction<S>;\n}\n\ntype AnyRegisteredProtocol = RegisteredProtocol<Model.KnownProviderEnum, TSchema>;\n\ntype RegistryEntry = {\n\tprovider: AnyRegisteredProtocol;\n\tsourceId?: string;\n};\n\nconst protocolRegistry = new Map<Model.KnownProviderEnum, RegistryEntry>();\n\nfunction wrapStream<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprotocol: TProtocol,\n\tstream: StreamFunction<TProtocol, S>,\n): ProtocolStreamFunction<S> {\n\treturn (model, context, options) => {\n\t\tif (model.protocol !== protocol) {\n\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\tactual: model.protocol,\n\t\t\t\texpected: protocol,\n\t\t\t});\n\t\t}\n\n\t\treturn stream(model as Model.TModel<TProtocol>, context, options);\n\t};\n}\n\nexport function registerProtocolProvider<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\tprovider: Protocol<TProtocol, S>,\n\tsourceId?: string,\n): void {\n\tconst registered: RegisteredProtocol<TProtocol, S> = {\n\t\tprotocol: provider.protocol,\n\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t};\n\n\tprotocolRegistry.set(provider.protocol, {\n\t\tprovider: registered as AnyRegisteredProtocol,\n\t\t...(sourceId !== undefined && { sourceId }),\n\t});\n}\n\nexport function getProtocolProvider(protocol: Model.KnownProviderEnum): AnyRegisteredProtocol | undefined {\n\treturn protocolRegistry.get(protocol)?.provider;\n}\n\nexport function resolveProtocolProvider(model: Model.Info): AnyRegisteredProtocol {\n\tconst provider = getProtocolProvider(model.protocol);\n\tif (!provider) {\n\t\tthrow new ProviderProtocolNotFoundError({\n\t\t\tprotocol: model.protocol,\n\t\t});\n\t}\n\n\treturn provider;\n}\n\nexport function getProtocolProviders(): AnyRegisteredProtocol[] {\n\treturn Array.from(protocolRegistry.values(), (entry) => entry.provider);\n}\n\nexport function stream<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): AssistantMessageEventStream {\n\tconst provider = resolveProtocolProvider(model);\n\treturn provider.stream(model, context, options);\n}\n\nexport async function complete<TProtocol extends ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: OptionsFor<TProtocol>,\n): Promise<Message.AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function unregisterProtocolProviders(sourceId: string): void {\n\tfor (const [protocol, entry] of protocolRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tprotocolRegistry.delete(protocol);\n\t\t}\n\t}\n}\n\nexport function clearProtocolProviders(): void {\n\tprotocolRegistry.clear();\n}\n","import { Type, type Static } from \"typebox\";\nimport type * as Model from \"../model/model.ts\";\n\nexport const CacheRetention = Type.Union([Type.Literal(\"none\"), Type.Literal(\"short\"), Type.Literal(\"long\")]);\nexport type CacheRetention = Static<typeof CacheRetention>;\n\nexport const GenerationOptions = Type.Object({\n\tmaxTokens: Type.Optional(Type.Number()),\n\ttemperature: Type.Optional(Type.Number()),\n\tcacheRetention: Type.Optional(CacheRetention),\n});\n\nexport const HelperOptions = Type.Object({\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tsessionId: Type.Optional(Type.String()),\n\tapiKey: Type.Optional(Type.String()),\n\ttimeoutMs: Type.Optional(Type.Number()),\n\tmaxRetries: Type.Optional(Type.Number()),\n\tsignal: Type.Optional(Type.Unsafe<AbortSignal>({})),\n\tonPayload: Type.Optional(\n\t\tType.Unsafe<(payload: unknown, model: Model.TModel<Model.KnownProviderEnum>) => Promise<unknown>>({}),\n\t),\n\tmetadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n});\n\nexport const ThinkingBudgets = Type.Object({\n\tminimal: Type.Optional(Type.Number()),\n\tlow: Type.Optional(Type.Number()),\n\tmedium: Type.Optional(Type.Number()),\n\thigh: Type.Optional(Type.Number()),\n\txhigh: Type.Optional(Type.Number()),\n\tmax: Type.Optional(Type.Number()),\n});\nexport type ThinkingBudgets = Static<typeof ThinkingBudgets>;\n\nexport const SharedOptions = Type.Evaluate(Type.Intersect([GenerationOptions, HelperOptions]));\nexport type SharedOptions = Static<typeof SharedOptions>;\n\nconst DEFAULT_MAX_OUTPUT_TOKENS = 32000;\nconst CONTEXT_WINDOW_OUTPUT_TOLERANCE = 1024;\n\nexport function applyDefaultMaxTokens<TOptions extends SharedOptions = SharedOptions>(\n\tmodel: Model.TModel<Model.KnownProviderEnum>,\n\toptions?: TOptions,\n): TOptions & Pick<SharedOptions, \"maxTokens\"> {\n\tconst defaultMaxTokens =\n\t\tmodel.maxTokens > 0\n\t\t\t? model.maxTokens >= model.contextWindow - CONTEXT_WINDOW_OUTPUT_TOLERANCE\n\t\t\t\t? Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS)\n\t\t\t\t: model.maxTokens\n\t\t\t: undefined;\n\n\treturn {\n\t\t...options,\n\t\tmaxTokens: options?.maxTokens ?? defaultMaxTokens,\n\t} as TOptions & Pick<SharedOptions, \"maxTokens\">;\n}\n","import type { AnthropicLanguageModelOptions, AnthropicProviderSettings } from \"@ai-sdk/anthropic\";\nimport type { GoogleGenerativeAIProviderSettings, GoogleLanguageModelOptions } from \"@ai-sdk/google\";\nimport type { GoogleVertexProviderSettings } from \"@ai-sdk/google-vertex\";\nimport type { GoogleVertexAnthropicProviderSettings } from \"@ai-sdk/google-vertex/anthropic\";\nimport type {\n\tOpenAILanguageModelChatOptions,\n\tOpenAILanguageModelCompletionOptions,\n\tOpenAILanguageModelResponsesOptions,\n\tOpenAIProviderSettings,\n} from \"@ai-sdk/openai\";\nimport type {\n\tOpenAICompatibleLanguageModelChatOptions,\n\tOpenAICompatibleLanguageModelCompletionOptions,\n\tOpenAICompatibleProviderSettings,\n} from \"@ai-sdk/openai-compatible\";\nimport type { XaiLanguageModelChatOptions, XaiLanguageModelResponsesOptions, XaiProviderSettings } from \"@ai-sdk/xai\";\nimport type { OpenRouterProviderOptions, OpenRouterProviderSettings } from \"@openrouter/ai-sdk-provider\";\nimport type { OpenAICodexLanguageModelOptions, OpenAICodexProviderSettings } from \"../providers/openai-codex/index.ts\";\nimport { Type, type Static } from \"typebox\";\nimport * as Model from \"../model/model.ts\";\nimport type * as Protocol from \"./protocol.ts\";\nimport { SharedOptions, ThinkingBudgets } from \"./shared.ts\";\n\nexport const Options = Type.Evaluate(\n\tType.Intersect([\n\t\tSharedOptions,\n\t\tType.Object({\n\t\t\tbaseURL: Type.Optional(Type.String()),\n\t\t\tmethod: Type.Optional(Model.APIMethodEnumSchema),\n\t\t\tmodelId: Type.Optional(Type.String()),\n\t\t\treasoning: Type.Optional(Model.ActiveThinkingLevel),\n\t\t\tthinkingBudgets: Type.Optional(ThinkingBudgets),\n\t\t\ttoolChoice: Type.Optional(Type.Any()),\n\t\t\tactiveTools: Type.Optional(Type.Array(Type.String())),\n\t\t\tfactoryOptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\t\t\tproviderOptions: Type.Optional(Type.Record(Type.String(), Type.Record(Type.String(), Type.Unknown()))),\n\t\t}),\n\t]),\n);\n\ntype ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\n\nexport type AISDKOptions<\n\tTFactoryOptions,\n\tTProviderOptions extends ProviderOptionBag = ProviderOptionBag,\n> = Protocol.CommonOptions & {\n\tbaseURL?: string;\n\tmethod?: Model.APIMethodEnum;\n\tmodelId?: string;\n\ttoolChoice?: unknown;\n\tactiveTools?: string[];\n\tfactoryOptions?: Partial<TFactoryOptions> & Record<string, unknown>;\n\tproviderOptions?: TProviderOptions & ProviderOptionBag;\n};\n\ntype OpenAILanguageOptions =\n\t| OpenAILanguageModelResponsesOptions\n\t| OpenAILanguageModelChatOptions\n\t| OpenAILanguageModelCompletionOptions;\ntype OpenAICompatibleLanguageOptions =\n\t| OpenAICompatibleLanguageModelChatOptions\n\t| OpenAICompatibleLanguageModelCompletionOptions;\ntype XaiLanguageOptions = XaiLanguageModelResponsesOptions | XaiLanguageModelChatOptions;\n\nexport type OpenAIOptions = AISDKOptions<OpenAIProviderSettings, { openai?: OpenAILanguageOptions }>;\nexport type AnthropicOptions = AISDKOptions<AnthropicProviderSettings, { anthropic?: AnthropicLanguageModelOptions }>;\nexport type GoogleOptions = AISDKOptions<GoogleGenerativeAIProviderSettings, { google?: GoogleLanguageModelOptions }>;\nexport type GoogleVertexOptions = AISDKOptions<GoogleVertexProviderSettings>;\nexport type GoogleVertexAnthropicOptions = AISDKOptions<GoogleVertexAnthropicProviderSettings>;\nexport type OpenAICompatibleOptions = AISDKOptions<\n\tOpenAICompatibleProviderSettings,\n\t{ \"openai-compatible\"?: OpenAICompatibleLanguageOptions }\n>;\nexport type OpenAICodexOptions = AISDKOptions<\n\tOpenAICodexProviderSettings,\n\t{ \"openai-codex\"?: OpenAICodexLanguageModelOptions }\n>;\nexport type OpenRouterOptions = AISDKOptions<OpenRouterProviderSettings, { openrouter?: OpenRouterProviderOptions }>;\nexport type XaiOptions = AISDKOptions<XaiProviderSettings, { xai?: XaiLanguageOptions }>;\n\nexport type Options = Static<typeof Options>;\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type * as Event from \"../event/event.ts\";\nimport type * as Message from \"../message/message.ts\";\n\n// Implements the async iterator pattern\n// LLM output are streams of events for consuming\n// This class helps with that by acting like buffer data structure to manage the streams\n// for producer and consumer\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate readonly finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\tprivate readonly isComplete: (event: T) => boolean;\n\tprivate readonly extractResult: (event: T) => R;\n\n\tconstructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R) {\n\t\tthis.isComplete = isComplete;\n\t\tthis.extractResult = extractResult;\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<Event.LLMMessageEvent, Message.AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n","import Type, { type TUnsafe } from \"typebox\";\n\n/**\n * `T` with every `undefined`-valued key turned into an optional key.\n */\ntype Compact<T> = {\n\t[K in keyof T as undefined extends T[K] ? never : K]: T[K];\n} & {\n\t[K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined>;\n};\n\n/**\n * Drops keys whose value is `undefined`.\n *\n * Under `exactOptionalPropertyTypes` an explicit `undefined` is not assignable to an optional\n * property, so a literal built from optional inputs has to omit the key rather than pass it\n * through. Only worth reaching for when a literal forwards many optional values at once — for a\n * handful of keys a conditional spread reads better.\n */\nexport function compact<T extends object>(value: T): Compact<T> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tif (entry !== undefined) result[key] = entry;\n\t}\n\treturn result as Compact<T>;\n}\n\n/**\n * Creates a string enum schema compatible with Google's API and other providers\n * that don't support anyOf/const patterns.\n *\n * @example\n * const OperationSchema = StringEnum([\"add\", \"subtract\", \"multiply\", \"divide\"], {\n * description: \"The operation to perform\"\n * });\n *\n * type Operation = Static<typeof OperationSchema>; // \"add\" | \"subtract\" | \"multiply\" | \"divide\"\n */\nexport function StringEnum<T extends readonly string[]>(\n\tvalues: T,\n\toptions?: { description?: string; default?: T[number] },\n): TUnsafe<T[number]> {\n\treturn Type.Unsafe<T[number]>({\n\t\ttype: \"string\",\n\t\tenum: values as any,\n\t\t...(options?.description && { description: options.description }),\n\t\t...(options?.default && { default: options.default }),\n\t});\n}\n","type ApiKeyProvider = {\n\tenv?: string[];\n\tkey?: string;\n};\n\nexport function mergeHeaders(\n\t...headerSources: (Record<string, string | null> | undefined)[]\n): Record<string, string | null> {\n\tconst merged: Record<string, string | null> = {};\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\treturn merged;\n}\n\nexport function getEnvApiKey(provider: ApiKeyProvider): string | undefined {\n\tif (typeof process === \"undefined\") return;\n\n\tconst candidates = [provider.key, ...(provider.env ?? [])].filter((name): name is string => Boolean(name));\n\tfor (const name of candidates) {\n\t\tconst value = process.env[name];\n\t\tif (value) return value;\n\t}\n}\n\nexport function formatThrownError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.stack || error.message || error.name;\n\t}\n\tif (typeof error === \"string\") {\n\t\treturn error;\n\t}\n\ttry {\n\t\treturn JSON.stringify(error);\n\t} catch {\n\t\treturn String(error);\n\t}\n}\n","import type { LanguageModel } from \"ai\";\nimport * as Model from \"../model/model.ts\";\nimport type { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { loadProviderFactory, packageForModel, resolveLanguageModel } from \"./registry.ts\";\nimport { getEnvApiKey, mergeHeaders } from \"./runtime.ts\";\n\nfunction cleanHeaders(headers: Record<string, string | null>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value !== null) result[key] = value;\n\t}\n\treturn result;\n}\n\nfunction resolveBaseURL(model: Model.Info, options: Options): string | undefined {\n\treturn (options.baseURL ?? model.api?.url ?? model.baseUrl) || undefined;\n}\n\nexport async function resolveAISDKLanguageModel(model: Model.Info, options: Options): Promise<LanguageModel> {\n\tconst npm = packageForModel(model);\n\tconst createProvider = await loadProviderFactory(npm);\n\tconst apiKey = options.apiKey ?? getEnvApiKey(model.provider);\n\tconst headers = cleanHeaders(mergeHeaders(model.headers, options.headers));\n\tconst baseURL = resolveBaseURL(model, options);\n\n\tconst factoryOptions: Record<string, unknown> = {\n\t\t...model.options,\n\t\t...options.factoryOptions,\n\t};\n\n\tif (apiKey) factoryOptions.apiKey = apiKey;\n\tif (Object.keys(headers).length > 0) factoryOptions.headers = headers;\n\tif (baseURL) factoryOptions.baseURL = baseURL;\n\n\tif (npm === \"@ai-sdk/openai-compatible\") {\n\t\tif (!baseURL) {\n\t\t\tthrow new Protocol.ProtocolAuthError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t\tmessage: \"AI SDK openai-compatible transport requires model.baseUrl, model.api.url, or options.baseURL\",\n\t\t\t});\n\t\t}\n\t\tfactoryOptions.name ??= model.provider.id;\n\t\tfactoryOptions.includeUsage ??= true;\n\t}\n\n\tif (npm === \"@codeworksh/ai-sdk-openai-codex\") {\n\t\t// Codex uses the session id for the session-id header and prompt cache key.\n\t\tconst cacheDisabled =\n\t\t\toptions.cacheRetention === \"none\" ||\n\t\t\t(typeof process !== \"undefined\" && process.env.CODEWORK_CACHE_RETENTION === \"none\");\n\t\tif (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;\n\t\tfactoryOptions.compat ??= {\n\t\t\t...model.compat,\n\t\t\tsupportsImages: model.input.includes(\"image\"),\n\t\t};\n\t}\n\n\tconst provider = createProvider(factoryOptions);\n\treturn resolveLanguageModel(provider, model, options.method);\n}\n","/**\n * @description Helper function to parse partial jsons during LLM streaming.\n */\n\nimport { parse as partialParse } from \"partial-json\";\n\n/**\n * Attempts to parse potentially incomplete JSON during streaming.\n * Always returns a valid object, even if the JSON is incomplete.\n *\n * @param partialJson The partial JSON string from streaming\n * @returns Parsed object or empty object if parsing fails\n */\nexport function parseStreamingJson<T = any>(partialJson: string | undefined): T {\n\tif (!partialJson || partialJson.trim() === \"\") {\n\t\treturn {} as T;\n\t}\n\n\t// Try standard parsing first (fastest for complete JSON)\n\ttry {\n\t\treturn JSON.parse(partialJson) as T;\n\t} catch {\n\t\tconst repaired = repairInvalidJsonStringContent(partialJson);\n\t\tif (repaired !== partialJson) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(repaired) as T;\n\t\t\t} catch {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = partialParse(repaired);\n\t\t\t\t\treturn (result ?? {}) as T;\n\t\t\t\t} catch {\n\t\t\t\t\t// Fall through to the original partial parser.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Try partial-json for incomplete JSON\n\t\ttry {\n\t\t\tconst result = partialParse(partialJson);\n\t\t\treturn (result ?? {}) as T;\n\t\t} catch {\n\t\t\t// If all parsing fails, return empty object\n\t\t\treturn {} as T;\n\t\t}\n\t}\n}\n\nfunction repairInvalidJsonStringContent(input: string): string {\n\tlet output = \"\";\n\tlet inString = false;\n\tlet escaping = false;\n\n\tfor (const char of input) {\n\t\tif (!inString) {\n\t\t\toutput += char;\n\t\t\tif (char === '\"') inString = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (escaping) {\n\t\t\tif (`\"\\\\/bfnrtu`.includes(char)) {\n\t\t\t\toutput += `\\\\${char}`;\n\t\t\t} else {\n\t\t\t\toutput += `\\\\\\\\${char}`;\n\t\t\t}\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"\\\\\") {\n\t\t\tescaping = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinString = false;\n\t\t\toutput += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (char) {\n\t\t\tcase \"\\b\":\n\t\t\t\toutput += \"\\\\b\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\f\":\n\t\t\t\toutput += \"\\\\f\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\n\":\n\t\t\t\toutput += \"\\\\n\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\r\":\n\t\t\t\toutput += \"\\\\r\";\n\t\t\t\tbreak;\n\t\t\tcase \"\\t\":\n\t\t\t\toutput += \"\\\\t\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += char;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (escaping) output += \"\\\\\\\\\";\n\treturn output;\n}\n","/**\n * Removes unpaired Unicode surrogate characters from a string.\n *\n * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,\n * or vice versa) cause JSON serialization errors in many API providers.\n *\n * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired\n * surrogates and will NOT be affected by this function.\n *\n * @param text - The text to sanitize\n * @returns The sanitized text with unpaired surrogates removed\n *\n * @example\n * // Valid emoji (properly paired surrogates) are preserved\n * sanitizeSurrogates(\"Hello 🙈 World\") // => \"Hello 🙈 World\"\n *\n * // Unpaired high surrogate is removed\n * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low\n * sanitizeSurrogates(`Text ${unpaired} here`) // => \"Text here\"\n */\nexport function sanitizeSurrogates(text: string): string {\n\t// Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate)\n\t// Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate)\n\treturn text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\");\n}\n","import {\n\tjsonSchema,\n\ttype AssistantModelMessage,\n\ttype FinishReason,\n\ttype LanguageModelUsage,\n\ttype ModelMessage,\n\ttype TextStreamPart,\n\ttype ToolModelMessage,\n\ttype ToolSet,\n\ttype UserModelMessage,\n} from \"ai\";\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { resolveOpenAICodexToolConstraint } from \"../providers/openai-codex/codex-tools.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/jsonparse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize.ts\";\n\ntype ToolCallPart = Extract<Message.AssistantMessage[\"parts\"][number], { type: \"toolCall\" }>;\ntype TerminalToolCall = Exclude<ToolCallPart, Message.ToolCallPendingPart | Message.ToolCallRunningPart>;\n\nexport function createAssistantMessage(model: Model.Info): Message.AssistantMessage {\n\treturn Message.createAssistantMessage({\n\t\trole: \"assistant\",\n\t\tparts: [],\n\t\tprotocol: model.protocol,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttime: {\n\t\t\tcreated: Date.now(),\n\t\t\tcompleted: Date.now(),\n\t\t},\n\t});\n}\n\nfunction userContent(parts: Message.UserMessage[\"parts\"], supportsImages: boolean): ModelMessage[] {\n\tconst content: Exclude<UserModelMessage[\"content\"], string> = [];\n\tfor (const part of parts) {\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length > 0) {\n\t\t\t\tcontent.push({ type: \"text\", text });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (supportsImages) {\n\t\t\tcontent.push({ type: \"file\", data: part.data, mediaType: part.mimeType });\n\t\t}\n\t}\n\n\tif (content.length === 0) return [];\n\treturn [{ role: \"user\", content }];\n}\n\nfunction sanitizeValue(value: unknown): unknown {\n\tif (typeof value === \"string\") return sanitizeSurrogates(value);\n\tif (Array.isArray(value)) return value.map((item) => sanitizeValue(item));\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, item] of Object.entries(value)) {\n\t\t\tresult[key] = sanitizeValue(item);\n\t\t}\n\t\treturn result;\n\t}\n\treturn value;\n}\n\nfunction sanitizeRecord(value: Record<string, unknown>): Record<string, unknown> {\n\treturn sanitizeValue(value) as Record<string, unknown>;\n}\n\nfunction toolResultOutput(toolCall: TerminalToolCall) {\n\tconst text = toolCall.result.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => sanitizeSurrogates(content.text))\n\t\t.join(\"\\n\");\n\tconst images = toolCall.result.content.filter((content) => content.type === \"image\");\n\n\tif (toolCall.result.isError) {\n\t\treturn {\n\t\t\ttype: \"error-text\" as const,\n\t\t\tvalue: text || \"Tool returned an error\",\n\t\t};\n\t}\n\n\tif (images.length === 0) {\n\t\treturn {\n\t\t\ttype: \"text\" as const,\n\t\t\tvalue: text,\n\t\t};\n\t}\n\n\treturn {\n\t\ttype: \"content\" as const,\n\t\tvalue: [\n\t\t\t...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n\t\t\t...images.map((image) => ({\n\t\t\t\ttype: \"file\" as const,\n\t\t\t\tdata: { type: \"data\" as const, data: image.data },\n\t\t\t\tmediaType: image.mimeType,\n\t\t\t})),\n\t\t],\n\t};\n}\n\nfunction normalizeOpenAICodexIdPart(value: string): string {\n\treturn value\n\t\t.replace(/[^a-zA-Z0-9_-]/g, \"_\")\n\t\t.slice(0, 64)\n\t\t.replace(/_+$/, \"\");\n}\n\nexport function normalizeOpenAICodexToolCallId(\n\tid: string,\n\tmodel: Model.Info,\n\tsource: Message.AssistantMessage,\n): string {\n\tif (!id.includes(\"|\")) return normalizeOpenAICodexIdPart(id);\n\tconst [callId, itemId = \"\"] = id.split(\"|\");\n\tconst normalizedCallId = normalizeOpenAICodexIdPart(callId ?? \"\");\n\tconst isForeignToolCall = source.provider.id !== model.provider.id || source.protocol !== model.protocol;\n\tlet normalizedItemId = isForeignToolCall ? `fc_${shortHash(itemId)}` : normalizeOpenAICodexIdPart(itemId);\n\tif (!normalizedItemId.startsWith(\"fc_\") && !normalizedItemId.startsWith(\"ctc_\")) {\n\t\tnormalizedItemId = normalizeOpenAICodexIdPart(`fc_${normalizedItemId}`);\n\t}\n\treturn `${normalizedCallId}|${normalizedItemId}`;\n}\n\ntype OpenAIReasoningMetadata = {\n\titemId: string;\n\treasoningEncryptedContent?: string | null;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function encodeOpenAIReasoningSignature(providerMetadata: unknown): string | undefined {\n\tif (!isRecord(providerMetadata)) return;\n\tconst metadata = providerMetadata.openai;\n\tif (!isRecord(metadata) || typeof metadata.itemId !== \"string\") return;\n\n\tconst signature: OpenAIReasoningMetadata = { itemId: metadata.itemId };\n\tif (typeof metadata.reasoningEncryptedContent === \"string\" || metadata.reasoningEncryptedContent === null) {\n\t\tsignature.reasoningEncryptedContent = metadata.reasoningEncryptedContent;\n\t}\n\treturn JSON.stringify(signature);\n}\n\nfunction decodeOpenAIReasoningSignature(signature: string): OpenAIReasoningMetadata {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(signature);\n\t\tif (isRecord(parsed) && typeof parsed.itemId === \"string\") {\n\t\t\treturn {\n\t\t\t\titemId: parsed.itemId,\n\t\t\t\t...(typeof parsed.reasoningEncryptedContent === \"string\" || parsed.reasoningEncryptedContent === null\n\t\t\t\t\t? { reasoningEncryptedContent: parsed.reasoningEncryptedContent }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// Older persisted messages may contain the item id directly.\n\t}\n\treturn { itemId: signature };\n}\n\nfunction assistantMessages(message: Message.AssistantMessage, model: Model.Info): ModelMessage[] {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") return [];\n\n\tconst assistantContent: Exclude<AssistantModelMessage[\"content\"], string> = [];\n\tconst toolResults: ToolModelMessage[\"content\"] = [];\n\n\tfor (const part of message.parts) {\n\t\tif (part.type === \"text\") {\n\t\t\tconst text = sanitizeSurrogates(part.text);\n\t\t\tif (text.trim().length === 0) continue;\n\t\t\tassistantContent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext,\n\t\t\t\t...(part.textSignature && message.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t? { providerOptions: { \"openai-codex\": { messageId: part.textSignature } } }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type === \"thinking\") {\n\t\t\tconst thinking = sanitizeSurrogates(part.thinking);\n\t\t\tif (thinking.trim().length === 0 && !part.thinkingSignature) continue;\n\t\t\tconst reasoning: Record<string, unknown> = { type: \"reasoning\", text: thinking };\n\t\t\t// OpenAI Responses only accepts native reasoning items. Older messages\n\t\t\t// without metadata would be skipped by the SDK with a warning anyway.\n\t\t\tif (message.protocol === Model.KnownProviderEnum.openai) {\n\t\t\t\tif (!part.thinkingSignature) continue;\n\t\t\t\treasoning.providerOptions = { openai: decodeOpenAIReasoningSignature(part.thinkingSignature) };\n\t\t\t} else if (part.thinkingSignature) {\n\t\t\t\treasoning.providerOptions =\n\t\t\t\t\tmessage.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t\t\t? { \"openai-codex\": { reasoningItem: part.thinkingSignature } }\n\t\t\t\t\t\t: { anthropic: { signature: part.thinkingSignature } };\n\t\t\t}\n\t\t\tassistantContent.push(reasoning as (typeof assistantContent)[number]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.type !== \"toolCall\") continue;\n\n\t\tconst codexToolMetadata: { namespace?: string; omitItemId?: boolean } = {};\n\t\tif (part.namespace && message.protocol === Model.KnownProviderEnum.openaiCodex) {\n\t\t\tcodexToolMetadata.namespace = part.namespace;\n\t\t}\n\t\tif (\n\t\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex &&\n\t\t\tmessage.protocol === model.protocol &&\n\t\t\tmessage.provider.id === model.provider.id &&\n\t\t\tmessage.model !== model.id\n\t\t) {\n\t\t\tcodexToolMetadata.omitItemId = true;\n\t\t}\n\t\tassistantContent.push({\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\tinput: sanitizeRecord(part.arguments ?? {}),\n\t\t\t...(Object.keys(codexToolMetadata).length > 0\n\t\t\t\t? { providerOptions: { \"openai-codex\": codexToolMetadata } }\n\t\t\t\t: {}),\n\t\t});\n\n\t\tconst terminal = part.status === \"pending\" || part.status === \"running\" ? undefined : part;\n\t\ttoolResults.push({\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: part.callID,\n\t\t\ttoolName: part.name,\n\t\t\t...(terminal?.addedToolNames?.length\n\t\t\t\t? { providerOptions: { \"openai-codex\": { addedToolNames: terminal.addedToolNames } } }\n\t\t\t\t: {}),\n\t\t\toutput: terminal\n\t\t\t\t? toolResultOutput(terminal)\n\t\t\t\t: {\n\t\t\t\t\t\ttype: \"error-text\",\n\t\t\t\t\t\tvalue: \"No result provided\",\n\t\t\t\t\t},\n\t\t});\n\t}\n\n\tconst result: ModelMessage[] = [];\n\tif (assistantContent.length > 0) {\n\t\tresult.push({ role: \"assistant\", content: assistantContent });\n\t}\n\tif (toolResults.length > 0) {\n\t\tresult.push({ role: \"tool\", content: toolResults });\n\t}\n\treturn result;\n}\n\nexport function convertMessages(context: Message.Context, model: Model.Info): ModelMessage[] {\n\tconst messages: ModelMessage[] = [];\n\tconst transformedMessages = Message.transformMessages(\n\t\tcontext.messages,\n\t\tmodel,\n\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex ? normalizeOpenAICodexToolCallId : undefined,\n\t);\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tmessages.push(...userContent(msg.parts, model.input.includes(\"image\")));\n\t\t\tcontinue;\n\t\t}\n\t\tmessages.push(...assistantMessages(msg, model));\n\t}\n\n\treturn messages;\n}\n\nexport function convertTools(tools?: Message.Tool[], model?: Model.Info): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tconst constraint =\n\t\t\tmodel?.protocol === Model.KnownProviderEnum.openaiCodex\n\t\t\t\t? resolveOpenAICodexToolConstraint(tool, model.compat)\n\t\t\t\t: undefined;\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(tool.parameters as any),\n\t\t\t...(constraint?.type === \"json_schema\" ? { strict: true } : {}),\n\t\t\t...(constraint?.type === \"grammar\" ? { providerOptions: { \"openai-codex\": { grammar: constraint } } } : {}),\n\t\t};\n\t}\n\treturn result;\n}\n\nexport function mapFinishReason(reason: FinishReason | undefined): Message.StopReason {\n\tswitch (reason) {\n\t\tcase \"length\":\n\t\t\treturn \"length\";\n\t\tcase \"tool-calls\":\n\t\t\treturn \"toolUse\";\n\t\tcase \"content-filter\":\n\t\tcase \"error\":\n\t\tcase \"other\":\n\t\t\treturn \"error\";\n\t\tcase \"stop\":\n\t\tdefault:\n\t\t\treturn \"stop\";\n\t}\n}\n\nexport function mapUsage(\n\tusage: LanguageModelUsage | undefined,\n\tmodel: Model.Info,\n\tcostMultiplier = 1,\n): Message.AssistantMessage[\"usage\"] {\n\tconst cacheRead = usage?.inputTokenDetails.cacheReadTokens ?? 0;\n\tconst cacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;\n\tconst input =\n\t\tusage?.inputTokenDetails?.noCacheTokens ?? Math.max((usage?.inputTokens ?? 0) - cacheRead - cacheWrite, 0);\n\tconst output = usage?.outputTokens ?? 0;\n\tconst totalTokens = usage?.totalTokens ?? input + cacheRead + cacheWrite + output;\n\tconst result: Message.AssistantMessage[\"usage\"] = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\t...(usage?.outputTokenDetails?.reasoningTokens !== undefined\n\t\t\t? { reasoning: usage.outputTokenDetails.reasoningTokens }\n\t\t\t: {}),\n\t\ttotalTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, result);\n\tif (costMultiplier !== 1) {\n\t\tresult.cost.input *= costMultiplier;\n\t\tresult.cost.output *= costMultiplier;\n\t\tresult.cost.cacheRead *= costMultiplier;\n\t\tresult.cost.cacheWrite *= costMultiplier;\n\t\tresult.cost.total = result.cost.input + result.cost.output + result.cost.cacheRead + result.cost.cacheWrite;\n\t}\n\treturn result;\n}\n\nexport type StreamingToolCallBlock = Message.ToolCallPendingPart & {\n\tpartialJson?: string;\n};\n\nexport function toolCallFromPart(\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n): StreamingToolCallBlock {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tcallID: part.toolCallId,\n\t\tname: part.toolName,\n\t\targuments: typeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n}\n\nexport function updateToolCallFromInput(block: StreamingToolCallBlock, partialJson: string): void {\n\tblock.partialJson = partialJson;\n\tblock.arguments = parseStreamingJson<Record<string, unknown>>(partialJson);\n\tblock.time.end = Date.now();\n}\n","import { streamText, type TextStreamPart, type ToolSet } from \"ai\";\nimport * as Message from \"../message/message.ts\";\nimport * as Model from \"../model/model.ts\";\nimport { AssistantMessageEventStream } from \"../utils/eventstream.ts\";\nimport { compact } from \"../utils/helpers.ts\";\nimport { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { resolveAISDKLanguageModel } from \"./provider.ts\";\nimport { formatThrownError } from \"./runtime.ts\";\nimport { applyDefaultMaxTokens } from \"./shared.ts\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tcreateAssistantMessage,\n\tencodeOpenAIReasoningSignature,\n\tmapFinishReason,\n\tmapUsage,\n\ttoolCallFromPart,\n\tupdateToolCallFromInput,\n\ttype StreamingToolCallBlock,\n} from \"./transform.ts\";\n\ntype TextBlock = Message.TextContent & { streamId?: string };\ntype ThinkingBlock = Message.ThinkingContent & { streamId?: string };\n\ntype StreamBlock = TextBlock | ThinkingBlock | StreamingToolCallBlock;\ntype RuntimeOptions = Options & Protocol.CommonOptions;\ntype ProviderOptionBag = Record<string, Record<string, unknown> | undefined>;\n\nfunction providerOptionsKey(model: Model.Info): string {\n\treturn model.providerOptionsKey ?? model.protocol;\n}\n\nfunction mergeProviderOptions(...sources: Array<ProviderOptionBag | undefined>): ProviderOptionBag {\n\tconst result: ProviderOptionBag = {};\n\tfor (const source of sources) {\n\t\tif (!source) continue;\n\t\tfor (const [key, value] of Object.entries(source)) {\n\t\t\tif (!value) continue;\n\t\t\tresult[key] = {\n\t\t\t\t...result[key],\n\t\t\t\t...value,\n\t\t\t};\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction configuredCacheRetention(options: RuntimeOptions): \"none\" | \"short\" | \"long\" | undefined {\n\tif (options.cacheRetention) return options.cacheRetention;\n\tconst env = process.env.CODEWORK_CACHE_RETENTION;\n\tif (env === \"none\" || env === \"short\" || env === \"long\") return env;\n}\n\nfunction cacheProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\tconst retention = configuredCacheRetention(options);\n\tconst key = providerOptionsKey(model);\n\n\tif (retention === \"none\") return {};\n\n\tif (key === \"openai\") {\n\t\tconst openai: Record<string, unknown> = {};\n\t\tif (options.sessionId) openai.promptCacheKey = options.sessionId;\n\t\tif (retention === \"short\") openai.promptCacheRetention = \"in_memory\";\n\t\tif (retention === \"long\") openai.promptCacheRetention = \"24h\";\n\t\treturn Object.keys(openai).length > 0 ? { [key]: openai } : {};\n\t}\n\n\tif (key === \"openai-codex\" && options.sessionId) {\n\t\treturn { [key]: { promptCacheKey: options.sessionId } };\n\t}\n\n\tif ((key === \"anthropic\" || key === \"google-vertex-anthropic\") && retention) {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tcacheControl: {\n\t\t\t\t\ttype: \"ephemeral\",\n\t\t\t\t\t...(retention === \"long\" ? { ttl: \"1h\" } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\n// Default thinking budgets as a fraction of model.maxTokens, per level.\nconst DEFAULT_THINKING_BUDGET_FRACTIONS: Record<Model.ActiveThinkingLevel, number> = {\n\tminimal: 0.05,\n\tlow: 0.1,\n\tmedium: 0.25,\n\thigh: 0.5,\n\txhigh: 0.8,\n\tmax: 0.95,\n};\n\nconst MIN_THINKING_BUDGET = 1024;\n\nfunction resolveThinkingBudget(\n\tmodel: Model.Info,\n\toptions: RuntimeOptions,\n\tlevel: Model.ActiveThinkingLevel,\n): number | undefined {\n\t// Explicit budget from caller takes priority.\n\tconst explicit = options.thinkingBudgets?.[level];\n\tif (explicit !== undefined) return explicit;\n\n\t// Compute a sensible default so @ai-sdk/anthropic does not warn.\n\tconst key = providerOptionsKey(model);\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\tconst fraction = DEFAULT_THINKING_BUDGET_FRACTIONS[level];\n\t\treturn Math.max(Math.floor(model.maxTokens * fraction), MIN_THINKING_BUDGET);\n\t}\n\n\treturn undefined;\n}\n\nfunction reasoningProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\tconst requestedLevel = options.reasoning;\n\tif (!requestedLevel) return {};\n\n\tconst level = Model.clampThinkingLevel(model, requestedLevel);\n\tif (level === \"off\") return {};\n\n\tconst mapped = model.thinkingLevelMap?.[level] ?? level;\n\tif (!mapped) return {};\n\n\tconst key = providerOptionsKey(model);\n\tconst budget = resolveThinkingBudget(model, options, level);\n\n\tif (key === \"openai\" || key === \"xai\" || key === \"openai-codex\") {\n\t\treturn { [key]: { reasoningEffort: mapped } };\n\t}\n\n\tif (key === \"openrouter\") {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\treasoning: {\n\t\t\t\t\teffort: mapped === \"off\" ? \"none\" : mapped,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"google\" || key === \"google-vertex\") {\n\t\tconst thinkingLevel = mapped === \"xhigh\" ? \"high\" : mapped;\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinkingConfig: {\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\tincludeThoughts: true,\n\t\t\t\t\t...(budget !== undefined ? { thinkingBudget: budget } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\treturn {\n\t\t\t[key]: {\n\t\t\t\tthinking: {\n\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\tbudgetTokens: budget ?? MIN_THINKING_BUDGET,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {};\n}\n\nfunction resolveProviderOptions(model: Model.Info, options: RuntimeOptions): ProviderOptionBag {\n\treturn mergeProviderOptions(\n\t\tmodel.providerOptions as ProviderOptionBag | undefined,\n\t\tcacheProviderOptions(model, options),\n\t\treasoningProviderOptions(model, options),\n\t\toptions.providerOptions as ProviderOptionBag | undefined,\n\t);\n}\n\nfunction partIndex(output: Message.AssistantMessage, block: StreamBlock): number {\n\treturn output.parts.indexOf(block as Message.AssistantMessage[\"parts\"][number]);\n}\n\nfunction openAICodexMetadata(value: unknown): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst metadata = (value as Record<string, unknown>)[\"openai-codex\"];\n\treturn typeof metadata === \"object\" && metadata !== null && !Array.isArray(metadata)\n\t\t? (metadata as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction ensureTextBlock(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): TextBlock {\n\tconst existing = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: TextBlock = { type: \"text\", text: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"text.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n): ThinkingBlock {\n\tconst existing = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (existing) return existing;\n\n\tconst block: ThinkingBlock = { type: \"thinking\", thinking: \"\", streamId: id };\n\toutput.parts.push(block);\n\tstream.push({ type: \"thinking.start\", partIndex: partIndex(output, block), partial: output });\n\treturn block;\n}\n\nfunction ensureToolCallBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tname: string,\n\tstream: AssistantMessageEventStream,\n\temitStart: boolean,\n): StreamingToolCallBlock {\n\tconst existing = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (existing) {\n\t\tif (!existing.name && name) existing.name = name;\n\t\treturn existing;\n\t}\n\n\tconst block: StreamingToolCallBlock = {\n\t\ttype: \"toolCall\",\n\t\tcallID: id,\n\t\tname,\n\t\targuments: {},\n\t\tstatus: \"pending\",\n\t\ttime: {\n\t\t\tstart: Date.now(),\n\t\t\tend: Date.now(),\n\t\t},\n\t};\n\toutput.parts.push(block);\n\tif (emitStart) {\n\t\tstream.push({ type: \"toolcall.start\", partIndex: partIndex(output, block), partial: output });\n\t}\n\treturn block;\n}\n\nfunction finishTextBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\ttextSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"text\" && (part as TextBlock).streamId === id) as\n\t\t| TextBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (textSignature) block.textSignature = textSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"text.end\", partIndex: index, content: block.text, partial: output });\n}\n\nfunction finishThinkingBlock(\n\toutput: Message.AssistantMessage,\n\tid: string,\n\tstream: AssistantMessageEventStream,\n\tthinkingSignature?: string,\n): void {\n\tconst block = output.parts.find((part) => part.type === \"thinking\" && (part as ThinkingBlock).streamId === id) as\n\t\t| ThinkingBlock\n\t\t| undefined;\n\tif (!block) return;\n\tif (thinkingSignature) block.thinkingSignature = thinkingSignature;\n\tconst index = partIndex(output, block);\n\tdelete (block as { streamId?: string }).streamId;\n\tstream.push({ type: \"thinking.end\", partIndex: index, content: block.thinking, partial: output });\n}\n\nfunction finishToolInput(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): void {\n\tconst block = output.parts.find((part) => part.type === \"toolCall\" && part.callID === id) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tif (!block) return;\n\tconst index = partIndex(output, block);\n\tdelete block.partialJson;\n\tstream.push({ type: \"toolcall.end\", partIndex: index, toolCall: block, partial: output });\n}\n\nfunction finalizeToolCall(\n\toutput: Message.AssistantMessage,\n\tpart: Extract<TextStreamPart<ToolSet>, { type: \"tool-call\" }>,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst existing = output.parts.find((item) => item.type === \"toolCall\" && item.callID === part.toolCallId) as\n\t\t| StreamingToolCallBlock\n\t\t| undefined;\n\tconst block = existing ?? toolCallFromPart(part);\n\tblock.callID = part.toolCallId;\n\tblock.name = part.toolName;\n\tblock.arguments =\n\t\ttypeof part.input === \"object\" && part.input !== null ? (part.input as Record<string, unknown>) : {};\n\tconst namespace = openAICodexMetadata(part.providerMetadata)?.namespace;\n\tif (typeof namespace === \"string\") block.namespace = namespace;\n\tblock.time.end = Date.now();\n\tdelete block.partialJson;\n\n\tif (!existing) {\n\t\toutput.parts.push(block);\n\t}\n\n\tconst index = partIndex(output, block);\n\tstream.push({ type: \"toolcall.final\", partIndex: index, toolCall: block, partial: output });\n}\n\nfunction handlePart(\n\tpart: TextStreamPart<ToolSet>,\n\toutput: Message.AssistantMessage,\n\tmodel: Model.Info,\n\tstream: AssistantMessageEventStream,\n\tcostMultiplier: number,\n): void {\n\tswitch (part.type) {\n\t\tcase \"text-start\":\n\t\t\tensureTextBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"text-delta\": {\n\t\t\tconst block = ensureTextBlock(output, part.id, stream);\n\t\t\tblock.text += part.text;\n\t\t\tstream.push({ type: \"text.delta\", partIndex: partIndex(output, block), delta: part.text, partial: output });\n\t\t\tbreak;\n\t\t}\n\t\tcase \"text-end\": {\n\t\t\tconst messageId = openAICodexMetadata(part.providerMetadata)?.messageId;\n\t\t\tfinishTextBlock(output, part.id, stream, typeof messageId === \"string\" ? messageId : undefined);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-start\":\n\t\t\tensureThinkingBlock(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"reasoning-delta\": {\n\t\t\tconst block = ensureThinkingBlock(output, part.id, stream);\n\t\t\tblock.thinking += part.text;\n\t\t\t// Capture the provider thinking signature for faithful multi-turn replay.\n\t\t\t// @ai-sdk/anthropic emits it as a reasoning-delta with empty text and providerMetadata.\n\t\t\tconst sig =\n\t\t\t\t(part.providerMetadata?.anthropic as Record<string, unknown> | undefined)?.signature ??\n\t\t\t\t(part.providerMetadata?.[\"google-vertex-anthropic\"] as Record<string, unknown> | undefined)?.signature;\n\t\t\tif (typeof sig === \"string\") block.thinkingSignature = sig;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reasoning-end\": {\n\t\t\tconst reasoningItem = openAICodexMetadata(part.providerMetadata)?.reasoningItem;\n\t\t\tconst openAISignature = encodeOpenAIReasoningSignature(part.providerMetadata);\n\t\t\tfinishThinkingBlock(\n\t\t\t\toutput,\n\t\t\t\tpart.id,\n\t\t\t\tstream,\n\t\t\t\ttypeof reasoningItem === \"string\" ? reasoningItem : openAISignature,\n\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-start\":\n\t\t\tensureToolCallBlock(output, part.id, part.toolName, stream, true);\n\t\t\tbreak;\n\t\tcase \"tool-input-delta\": {\n\t\t\tconst block = ensureToolCallBlock(output, part.id, \"\", stream, true);\n\t\t\tconst partialJson = (block.partialJson ?? \"\") + part.delta;\n\t\t\tupdateToolCallFromInput(block, partialJson);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall.delta\",\n\t\t\t\tpartIndex: partIndex(output, block),\n\t\t\t\tdelta: part.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-input-end\":\n\t\t\tfinishToolInput(output, part.id, stream);\n\t\t\tbreak;\n\t\tcase \"tool-call\":\n\t\t\tfinalizeToolCall(output, part, stream);\n\t\t\tbreak;\n\t\tcase \"finish-step\":\n\t\t\toutput.responseId ||= part.response.id;\n\t\t\tif (part.response.modelId && part.response.modelId !== model.id)\n\t\t\t\toutput.responseModel ||= part.response.modelId;\n\t\t\toutput.usage = mapUsage(part.usage, model, costMultiplier);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"finish\":\n\t\t\toutput.usage = mapUsage(part.totalUsage, model, costMultiplier);\n\t\t\toutput.stopReason = mapFinishReason(part.finishReason);\n\t\t\tbreak;\n\t\tcase \"abort\":\n\t\t\toutput.stopReason = \"aborted\";\n\t\t\tif (part.reason !== undefined) output.errorMessage = part.reason;\n\t\t\tbreak;\n\t\tcase \"error\":\n\t\t\tthrow part.error instanceof Error ? part.error : new Error(formatThrownError(part.error));\n\t}\n}\n\nfunction resolveCostMultiplier(model: Model.Info, options: RuntimeOptions, providerOptions: ProviderOptionBag): number {\n\tif (providerOptionsKey(model) !== \"openai-codex\") return 1;\n\tconst providerTier = providerOptions[\"openai-codex\"]?.serviceTier;\n\tconst factoryTier = options.factoryOptions?.serviceTier;\n\tconst modelTier = model.options?.serviceTier;\n\tconst serviceTier = providerTier ?? factoryTier ?? modelTier;\n\tif (serviceTier === \"flex\") return 0.5;\n\tif (serviceTier === \"priority\") return model.id === \"gpt-5.5\" ? 2.5 : 2;\n\treturn 1;\n}\n\n/**\n * Resolve maxOutputTokens so that (maxOutputTokens + thinkingBudget) does not exceed model.maxTokens.\n * Without this adjustment @ai-sdk/anthropic logs a warning and silently caps the value.\n */\nfunction resolveMaxOutputTokens(\n\tmodel: Model.Info,\n\toptions: RuntimeOptions,\n\tproviderOptions: Record<string, unknown> | undefined,\n): number | undefined {\n\tconst maxTokens = options.maxTokens;\n\tif (maxTokens === undefined) return undefined;\n\n\tconst key = providerOptionsKey(model);\n\t// The ChatGPT Codex backend rejects max_output_tokens, so never send it.\n\tif (key === \"openai-codex\") return undefined;\n\n\tif (key === \"anthropic\" || key === \"google-vertex-anthropic\") {\n\t\tconst thinkingConfig = providerOptions?.[key] as Record<string, unknown> | undefined;\n\t\tconst thinking = thinkingConfig?.thinking as { budgetTokens?: number } | undefined;\n\t\tconst budgetTokens = thinking?.budgetTokens ?? 0;\n\t\tif (budgetTokens > 0 && maxTokens + budgetTokens > model.maxTokens) {\n\t\t\treturn Math.max(model.maxTokens - budgetTokens, 1);\n\t\t}\n\t}\n\n\treturn maxTokens;\n}\n\nexport const stream: Protocol.StreamFunction<Model.KnownProviderEnum, typeof Options> = (model, context, options) => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst runtimeOptions = applyDefaultMaxTokens(model, (options ?? {}) as RuntimeOptions);\n\n\tvoid (async () => {\n\t\tconst output = createAssistantMessage(model);\n\t\ttry {\n\t\t\tconst languageModel = await resolveAISDKLanguageModel(model, runtimeOptions);\n\t\t\tconst tools = convertTools(context.tools, model);\n\t\t\tconst messages = convertMessages(context, model);\n\t\t\tconst providerOptions = resolveProviderOptions(model, runtimeOptions) as Parameters<\n\t\t\t\ttypeof streamText<ToolSet>\n\t\t\t>[0][\"providerOptions\"];\n\t\t\tconst costMultiplier = resolveCostMultiplier(model, runtimeOptions, providerOptions as ProviderOptionBag);\n\t\t\tconst activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = compact({\n\t\t\t\tmodel: languageModel,\n\t\t\t\tsystem: context.systemPrompt,\n\t\t\t\tmessages,\n\t\t\t\ttools,\n\t\t\t\ttoolChoice: runtimeOptions.toolChoice as Parameters<typeof streamText<ToolSet>>[0][\"toolChoice\"],\n\t\t\t\tactiveTools,\n\t\t\t\tmaxOutputTokens: resolveMaxOutputTokens(model, runtimeOptions, providerOptions),\n\t\t\t\ttemperature: runtimeOptions.temperature,\n\t\t\t\tproviderOptions,\n\t\t\t\tabortSignal: runtimeOptions.signal,\n\t\t\t\ttimeout: runtimeOptions.timeoutMs,\n\t\t\t\tmaxRetries: runtimeOptions.maxRetries,\n\t\t\t\theaders: runtimeOptions.headers,\n\t\t\t});\n\n\t\t\tconst payload = await runtimeOptions.onPayload?.(params, model);\n\t\t\tif (payload !== undefined) {\n\t\t\t\tparams = payload as Parameters<typeof streamText<ToolSet>>[0];\n\t\t\t}\n\n\t\t\tconst result = streamText(params);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tfor await (const part of result.fullStream) {\n\t\t\t\thandlePart(part, output, model, stream, costMultiplier);\n\t\t\t}\n\n\t\t\tif (runtimeOptions.signal?.aborted || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Request was aborted\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"Provider returned an error stop reason\");\n\t\t\t}\n\n\t\t\toutput.time.completed = Date.now();\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.parts) {\n\t\t\t\tdelete (block as TextBlock).streamId;\n\t\t\t\tdelete (block as ThinkingBlock).streamId;\n\t\t\t\tdelete (block as StreamingToolCallBlock).partialJson;\n\t\t\t}\n\t\t\toutput.time.completed = Date.now();\n\t\t\toutput.stopReason = runtimeOptions.signal?.aborted || output.stopReason === \"aborted\" ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatThrownError(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n","import * as Model from \"../model/model.ts\";\nimport { Options } from \"./options.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport { stream } from \"./stream.ts\";\n\nexport { Options } from \"./options.ts\";\nexport * from \"./registry.ts\";\nexport { stream } from \"./stream.ts\";\nexport * from \"./transform.ts\";\n\nexport function createAISDKProtocol(\n\tprotocol: Model.KnownProviderEnum,\n): Protocol.Protocol<Model.KnownProviderEnum, typeof Options> {\n\treturn {\n\t\tprotocol,\n\t\tstream,\n\t};\n}\n\nexport function registerAISDKProtocols(): void {\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.anthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.google));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertexAnthropic));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openai));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCompatible));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCodex));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openrouter));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));\n}\n","import { registerAISDKProtocols } from \"./index.ts\";\n\nregisterAISDKProtocols();\n","import \"./llm/register.ts\";\n\nimport type * as Message from \"./message/message.ts\";\nimport type * as Model from \"./model/model.ts\";\nimport * as Protocol from \"./llm/protocol.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream.ts\";\n\n/**\n * Stream assistant responses for a model and context.\n *\n * Example:\n *\n * ```ts\n * const s = stream(model, context, {\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * });\n *\n * for await (const event of s) {\n * if (event.type === \"text.delta\") {\n * process.stdout.write(event.delta);\n * }\n * }\n *\n * const message = await s.result();\n * ```\n *\n * This export also includes convenience helpers:\n *\n * ```ts\n * const message = await stream.complete(model, context, options);\n * ```\n */\ntype StreamCallable = {\n\t<TProtocol extends Protocol.ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: Protocol.OptionsFor<TProtocol>,\n\t): AssistantMessageEventStream;\n\tcomplete: typeof Protocol.complete;\n\tresolveProtocolProvider: typeof Protocol.resolveProtocolProvider;\n};\n\nconst streamImpl = <TProtocol extends Protocol.ProtocolWithOptions>(\n\tmodel: Model.TModel<TProtocol>,\n\tcontext: Message.Context,\n\toptions?: Protocol.OptionsFor<TProtocol>,\n): AssistantMessageEventStream => Protocol.stream(model, context, options);\n\n/**\n * Start a streaming assistant response for a model/context pair.\n *\n * This is the main streaming entrypoint.\n * Attached helpers:\n *\n * - `stream.complete(...)` resolves the final assistant message without manually iterating events.\n * - `stream.resolveProtocolProvider(...)` exposes protocol resolution for advanced integrations.\n */\nexport const stream = Object.assign(streamImpl, {\n\tcomplete: Protocol.complete,\n\tresolveProtocolProvider: Protocol.resolveProtocolProvider,\n}) as StreamCallable;\n\n/** Resolve a streamed response directly to the final assistant message. */\nexport const complete = Protocol.complete;\n","/**\n * @description Validation powered by TypeBox's built-in schema compiler.\n */\n\nimport type { Static, TSchema } from \"typebox\";\nimport Schema from \"typebox/schema\";\nimport Value from \"typebox/value\";\n\nimport type * as Message from \"../message/message.ts\";\n\nconst validators = new WeakMap<TSchema, ReturnType<typeof Schema.Compile>>();\n\nfunction getValidator<T extends TSchema>(schema: T): ReturnType<typeof Schema.Compile<T>> {\n\tconst existing = validators.get(schema) as ReturnType<typeof Schema.Compile<T>> | undefined;\n\tif (existing) return existing;\n\n\tconst validator = Schema.Compile(schema);\n\tvalidators.set(schema, validator);\n\treturn validator;\n}\n\nfunction errorPath(error: { instancePath?: string; params?: Record<string, unknown> }): string {\n\tif (error.instancePath) return error.instancePath.substring(1);\n\n\tconst requiredProperties = error.params?.requiredProperties;\n\tif (Array.isArray(requiredProperties)) return requiredProperties.join(\", \");\n\n\treturn \"root\";\n}\n\n/**\n * Validates an arbitrary value against a TypeBox schema and returns the coerced value.\n */\nexport function validateSchema<T extends TSchema>(schema: T, value: unknown, label: string): Static<T> {\n\tconst validator = getValidator(schema);\n\tconst input = Value.Convert(schema, structuredClone(value));\n\n\ttry {\n\t\treturn validator.Parse(input);\n\t} catch {\n\t\tconst [_result, validationErrors] = validator.Errors(input);\n\t\tconst errors =\n\t\t\tvalidationErrors\n\t\t\t\t.map((err) => {\n\t\t\t\t\treturn ` - ${errorPath(err)}: ${err.message}`;\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\") || \"Unknown Validation Error\";\n\n\t\tthrow new Error(\n\t\t\t[\n\t\t\t\t`Validation Failed For ${label}`,\n\t\t\t\t`${errors}\\n`,\n\t\t\t\t\"Received Value:\",\n\t\t\t\t`${JSON.stringify(value, null, 2)}\\n`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n */\nexport function validateToolCall<T extends Message.Tool>(\n\ttools: T[],\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\tconst tool = tools.find((t) => t.name === toolExecution.name);\n\tif (!tool) {\n\t\tthrow new Error(`Tool \"${toolExecution.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolExecution);\n}\n\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n */\nexport function validateToolArguments<T extends Message.Tool>(\n\ttool: T,\n\ttoolExecution: Message.ToolCallInFlight,\n): Message.ToolArguments<T> {\n\treturn validateSchema(\n\t\ttool.parameters,\n\t\ttoolExecution.rawArgs,\n\t\t`Tool \"${toolExecution.name}\"`,\n\t) as Message.ToolArguments<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAa,oBAAoBA,OAAK,OAAO;CAC5C,MAAMA,OAAK,QAAQ,MAAM;CACzB,MAAMA,OAAK,OAAO;CAClB,eAAeA,OAAK,SAASA,OAAK,OAAO,CAAC;AAC3C,CAAC;AAGD,MAAa,qBAAqBA,OAAK,OAAO;CAC7C,MAAMA,OAAK,QAAQ,OAAO;CAC1B,MAAMA,OAAK,OAAO;CAClB,UAAUA,OAAK,OAAO;AACvB,CAAC;AAGD,MAAa,wBAAwBA,OAAK,OAAO;CAChD,MAAMA,OAAK,QAAQ,UAAU;CAC7B,UAAUA,OAAK,OAAO;CAGtB,mBAAmBA,OAAK,SAASA,OAAK,OAAO,CAAC;;;;CAI9C,UAAUA,OAAK,SAASA,OAAK,QAAQ,CAAC;AACvC,CAAC;AAGD,MAAa,qBAAqBA,OAAK,OAAO;CAC7C,MAAMA,OAAK,QAAQ,UAAU;CAC7B,QAAQA,OA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