@codeworksh/aikit 0.4.1-dev.20260530184501 → 0.4.1-dev.20260530191957

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/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["Type","Type","Type","Type","Type","partialParse","stream"],"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/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 { Model } from \"../model/model\";\n\nexport namespace Message {\n\texport const TextContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"text\"),\n\t\ttext: Type.String(),\n\t\ttextSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the message ID\n\t});\n\texport type TextContent = Static<typeof TextContentSchema>;\n\n\texport const ImageContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"image\"),\n\t\tdata: Type.String(), // base64 encoded image data\n\t\tmimeType: Type.String(), // e.g., \"image/jpeg\", \"image/png\"\n\t});\n\texport type ImageContent = Static<typeof ImageContentSchema>;\n\n\texport const ThinkingContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"thinking\"),\n\t\tthinking: Type.String(),\n\t\tthinkingSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the reasoning item ID\n\t\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t\t * to the API for multi-turn continuity. */\n\t\tredacted: Type.Optional(Type.Boolean()),\n\t});\n\texport type ThinkingContent = Static<typeof ThinkingContentSchema>;\n\n\texport const ToolCallBaseSchema = Type.Object({\n\t\ttype: Type.Literal(\"toolCall\"),\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\targuments: Type.Record(Type.String(), Type.Any()),\n\t\tthoughtSignature: Type.Optional(Type.String()), // Google-specific: opaque signature for reusing thought context\n\t\ttime: Type.Object({\n\t\t\tstart: Type.Number(), // Unix timestamp in milliseconds\n\t\t\tend: Type.Number(), // Unix timestamp in milliseconds, last known lifecycle update\n\t\t}),\n\t});\n\n\texport const ToolSuccessResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(false),\n\t});\n\texport const ToolErrorResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(true),\n\t});\n\texport const ToolRunningPartial = Type.Object({\n\t\tcontent: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),\n\t\tdetails: Type.Optional(Type.Any()),\n\t});\n\n\texport const ToolStatusEnum = {\n\t\tpending: \"pending\",\n\t\trunning: \"running\",\n\t\tcompleted: \"completed\",\n\t\terror: \"error\",\n\t\tskipped: \"skipped\",\n\t\taborted: \"aborted\",\n\t} as const;\n\n\texport const ToolRunningSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.running),\n\t\tpartial: Type.Optional(ToolRunningPartial),\n\t});\n\texport const ToolCompletedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.completed),\n\t\tresult: ToolSuccessResult,\n\t});\n\texport const ToolErrorSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.error),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolSkippedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.skipped),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolAbortedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.aborted),\n\t\tresult: ToolErrorResult,\n\t});\n\n\tconst ToolCallPendingPart = Type.Intersect([\n\t\tToolCallBaseSchema,\n\t\tType.Object({\n\t\t\tstatus: Type.Literal(ToolStatusEnum.pending),\n\t\t}),\n\t]);\n\tconst ToolCallRunningPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolRunningSchema]));\n\tconst ToolCallCompletedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));\n\tconst ToolCallErrorPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolErrorSchema]));\n\tconst ToolCallSkippedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));\n\tconst ToolCallAbortedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));\n\n\texport const ToolCallInFlightSchema = Type.Object({\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\trawArgs: Type.Record(Type.String(), Type.Unknown()),\n\t\targs: Type.Optional(Type.Unknown()),\n\t});\n\texport type ToolCallInFlight = Static<typeof ToolCallInFlightSchema>;\n\n\texport const ToolCallSchema = Type.Union([\n\t\tToolCallPendingPart,\n\t\tToolCallRunningPart,\n\t\tToolCallCompletedPart,\n\t\tToolCallErrorPart,\n\t\tToolCallSkippedPart,\n\t\tToolCallAbortedPart,\n\t]);\n\n\texport type ToolCall = Static<typeof ToolCallSchema>;\n\texport type ToolCallPendingPart = Static<typeof ToolCallPendingPart>;\n\texport type ToolCallRunningPart = Static<typeof ToolCallRunningPart>;\n\texport type ToolCallCompletedPart = Static<typeof ToolCallCompletedPart>;\n\texport type ToolCallErrorPart = Static<typeof ToolCallErrorPart>;\n\n\texport const UsageSchema = Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t\ttotalTokens: Type.Number(),\n\t\tcost: Type.Object({\n\t\t\tinput: Type.Number(),\n\t\t\toutput: Type.Number(),\n\t\t\tcacheRead: Type.Number(),\n\t\t\tcacheWrite: Type.Number(),\n\t\t\ttotal: Type.Number(),\n\t\t}),\n\t});\n\texport type Usage = Static<typeof UsageSchema>;\n\n\texport const StopReasonSchema = Type.Union([\n\t\tType.Literal(\"stop\"),\n\t\tType.Literal(\"length\"),\n\t\tType.Literal(\"toolUse\"),\n\t\tType.Literal(\"error\"),\n\t\tType.Literal(\"aborted\"),\n\t]);\n\texport type StopReason = Static<typeof StopReasonSchema>;\n\n\texport const UserMessageSchema = Type.Object({\n\t\tmessageId: Type.String(),\n\t\trole: Type.Literal(\"user\"),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t});\n\texport type UserMessage = Static<typeof UserMessageSchema>;\n\n\texport const AssistantMessageSchema = Type.Object({\n\t\trole: Type.Literal(\"assistant\"),\n\t\tprotocol: Model.KnownProviderEnumSchema,\n\t\tprovider: Model.ProviderInfo,\n\t\tmodel: Type.String(),\n\t\tusage: UsageSchema,\n\t\tstopReason: StopReasonSchema,\n\t\terrorMessage: Type.Optional(Type.String()),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t\tcompleted: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema, ThinkingContentSchema, ToolCallSchema])),\n\t\tresponseId: Type.Optional(Type.String()), // Provider-specific response/message identifier when the upstream API exposes one\n\t\tresponseModel: Type.Optional(Type.String()), // Concrete routed model identifier when it differs from the requested model\n\t\tmessageId: Type.String(),\n\t});\n\texport type AssistantMessage = Static<typeof AssistantMessageSchema>;\n\n\texport const MessageSchema = Type.Union([UserMessageSchema, AssistantMessageSchema]);\n\texport type Message = Static<typeof MessageSchema>;\n\n\ttype UserMessageInit = Omit<UserMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\ttype AssistantMessageInit = Omit<AssistantMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\texport function createMessageId(): string {\n\t\treturn uuidv7();\n\t}\n\n\texport function createUserMessage(message: UserMessageInit): UserMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\texport function createAssistantMessage(message: AssistantMessageInit): AssistantMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\t/**\n\t * Generic tool definition with typed parameter schema.\n\t * Usage:\n\t *\n\t * const search = Message.defineTool({\n\t * name: \"search\",\n\t * description: \"Search documents\",\n\t * parameters: Type.Object({\n\t * query: Type.String(),\n\t * limit: Type.Optional(Type.Number()),\n\t * }),\n\t * });\n\t *\n\t * type SearchParams = Static<typeof search.parameters>;\n\t */\n\texport const ToolSchema = Type.Object({\n\t\tname: Type.String(),\n\t\tdescription: Type.String(),\n\t\tparameters: Type.Unsafe<TSchema>({}),\n\t});\n\texport interface Tool<TParameters extends TSchema = TSchema> {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: TParameters;\n\t}\n\texport type ToolArguments<T extends Tool> = Static<T[\"parameters\"]>;\n\n\texport function defineTool<TParameters extends TSchema>(tool: Tool<TParameters>): Tool<TParameters> {\n\t\treturn tool;\n\t}\n\n\texport const ContextSchema = Type.Object({\n\t\tsystemPrompt: Type.Optional(Type.String()),\n\t\tmessages: Type.Array(MessageSchema),\n\t\ttools: Type.Optional(Type.Array(ToolSchema)),\n\t});\n\texport type Context = Static<typeof ContextSchema>;\n\n\tfunction isUnresolvedToolCall(toolCall: ToolCall): toolCall is ToolCallPendingPart | ToolCallRunningPart {\n\t\treturn toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;\n\t}\n\n\tfunction syntheticSkippedToolCall(toolCall: ToolCallPendingPart | ToolCallRunningPart): ToolCall {\n\t\tconst {\n\t\t\tstatus: _status,\n\t\t\tpartial: _partial,\n\t\t\t...base\n\t\t} = toolCall as (ToolCallPendingPart | ToolCallRunningPart) & {\n\t\t\tpartial?: unknown;\n\t\t};\n\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: ToolStatusEnum.skipped,\n\t\t\tresult: {\n\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\tisError: true,\n\t\t\t},\n\t\t\ttime: {\n\t\t\t\t...toolCall.time,\n\t\t\t\tend: Math.max(toolCall.time.end, Date.now()),\n\t\t\t},\n\t\t};\n\t}\n\n\texport function transformMessages<TProtocol extends Model.KnownProviderEnum>(\n\t\tmessages: Message[],\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tnormalizeToolCallId?: (id: string, model: Model.TModel<TProtocol>, source: AssistantMessage) => string,\n\t): Message[] {\n\t\tconst toolCallIDMap = new Map<string, string>();\n\n\t\tconst transformed: Message[] = [];\n\t\tfor (const msg of messages) {\n\t\t\tif (msg.role === \"user\") {\n\t\t\t\ttransformed.push(msg);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider.id === model.provider.id &&\n\t\t\t\tassistantMsg.protocol === model.protocol &&\n\t\t\t\tassistantMsg.model === model.id;\n\n\t\t\tconst transformedParts = assistantMsg.parts.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (isSameModel && block.thinkingSignature) return block;\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst normalizedID = toolCallIDMap.get(block.callID);\n\t\t\t\t\tif (normalizedID && normalizedID !== block.callID) {\n\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: normalizedID };\n\t\t\t\t\t} else if (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);\n\t\t\t\t\t\tif (nextID !== toolCall.callID) {\n\t\t\t\t\t\t\ttoolCallIDMap.set(toolCall.callID, nextID);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: nextID };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\t\t\tconst parts = transformedParts.map((block) => {\n\t\t\t\tif (block.type === \"toolCall\" && isUnresolvedToolCall(block)) {\n\t\t\t\t\treturn syntheticSkippedToolCall(block);\n\t\t\t\t}\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\ttransformed.push({\n\t\t\t\t...assistantMsg,\n\t\t\t\tparts,\n\t\t\t});\n\t\t}\n\n\t\treturn transformed;\n\t}\n}\n","import Type, { type Static } from \"typebox\";\nimport { Message } from \"../message/message\";\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 namespace Event {\n\texport const LLMMessageEventType = {\n\t\tstart: \"start\",\n\n\t\ttextStart: \"text.start\",\n\t\ttextDelta: \"text.delta\",\n\t\ttextEnd: \"text.end\",\n\n\t\tthinkingStart: \"thinking.start\",\n\t\tthinkingDelta: \"thinking.delta\",\n\t\tthinkingEnd: \"thinking.end\",\n\n\t\ttoolcallStart: \"toolcall.start\",\n\t\ttoolcallDelta: \"toolcall.delta\",\n\t\ttoolcallEnd: \"toolcall.end\",\n\t\ttoolcallFinal: \"toolcall.final\",\n\n\t\tdone: \"done\",\n\t\terror: \"error\",\n\t} as const;\n\texport type LLMMessageEventType = (typeof LLMMessageEventType)[keyof typeof LLMMessageEventType];\n\n\t/**\n\t * Event protocol for AssistantMessageEventStream.\n\t *\n\t * Streams should emit `start` before partial updates, then terminate with either:\n\t * - `done` carrying the final successful AssistantMessage, or\n\t * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n\t * and errorMessage.\n\t */\n\texport const LLMMessageEventSchema = Type.Union([\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.start),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tcontent: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tcontent: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\ttoolCall: Message.ToolCallSchema,\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallFinal),\n\t\t\tpartIndex: Type.Number(),\n\t\t\ttoolCall: Message.ToolCallSchema,\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.done),\n\t\t\treason: Type.Union([Type.Literal(\"stop\"), Type.Literal(\"length\"), Type.Literal(\"toolUse\")]),\n\t\t\tmessage: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.error),\n\t\t\treason: Type.Union([Type.Literal(\"aborted\"), Type.Literal(\"error\")]),\n\t\t\terror: Message.AssistantMessageSchema,\n\t\t}),\n\t]);\n\texport type LLMMessageEvent = Static<typeof LLMMessageEventSchema>;\n\n\texport const AgentEventType = {\n\t\t// Agent lifecycle\n\t\tagentStart: \"agent.start\",\n\t\tagentEnd: \"agent.end\",\n\t\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t\tturnStart: \"turn.start\",\n\t\tturnEnd: \"turn.end\",\n\t\t// Message lifecycle - emitted for user, assistant message and corresponding parts\n\t\tmessageStart: \"message.start\",\n\n\t\tmessagePartStart: \"message.part.start\",\n\t\tmessagePartUpdate: \"message.part.update\",\n\t\tmessagePartEnd: \"message.part.end\",\n\n\t\tmessageUpdate: \"message.update\",\n\t\tmessageEnd: \"message.end\",\n\t\t// Tool execution lifecycle\n\t\ttoolExecutionStart: \"tool.execution.start\",\n\t\ttoolExecutionUpdate: \"tool.execution.update\",\n\t\ttoolExecutionEnd: \"tool.execution.end\",\n\t} as const;\n\texport type AgentEventType = (typeof AgentEventType)[keyof typeof AgentEventType];\n\n\t//\n\t// message parts\n\tconst UserMessagePart = Type.Union([Message.TextContentSchema, Message.ImageContentSchema]);\n\tconst AssistantMessagePart = Type.Union([\n\t\tMessage.TextContentSchema,\n\t\tMessage.ImageContentSchema,\n\t\tMessage.ThinkingContentSchema,\n\t\tMessage.ToolCallSchema,\n\t]);\n\n\t//\n\t// user message part\n\t// part start\n\tconst UserMessagePartStart = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartStart),\n\t\tmessage: Message.UserMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: UserMessagePart,\n\t});\n\t// part end\n\tconst UserMessagePartEnd = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\t\tmessage: Message.UserMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: UserMessagePart,\n\t});\n\n\t//\n\t// assistant message part\n\t// part start\n\tconst AssistantMessagePartStart = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartStart),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t});\n\t// part update llm\n\tconst AssistantMessagePartLLMUpdate = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t\tsource: Type.Literal(\"llm\"),\n\t});\n\t// part update tool\n\tconst AssistantMessagePartToolUpdate = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t\tsource: Type.Literal(\"tool\"),\n\t});\n\t// part end\n\tconst AssistantMessagePartEnd = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t});\n\n\t//\n\t// tool exection\n\tconst ToolExecutionStartSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionStart),\n\t\t\t}),\n\t\t]),\n\t);\n\texport type ToolExecutionStart = Static<typeof ToolExecutionStartSchema>;\n\n\tconst ToolExecutionUpdateSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionUpdate),\n\t\t\t}),\n\t\t\tMessage.ToolRunningSchema,\n\t\t]),\n\t);\n\texport type ToolExecutionUpdate = Static<typeof ToolExecutionUpdateSchema>;\n\n\tconst ToolExecutionEndSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionEnd),\n\t\t\t}),\n\t\t\tType.Union([Message.ToolCompletedSchema, Message.ToolErrorSchema]),\n\t\t]),\n\t);\n\texport type ToolExecutionEnd = Static<typeof ToolExecutionEndSchema>;\n\n\t/**\n\t * Events emitted by the Agent lifecycle\n\t * These events provide fine-grained lifecycle information for messages, turns, and tool execution.\n\t */\n\texport const AgentEventSchema = Type.Union([\n\t\t//\n\t\t// Agent lifecycle\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.agentStart),\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.agentEnd),\n\t\t\tmessages: Type.Array(Message.MessageSchema),\n\t\t}),\n\t\t//\n\t\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.turnStart),\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.turnEnd),\n\t\t\tmessage: Message.AssistantMessageSchema,\n\t\t}),\n\t\t//\n\t\t// Message lifecycle - emitted for user, assistant and corresponding parts\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageStart),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\t// user message parts lifecycle\n\t\tType.Union([UserMessagePartStart, UserMessagePartEnd]),\n\t\t//\n\t\t// assistant message parts lifecycle\n\t\tType.Union([\n\t\t\tAssistantMessagePartStart,\n\t\t\tAssistantMessagePartLLMUpdate,\n\t\t\tAssistantMessagePartToolUpdate,\n\t\t\tAssistantMessagePartEnd,\n\t\t]),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageUpdate),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageEnd),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\t//\n\t\t// Tool execution lifecycle\n\t\tToolExecutionStartSchema,\n\t\tToolExecutionUpdateSchema,\n\t\tToolExecutionEndSchema,\n\t]);\n\texport type AgentEvent = Static<typeof AgentEventSchema>;\n}\n","import { Model } from \"./model/model\";\n\ntype LLM = {\n\t<TProvider extends string, TModel extends Model.Info[\"id\"]>(\n\t\tprovider: TProvider,\n\t\tmodel: TModel,\n\t\toverrides?: Partial<Model.Info>,\n\t): Promise<Model.Info | 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 <TProvider extends string, TModel extends Model.Info[\"id\"]>(\n\tprovider: TProvider,\n\tmodel: TModel,\n\toverrides?: Partial<Model.Info>,\n): Promise<Model.Info | undefined> => Model.getModel(provider, model, overrides);\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream\";\nimport type { SharedOptions, ThinkingBudgets } from \"./shared\";\n\nexport namespace Protocol {\n\texport const ProviderProtocolNotFoundError = NamedError.create(\n\t\t\"ProviderProtocolNotFoundError\",\n\t\tType.Object({\n\t\t\tprotocol: Model.KnownProviderEnumSchema,\n\t\t}),\n\t);\n\texport type ProviderProtocolNotFoundError = InstanceType<typeof ProviderProtocolNotFoundError>;\n\n\texport const ProtocolMismatchError = NamedError.create(\n\t\t\"ProtocolMismatchError\",\n\t\tType.Object({\n\t\t\tactual: Model.KnownProviderEnumSchema,\n\t\t\texpected: Model.KnownProviderEnumSchema,\n\t\t}),\n\t);\n\texport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\n\texport const ProtocolAuthError = NamedError.create(\n\t\t\"ProtocolAuthError\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t\tprotocol: Type.String(),\n\t\t}),\n\t);\n\texport type ProtocolAuthError = InstanceType<typeof ProtocolAuthError>;\n\n\texport type CommonOptions = SharedOptions & {\n\t\treasoning?: Model.ActiveThinkingLevel;\n\t\tthinkingBudgets?: ThinkingBudgets;\n\t};\n\texport interface OptionsByProtocol {}\n\texport type ProtocolWithOptions = keyof OptionsByProtocol & Model.KnownProviderEnum;\n\texport type OptionsFor<TProtocol extends ProtocolWithOptions> = OptionsByProtocol[TProtocol];\n\n\texport type StreamFunction<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: Static<S>) => AssistantMessageEventStream;\n\n\texport type ProtocolStreamFunction<S extends TSchema = TSchema> = (\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: Static<S>,\n\t) => AssistantMessageEventStream;\n\n\texport interface Protocol<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> {\n\t\tprotocol: TProtocol;\n\t\tstream: StreamFunction<TProtocol, S>;\n\t}\n\n\texport interface RegisteredProtocol<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> {\n\t\tprotocol: TProtocol;\n\t\tstream: ProtocolStreamFunction<S>;\n\t}\n\n\ttype AnyRegisteredProtocol = RegisteredProtocol<Model.KnownProviderEnum, TSchema>;\n\n\ttype RegistryEntry = {\n\t\tprovider: AnyRegisteredProtocol;\n\t\tsourceId?: string;\n\t};\n\n\tconst protocolRegistry = new Map<Model.KnownProviderEnum, RegistryEntry>();\n\n\tfunction wrapStream<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\t\tprotocol: TProtocol,\n\t\tstream: StreamFunction<TProtocol, S>,\n\t): ProtocolStreamFunction<S> {\n\t\treturn (model, context, options) => {\n\t\t\tif (model.protocol !== protocol) {\n\t\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\t\tactual: model.protocol,\n\t\t\t\t\texpected: protocol,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn stream(model as Model.TModel<TProtocol>, context, options);\n\t\t};\n\t}\n\n\texport function registerProtocolProvider<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\t\tprovider: Protocol<TProtocol, S>,\n\t\tsourceId?: string,\n\t): void {\n\t\tconst registered: RegisteredProtocol<TProtocol, S> = {\n\t\t\tprotocol: provider.protocol,\n\t\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t\t};\n\n\t\tprotocolRegistry.set(provider.protocol, {\n\t\t\tprovider: registered as AnyRegisteredProtocol,\n\t\t\tsourceId,\n\t\t});\n\t}\n\n\texport function getProtocolProvider(protocol: Model.KnownProviderEnum): AnyRegisteredProtocol | undefined {\n\t\treturn protocolRegistry.get(protocol)?.provider;\n\t}\n\n\texport function resolveProtocolProvider(model: Model.Info): AnyRegisteredProtocol {\n\t\tconst provider = getProtocolProvider(model.protocol);\n\t\tif (!provider) {\n\t\t\tthrow new ProviderProtocolNotFoundError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t});\n\t\t}\n\n\t\treturn provider;\n\t}\n\n\texport function getProtocolProviders(): AnyRegisteredProtocol[] {\n\t\treturn Array.from(protocolRegistry.values(), (entry) => entry.provider);\n\t}\n\n\texport function stream<TProtocol extends ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: OptionsFor<TProtocol>,\n\t): AssistantMessageEventStream;\n\texport function stream(\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: CommonOptions,\n\t): AssistantMessageEventStream;\n\texport function stream(\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: CommonOptions,\n\t): AssistantMessageEventStream {\n\t\tconst provider = resolveProtocolProvider(model);\n\t\treturn provider.stream(model, context, options);\n\t}\n\n\texport async function complete<TProtocol extends ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: OptionsFor<TProtocol>,\n\t): Promise<Message.AssistantMessage>;\n\texport async function complete(\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: CommonOptions,\n\t): Promise<Message.AssistantMessage>;\n\texport async function complete(\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: CommonOptions,\n\t): Promise<Message.AssistantMessage> {\n\t\tconst s = stream(model, context, options);\n\t\treturn s.result();\n\t}\n\n\texport function unregisterProtocolProviders(sourceId: string): void {\n\t\tfor (const [protocol, entry] of protocolRegistry.entries()) {\n\t\t\tif (entry.sourceId === sourceId) {\n\t\t\t\tprotocolRegistry.delete(protocol);\n\t\t\t}\n\t\t}\n\t}\n\n\texport function clearProtocolProviders(): void {\n\t\tprotocolRegistry.clear();\n\t}\n}\n","import { Type, type Static } from \"typebox\";\nimport { type Model } from \"../model/model\";\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});\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, type Static } from \"typebox\";\nimport { Model } from \"../model/model\";\nimport type { Protocol } from \"./protocol\";\nimport { SharedOptions, ThinkingBudgets } from \"./shared\";\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 OpenRouterOptions = AISDKOptions<OpenRouterProviderSettings, { openrouter?: OpenRouterProviderOptions }>;\nexport type XaiOptions = AISDKOptions<XaiProviderSettings, { xai?: XaiLanguageOptions }>;\n\nexport type Options = Static<typeof Options>;\n\ndeclare module \"./protocol\" {\n\texport namespace Protocol {\n\t\t// Used for type inference\n\t\t// eslint-disable-next-line no-unused-vars -- declaration merging registers AI SDK protocol options.\n\t\tinterface OptionsByProtocol {\n\t\t\t[Model.KnownProviderEnum.openai]: OpenAIOptions;\n\t\t\t[Model.KnownProviderEnum.anthropic]: AnthropicOptions;\n\t\t\t[Model.KnownProviderEnum.google]: GoogleOptions;\n\t\t\t[Model.KnownProviderEnum.googleVertex]: GoogleVertexOptions;\n\t\t\t[Model.KnownProviderEnum.googleVertexAnthropic]: GoogleVertexAnthropicOptions;\n\t\t\t[Model.KnownProviderEnum.openaiCompatible]: OpenAICompatibleOptions;\n\t\t\t[Model.KnownProviderEnum.openrouter]: OpenRouterOptions;\n\t\t\t[Model.KnownProviderEnum.xai]: XaiOptions;\n\t\t}\n\t}\n}\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type { Event } from \"../event/event\";\nimport type { Message } from \"../message/message\";\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\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\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","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 { Model } from \"../model/model\";\nimport type { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { loadProviderFactory, packageForModel, resolveLanguageModel } from \"./registry\";\nimport { getEnvApiKey, mergeHeaders } from \"./runtime\";\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\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport { parseStreamingJson } from \"../utils/jsonparse\";\nimport { sanitizeSurrogates } from \"../utils/sanitize\";\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: \"image\", image: 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: \"image-data\" as const,\n\t\t\t\tdata: image.data,\n\t\t\t\tmediaType: image.mimeType,\n\t\t\t})),\n\t\t],\n\t};\n}\n\nfunction assistantMessages(message: Message.AssistantMessage): 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({ type: \"text\", text });\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) 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\tanthropic: { signature: part.thinkingSignature },\n\t\t\t\t};\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\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});\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\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(context.messages, model);\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));\n\t}\n\n\treturn messages;\n}\n\nexport function convertTools(tools?: Message.Tool[]): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(tool.parameters as any),\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(usage: LanguageModelUsage | undefined, model: Model.Info): Message.AssistantMessage[\"usage\"] {\n\tconst cacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? usage?.cachedInputTokens ?? 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\ttotalTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, result);\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport { AssistantMessageEventStream } from \"../utils/eventstream\";\nimport { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { resolveAISDKLanguageModel } from \"./provider\";\nimport { formatThrownError } from \"./runtime\";\nimport { applyDefaultMaxTokens } from \"./shared\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tcreateAssistantMessage,\n\tmapFinishReason,\n\tmapUsage,\n\ttoolCallFromPart,\n\tupdateToolCallFromInput,\n\ttype StreamingToolCallBlock,\n} from \"./transform\";\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 === \"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};\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\") {\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 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(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): 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\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(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): 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\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\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): 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\tfinishTextBlock(output, part.id, stream);\n\t\t\tbreak;\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\tfinishThinkingBlock(output, part.id, stream);\n\t\t\tbreak;\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);\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);\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\toutput.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\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\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);\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 activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = {\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);\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 { Model } from \"../model/model\";\nimport { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { stream } from \"./stream\";\n\nexport { Options } from \"./options\";\nexport * from \"./registry\";\nexport { stream } from \"./stream\";\nexport * from \"./transform\";\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.openrouter));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));\n}\n","import { registerAISDKProtocols } from \"./index\";\n\nregisterAISDKProtocols();\n","import \"./llm/register\";\n\nimport type { Message } from \"./message/message\";\nimport type { Model } from \"./model/model\";\nimport { Protocol } from \"./llm/protocol\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream\";\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\t(model: Model.Info, context: Message.Context, options?: Protocol.CommonOptions): 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 { Message } from \"../message/message\";\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":";;;;;;;;AAIO,IAAA;;CACC,MAAM,oBAAA,SAAA,oBAAoBA,OAAK,OAAO;EAC5C,MAAMA,OAAK,QAAQ,OAAO;EAC1B,MAAMA,OAAK,QAAQ;EACnB,eAAeA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAC3C,CAAC;CAGK,MAAM,qBAAA,SAAA,qBAAqBA,OAAK,OAAO;EAC7C,MAAMA,OAAK,QAAQ,QAAQ;EAC3B,MAAMA,OAAK,QAAQ;EACnB,UAAUA,OAAK,QAAQ;EACvB,CAAC;CAGK,MAAM,wBAAA,SAAA,wBAAwBA,OAAK,OAAO;EAChD,MAAMA,OAAK,QAAQ,WAAW;EAC9B,UAAUA,OAAK,QAAQ;EACvB,mBAAmBA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAI/C,UAAUA,OAAK,SAASA,OAAK,SAAS,CAAC;EACvC,CAAC;CAGK,MAAM,qBAAA,SAAA,qBAAqBA,OAAK,OAAO;EAC7C,MAAMA,OAAK,QAAQ,WAAW;EAC9B,QAAQA,OAAK,QAAQ;EACrB,MAAMA,OAAK,QAAQ;EACnB,WAAWA,OAAK,OAAOA,OAAK,QAAQ,EAAEA,OAAK,KAAK,CAAC;EACjD,kBAAkBA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAC9C,MAAMA,OAAK,OAAO;GACjB,OAAOA,OAAK,QAAQ;GACpB,KAAKA,OAAK,QAAQ;GAClB,CAAC;EACF,CAAC;CAEK,MAAM,oBAAA,SAAA,oBAAoBA,OAAK,OAAO;EAC5C,SAASA,OAAK,MAAMA,OAAK,MAAM,CAAC,mBAAmB,mBAAm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AACjC,QAAO;;AAGR,SAAS,UAAU,OAA4E;AAC9F,KAAI,MAAM,aAAc,QAAO,MAAM,aAAa,UAAU,EAAE;CAE9D,MAAM,qBAAqB,MAAM,QAAQ;AACzC,KAAI,MAAM,QAAQ,mBAAmB,CAAE,QAAO,mBAAmB,KAAK,KAAK;AAE3E,QAAO;;;;;AAMR,SAAgB,eAAkC,QAAW,OAAgB,OAA0B;CACtG,MAAM,YAAY,aAAa,OAAO;CACtC,MAAM,QAAQ,MAAM,QAAQ,QAAQ,gBAAgB,MAAM,CAAC;AAE3D,KAAI;AACH,SAAO,UAAU,MAAM,MAAM;SACtB;EACP,MAAM,CAAC,SAAS,oBAAoB,UAAU,OAAO,MAAM;EAC3D,MAAM,SACL,iBACE,KAAK,QAAQ;AACb,UAAO,MAAM,UAAU,IAAI,CAAC,IAAI,IAAI;IACnC,CACD,KAAK,KAAK,IAAI;AAEjB,QAAM,IAAI,MACT;GACC,yBAAyB;GACzB,GAAG,OAAO;GACV;GACA,GAAG,KAAK,UAAU,OAAO,MAAM,EAAE,CAAC;GAClC,CAAC,KAAK,KAAK,CACZ;;;;;;AAOH,SAAgB,iBACf,OACA,eAC2B;CAC3B,MAAM,OAAO,MAAM,MAAM,MAAM,EAAE,SAAS,cAAc,KAAK;AAC7D,KAAI,CAAC,KACJ,OAAM,IAAI,MAAM,SAAS,cAAc,KAAK,aAAa;AAE1D,QAAO,sBAAsB,MAAM,cAAc;;;;;AAMlD,SAAgB,sBACf,MACA,eAC2B;AAC3B,QAAO,eACN,KAAK,YACL,cAAc,SACd,SAAS,cAAc,KAAK,GAC5B"}
1
+ {"version":3,"file":"index.mjs","names":["Type","Type","Type","Type","Type","partialParse","stream"],"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/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 { Model } from \"../model/model\";\n\nexport namespace Message {\n\texport const TextContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"text\"),\n\t\ttext: Type.String(),\n\t\ttextSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the message ID\n\t});\n\texport type TextContent = Static<typeof TextContentSchema>;\n\n\texport const ImageContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"image\"),\n\t\tdata: Type.String(), // base64 encoded image data\n\t\tmimeType: Type.String(), // e.g., \"image/jpeg\", \"image/png\"\n\t});\n\texport type ImageContent = Static<typeof ImageContentSchema>;\n\n\texport const ThinkingContentSchema = Type.Object({\n\t\ttype: Type.Literal(\"thinking\"),\n\t\tthinking: Type.String(),\n\t\tthinkingSignature: Type.Optional(Type.String()), // e.g., for OpenAI responses, the reasoning item ID\n\t\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t\t * to the API for multi-turn continuity. */\n\t\tredacted: Type.Optional(Type.Boolean()),\n\t});\n\texport type ThinkingContent = Static<typeof ThinkingContentSchema>;\n\n\texport const ToolCallBaseSchema = Type.Object({\n\t\ttype: Type.Literal(\"toolCall\"),\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\targuments: Type.Record(Type.String(), Type.Any()),\n\t\tthoughtSignature: Type.Optional(Type.String()), // Google-specific: opaque signature for reusing thought context\n\t\ttime: Type.Object({\n\t\t\tstart: Type.Number(), // Unix timestamp in milliseconds\n\t\t\tend: Type.Number(), // Unix timestamp in milliseconds, last known lifecycle update\n\t\t}),\n\t});\n\n\texport const ToolSuccessResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(false),\n\t});\n\texport const ToolErrorResult = Type.Object({\n\t\tcontent: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t\tdetails: Type.Optional(Type.Any()),\n\t\tisError: Type.Literal(true),\n\t});\n\texport const ToolRunningPartial = Type.Object({\n\t\tcontent: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),\n\t\tdetails: Type.Optional(Type.Any()),\n\t});\n\n\texport const ToolStatusEnum = {\n\t\tpending: \"pending\",\n\t\trunning: \"running\",\n\t\tcompleted: \"completed\",\n\t\terror: \"error\",\n\t\tskipped: \"skipped\",\n\t\taborted: \"aborted\",\n\t} as const;\n\n\texport const ToolRunningSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.running),\n\t\tpartial: Type.Optional(ToolRunningPartial),\n\t});\n\texport const ToolCompletedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.completed),\n\t\tresult: ToolSuccessResult,\n\t});\n\texport const ToolErrorSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.error),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolSkippedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.skipped),\n\t\tresult: ToolErrorResult,\n\t});\n\texport const ToolAbortedSchema = Type.Object({\n\t\tstatus: Type.Literal(ToolStatusEnum.aborted),\n\t\tresult: ToolErrorResult,\n\t});\n\n\tconst ToolCallPendingPart = Type.Intersect([\n\t\tToolCallBaseSchema,\n\t\tType.Object({\n\t\t\tstatus: Type.Literal(ToolStatusEnum.pending),\n\t\t}),\n\t]);\n\tconst ToolCallRunningPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolRunningSchema]));\n\tconst ToolCallCompletedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));\n\tconst ToolCallErrorPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolErrorSchema]));\n\tconst ToolCallSkippedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));\n\tconst ToolCallAbortedPart = Type.Evaluate(Type.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));\n\n\texport const ToolCallInFlightSchema = Type.Object({\n\t\tcallID: Type.String(),\n\t\tname: Type.String(),\n\t\trawArgs: Type.Record(Type.String(), Type.Unknown()),\n\t\targs: Type.Optional(Type.Unknown()),\n\t});\n\texport type ToolCallInFlight = Static<typeof ToolCallInFlightSchema>;\n\n\texport const ToolCallSchema = Type.Union([\n\t\tToolCallPendingPart,\n\t\tToolCallRunningPart,\n\t\tToolCallCompletedPart,\n\t\tToolCallErrorPart,\n\t\tToolCallSkippedPart,\n\t\tToolCallAbortedPart,\n\t]);\n\n\texport type ToolCall = Static<typeof ToolCallSchema>;\n\texport type ToolCallPendingPart = Static<typeof ToolCallPendingPart>;\n\texport type ToolCallRunningPart = Static<typeof ToolCallRunningPart>;\n\texport type ToolCallCompletedPart = Static<typeof ToolCallCompletedPart>;\n\texport type ToolCallErrorPart = Static<typeof ToolCallErrorPart>;\n\n\texport const UsageSchema = Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t\ttotalTokens: Type.Number(),\n\t\tcost: Type.Object({\n\t\t\tinput: Type.Number(),\n\t\t\toutput: Type.Number(),\n\t\t\tcacheRead: Type.Number(),\n\t\t\tcacheWrite: Type.Number(),\n\t\t\ttotal: Type.Number(),\n\t\t}),\n\t});\n\texport type Usage = Static<typeof UsageSchema>;\n\n\texport const StopReasonSchema = Type.Union([\n\t\tType.Literal(\"stop\"),\n\t\tType.Literal(\"length\"),\n\t\tType.Literal(\"toolUse\"),\n\t\tType.Literal(\"error\"),\n\t\tType.Literal(\"aborted\"),\n\t]);\n\texport type StopReason = Static<typeof StopReasonSchema>;\n\n\texport const UserMessageSchema = Type.Object({\n\t\tmessageId: Type.String(),\n\t\trole: Type.Literal(\"user\"),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),\n\t});\n\texport type UserMessage = Static<typeof UserMessageSchema>;\n\n\texport const AssistantMessageSchema = Type.Object({\n\t\trole: Type.Literal(\"assistant\"),\n\t\tprotocol: Model.KnownProviderEnumSchema,\n\t\tprovider: Model.ProviderInfo,\n\t\tmodel: Type.String(),\n\t\tusage: UsageSchema,\n\t\tstopReason: StopReasonSchema,\n\t\terrorMessage: Type.Optional(Type.String()),\n\t\ttime: Type.Object({\n\t\t\tcreated: Type.Number(),\n\t\t\tcompleted: Type.Number(),\n\t\t}),\n\t\tparts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema, ThinkingContentSchema, ToolCallSchema])),\n\t\tresponseId: Type.Optional(Type.String()), // Provider-specific response/message identifier when the upstream API exposes one\n\t\tresponseModel: Type.Optional(Type.String()), // Concrete routed model identifier when it differs from the requested model\n\t\tmessageId: Type.String(),\n\t});\n\texport type AssistantMessage = Static<typeof AssistantMessageSchema>;\n\n\texport const MessageSchema = Type.Union([UserMessageSchema, AssistantMessageSchema]);\n\texport type Message = Static<typeof MessageSchema>;\n\n\ttype UserMessageInit = Omit<UserMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\ttype AssistantMessageInit = Omit<AssistantMessage, \"messageId\"> & {\n\t\tmessageId?: string;\n\t};\n\n\texport function createMessageId(): string {\n\t\treturn uuidv7();\n\t}\n\n\texport function createUserMessage(message: UserMessageInit): UserMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\texport function createAssistantMessage(message: AssistantMessageInit): AssistantMessage {\n\t\tconst { messageId = createMessageId(), ...rest } = message;\n\t\treturn {\n\t\t\tmessageId,\n\t\t\t...rest,\n\t\t};\n\t}\n\n\t/**\n\t * Generic tool definition with typed parameter schema.\n\t * Usage:\n\t *\n\t * const search = Message.defineTool({\n\t * name: \"search\",\n\t * description: \"Search documents\",\n\t * parameters: Type.Object({\n\t * query: Type.String(),\n\t * limit: Type.Optional(Type.Number()),\n\t * }),\n\t * });\n\t *\n\t * type SearchParams = Static<typeof search.parameters>;\n\t */\n\texport const ToolSchema = Type.Object({\n\t\tname: Type.String(),\n\t\tdescription: Type.String(),\n\t\tparameters: Type.Unsafe<TSchema>({}),\n\t});\n\texport interface Tool<TParameters extends TSchema = TSchema> {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: TParameters;\n\t}\n\texport type ToolArguments<T extends Tool> = Static<T[\"parameters\"]>;\n\n\texport function defineTool<TParameters extends TSchema>(tool: Tool<TParameters>): Tool<TParameters> {\n\t\treturn tool;\n\t}\n\n\texport const ContextSchema = Type.Object({\n\t\tsystemPrompt: Type.Optional(Type.String()),\n\t\tmessages: Type.Array(MessageSchema),\n\t\ttools: Type.Optional(Type.Array(ToolSchema)),\n\t});\n\texport type Context = Static<typeof ContextSchema>;\n\n\tfunction isUnresolvedToolCall(toolCall: ToolCall): toolCall is ToolCallPendingPart | ToolCallRunningPart {\n\t\treturn toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;\n\t}\n\n\tfunction syntheticSkippedToolCall(toolCall: ToolCallPendingPart | ToolCallRunningPart): ToolCall {\n\t\tconst {\n\t\t\tstatus: _status,\n\t\t\tpartial: _partial,\n\t\t\t...base\n\t\t} = toolCall as (ToolCallPendingPart | ToolCallRunningPart) & {\n\t\t\tpartial?: unknown;\n\t\t};\n\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: ToolStatusEnum.skipped,\n\t\t\tresult: {\n\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\tisError: true,\n\t\t\t},\n\t\t\ttime: {\n\t\t\t\t...toolCall.time,\n\t\t\t\tend: Math.max(toolCall.time.end, Date.now()),\n\t\t\t},\n\t\t};\n\t}\n\n\texport function transformMessages<TProtocol extends Model.KnownProviderEnum>(\n\t\tmessages: Message[],\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tnormalizeToolCallId?: (id: string, model: Model.TModel<TProtocol>, source: AssistantMessage) => string,\n\t): Message[] {\n\t\tconst toolCallIDMap = new Map<string, string>();\n\n\t\tconst transformed: Message[] = [];\n\t\tfor (const msg of messages) {\n\t\t\tif (msg.role === \"user\") {\n\t\t\t\ttransformed.push(msg);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider.id === model.provider.id &&\n\t\t\t\tassistantMsg.protocol === model.protocol &&\n\t\t\t\tassistantMsg.model === model.id;\n\n\t\t\tconst transformedParts = assistantMsg.parts.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (isSameModel && block.thinkingSignature) return block;\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst normalizedID = toolCallIDMap.get(block.callID);\n\t\t\t\t\tif (normalizedID && normalizedID !== block.callID) {\n\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: normalizedID };\n\t\t\t\t\t} else if (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);\n\t\t\t\t\t\tif (nextID !== toolCall.callID) {\n\t\t\t\t\t\t\ttoolCallIDMap.set(toolCall.callID, nextID);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, callID: nextID };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\t\t\tconst parts = transformedParts.map((block) => {\n\t\t\t\tif (block.type === \"toolCall\" && isUnresolvedToolCall(block)) {\n\t\t\t\t\treturn syntheticSkippedToolCall(block);\n\t\t\t\t}\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\ttransformed.push({\n\t\t\t\t...assistantMsg,\n\t\t\t\tparts,\n\t\t\t});\n\t\t}\n\n\t\treturn transformed;\n\t}\n}\n","import Type, { type Static } from \"typebox\";\nimport { Message } from \"../message/message\";\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 namespace Event {\n\texport const LLMMessageEventType = {\n\t\tstart: \"start\",\n\n\t\ttextStart: \"text.start\",\n\t\ttextDelta: \"text.delta\",\n\t\ttextEnd: \"text.end\",\n\n\t\tthinkingStart: \"thinking.start\",\n\t\tthinkingDelta: \"thinking.delta\",\n\t\tthinkingEnd: \"thinking.end\",\n\n\t\ttoolcallStart: \"toolcall.start\",\n\t\ttoolcallDelta: \"toolcall.delta\",\n\t\ttoolcallEnd: \"toolcall.end\",\n\t\ttoolcallFinal: \"toolcall.final\",\n\n\t\tdone: \"done\",\n\t\terror: \"error\",\n\t} as const;\n\texport type LLMMessageEventType = (typeof LLMMessageEventType)[keyof typeof LLMMessageEventType];\n\n\t/**\n\t * Event protocol for AssistantMessageEventStream.\n\t *\n\t * Streams should emit `start` before partial updates, then terminate with either:\n\t * - `done` carrying the final successful AssistantMessage, or\n\t * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n\t * and errorMessage.\n\t */\n\texport const LLMMessageEventSchema = Type.Union([\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.start),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.textEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tcontent: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.thinkingEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tcontent: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallStart),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallDelta),\n\t\t\tpartIndex: Type.Number(),\n\t\t\tdelta: Type.String(),\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallEnd),\n\t\t\tpartIndex: Type.Number(),\n\t\t\ttoolCall: Message.ToolCallSchema,\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.toolcallFinal),\n\t\t\tpartIndex: Type.Number(),\n\t\t\ttoolCall: Message.ToolCallSchema,\n\t\t\tpartial: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.done),\n\t\t\treason: Type.Union([Type.Literal(\"stop\"), Type.Literal(\"length\"), Type.Literal(\"toolUse\")]),\n\t\t\tmessage: Message.AssistantMessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(LLMMessageEventType.error),\n\t\t\treason: Type.Union([Type.Literal(\"aborted\"), Type.Literal(\"error\")]),\n\t\t\terror: Message.AssistantMessageSchema,\n\t\t}),\n\t]);\n\texport type LLMMessageEvent = Static<typeof LLMMessageEventSchema>;\n\n\texport const AgentEventType = {\n\t\t// Agent lifecycle\n\t\tagentStart: \"agent.start\",\n\t\tagentEnd: \"agent.end\",\n\t\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t\tturnStart: \"turn.start\",\n\t\tturnEnd: \"turn.end\",\n\t\t// Message lifecycle - emitted for user, assistant message and corresponding parts\n\t\tmessageStart: \"message.start\",\n\n\t\tmessagePartStart: \"message.part.start\",\n\t\tmessagePartUpdate: \"message.part.update\",\n\t\tmessagePartEnd: \"message.part.end\",\n\n\t\tmessageUpdate: \"message.update\",\n\t\tmessageEnd: \"message.end\",\n\t\t// Tool execution lifecycle\n\t\ttoolExecutionStart: \"tool.execution.start\",\n\t\ttoolExecutionUpdate: \"tool.execution.update\",\n\t\ttoolExecutionEnd: \"tool.execution.end\",\n\t} as const;\n\texport type AgentEventType = (typeof AgentEventType)[keyof typeof AgentEventType];\n\n\t//\n\t// message parts\n\tconst UserMessagePart = Type.Union([Message.TextContentSchema, Message.ImageContentSchema]);\n\tconst AssistantMessagePart = Type.Union([\n\t\tMessage.TextContentSchema,\n\t\tMessage.ImageContentSchema,\n\t\tMessage.ThinkingContentSchema,\n\t\tMessage.ToolCallSchema,\n\t]);\n\n\t//\n\t// user message part\n\t// part start\n\tconst UserMessagePartStart = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartStart),\n\t\tmessage: Message.UserMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: UserMessagePart,\n\t});\n\t// part end\n\tconst UserMessagePartEnd = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\t\tmessage: Message.UserMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: UserMessagePart,\n\t});\n\n\t//\n\t// assistant message part\n\t// part start\n\tconst AssistantMessagePartStart = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartStart),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t});\n\t// part update llm\n\tconst AssistantMessagePartLLMUpdate = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t\tsource: Type.Literal(\"llm\"),\n\t});\n\t// part update tool\n\tconst AssistantMessagePartToolUpdate = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartUpdate),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t\tsource: Type.Literal(\"tool\"),\n\t});\n\t// part end\n\tconst AssistantMessagePartEnd = Type.Object({\n\t\ttype: Type.Literal(AgentEventType.messagePartEnd),\n\t\tmessage: Message.AssistantMessageSchema,\n\t\tpartIndex: Type.Number(),\n\t\tpart: AssistantMessagePart,\n\t});\n\n\t//\n\t// tool exection\n\tconst ToolExecutionStartSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionStart),\n\t\t\t}),\n\t\t]),\n\t);\n\texport type ToolExecutionStart = Static<typeof ToolExecutionStartSchema>;\n\n\tconst ToolExecutionUpdateSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionUpdate),\n\t\t\t}),\n\t\t\tMessage.ToolRunningSchema,\n\t\t]),\n\t);\n\texport type ToolExecutionUpdate = Static<typeof ToolExecutionUpdateSchema>;\n\n\tconst ToolExecutionEndSchema = Type.Evaluate(\n\t\tType.Intersect([\n\t\t\tMessage.ToolCallInFlightSchema,\n\t\t\tType.Object({\n\t\t\t\ttype: Type.Literal(AgentEventType.toolExecutionEnd),\n\t\t\t}),\n\t\t\tType.Union([Message.ToolCompletedSchema, Message.ToolErrorSchema]),\n\t\t]),\n\t);\n\texport type ToolExecutionEnd = Static<typeof ToolExecutionEndSchema>;\n\n\t/**\n\t * Events emitted by the Agent lifecycle\n\t * These events provide fine-grained lifecycle information for messages, turns, and tool execution.\n\t */\n\texport const AgentEventSchema = Type.Union([\n\t\t//\n\t\t// Agent lifecycle\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.agentStart),\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.agentEnd),\n\t\t\tmessages: Type.Array(Message.MessageSchema),\n\t\t}),\n\t\t//\n\t\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.turnStart),\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.turnEnd),\n\t\t\tmessage: Message.AssistantMessageSchema,\n\t\t}),\n\t\t//\n\t\t// Message lifecycle - emitted for user, assistant and corresponding parts\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageStart),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\t// user message parts lifecycle\n\t\tType.Union([UserMessagePartStart, UserMessagePartEnd]),\n\t\t//\n\t\t// assistant message parts lifecycle\n\t\tType.Union([\n\t\t\tAssistantMessagePartStart,\n\t\t\tAssistantMessagePartLLMUpdate,\n\t\t\tAssistantMessagePartToolUpdate,\n\t\t\tAssistantMessagePartEnd,\n\t\t]),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageUpdate),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\tType.Object({\n\t\t\ttype: Type.Literal(AgentEventType.messageEnd),\n\t\t\tmessage: Message.MessageSchema,\n\t\t}),\n\t\t//\n\t\t// Tool execution lifecycle\n\t\tToolExecutionStartSchema,\n\t\tToolExecutionUpdateSchema,\n\t\tToolExecutionEndSchema,\n\t]);\n\texport type AgentEvent = Static<typeof AgentEventSchema>;\n}\n","import { Model } from \"./model/model\";\n\ntype LLM = {\n\t<TProvider extends string, TModelId extends Model.Info[\"id\"]>(\n\t\tprovider: TProvider,\n\t\tmodel: TModelId,\n\t\toverrides?: Partial<Model.Info>,\n\t): Promise<Model.TModel<Model.ProviderToProtocol<TProvider>> | 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 <TProvider extends string, TModelId extends Model.Info[\"id\"]>(\n\tprovider: TProvider,\n\tmodel: TModelId,\n\toverrides?: Partial<Model.Info>,\n): Promise<Model.TModel<Model.ProviderToProtocol<TProvider>> | undefined> => Model.getModel(provider, model, overrides);\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport type { AssistantMessageEventStream } from \"../utils/eventstream\";\nimport type { OptionsByProtocol as ImportedOptionsByProtocol } from \"./options\";\nimport type { SharedOptions, ThinkingBudgets } from \"./shared\";\n\nexport namespace Protocol {\n\texport const ProviderProtocolNotFoundError = NamedError.create(\n\t\t\"ProviderProtocolNotFoundError\",\n\t\tType.Object({\n\t\t\tprotocol: Model.KnownProviderEnumSchema,\n\t\t}),\n\t);\n\texport type ProviderProtocolNotFoundError = InstanceType<typeof ProviderProtocolNotFoundError>;\n\n\texport const ProtocolMismatchError = NamedError.create(\n\t\t\"ProtocolMismatchError\",\n\t\tType.Object({\n\t\t\tactual: Model.KnownProviderEnumSchema,\n\t\t\texpected: Model.KnownProviderEnumSchema,\n\t\t}),\n\t);\n\texport type ProtocolMismatchError = InstanceType<typeof ProtocolMismatchError>;\n\n\texport const ProtocolAuthError = NamedError.create(\n\t\t\"ProtocolAuthError\",\n\t\tType.Object({\n\t\t\tmessage: Type.String(),\n\t\t\tprotocol: Type.String(),\n\t\t}),\n\t);\n\texport type ProtocolAuthError = InstanceType<typeof ProtocolAuthError>;\n\n\texport type CommonOptions = SharedOptions & {\n\t\treasoning?: Model.ActiveThinkingLevel;\n\t\tthinkingBudgets?: ThinkingBudgets;\n\t};\n\texport type OptionsByProtocol = ImportedOptionsByProtocol;\n\texport type ProtocolWithOptions = keyof OptionsByProtocol & Model.KnownProviderEnum;\n\texport type OptionsFor<TProtocol extends ProtocolWithOptions> = OptionsByProtocol[TProtocol];\n\n\texport type StreamFunction<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> = (model: Model.TModel<TProtocol>, context: Message.Context, options?: Static<S>) => AssistantMessageEventStream;\n\n\texport type ProtocolStreamFunction<S extends TSchema = TSchema> = (\n\t\tmodel: Model.Info,\n\t\tcontext: Message.Context,\n\t\toptions?: Static<S>,\n\t) => AssistantMessageEventStream;\n\n\texport interface Protocol<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> {\n\t\tprotocol: TProtocol;\n\t\tstream: StreamFunction<TProtocol, S>;\n\t}\n\n\texport interface RegisteredProtocol<\n\t\tTProtocol extends Model.KnownProviderEnum = Model.KnownProviderEnum,\n\t\tS extends TSchema = TSchema,\n\t> {\n\t\tprotocol: TProtocol;\n\t\tstream: ProtocolStreamFunction<S>;\n\t}\n\n\ttype AnyRegisteredProtocol = RegisteredProtocol<Model.KnownProviderEnum, TSchema>;\n\n\ttype RegistryEntry = {\n\t\tprovider: AnyRegisteredProtocol;\n\t\tsourceId?: string;\n\t};\n\n\tconst protocolRegistry = new Map<Model.KnownProviderEnum, RegistryEntry>();\n\n\tfunction wrapStream<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\t\tprotocol: TProtocol,\n\t\tstream: StreamFunction<TProtocol, S>,\n\t): ProtocolStreamFunction<S> {\n\t\treturn (model, context, options) => {\n\t\t\tif (model.protocol !== protocol) {\n\t\t\t\tthrow new ProtocolMismatchError({\n\t\t\t\t\tactual: model.protocol,\n\t\t\t\t\texpected: protocol,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn stream(model as Model.TModel<TProtocol>, context, options);\n\t\t};\n\t}\n\n\texport function registerProtocolProvider<TProtocol extends Model.KnownProviderEnum, S extends TSchema = TSchema>(\n\t\tprovider: Protocol<TProtocol, S>,\n\t\tsourceId?: string,\n\t): void {\n\t\tconst registered: RegisteredProtocol<TProtocol, S> = {\n\t\t\tprotocol: provider.protocol,\n\t\t\tstream: wrapStream(provider.protocol, provider.stream),\n\t\t};\n\n\t\tprotocolRegistry.set(provider.protocol, {\n\t\t\tprovider: registered as AnyRegisteredProtocol,\n\t\t\tsourceId,\n\t\t});\n\t}\n\n\texport function getProtocolProvider(protocol: Model.KnownProviderEnum): AnyRegisteredProtocol | undefined {\n\t\treturn protocolRegistry.get(protocol)?.provider;\n\t}\n\n\texport function resolveProtocolProvider(model: Model.Info): AnyRegisteredProtocol {\n\t\tconst provider = getProtocolProvider(model.protocol);\n\t\tif (!provider) {\n\t\t\tthrow new ProviderProtocolNotFoundError({\n\t\t\t\tprotocol: model.protocol,\n\t\t\t});\n\t\t}\n\n\t\treturn provider;\n\t}\n\n\texport function getProtocolProviders(): AnyRegisteredProtocol[] {\n\t\treturn Array.from(protocolRegistry.values(), (entry) => entry.provider);\n\t}\n\n\texport function stream<TProtocol extends ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: OptionsFor<TProtocol>,\n\t): AssistantMessageEventStream {\n\t\tconst provider = resolveProtocolProvider(model);\n\t\treturn provider.stream(model, context, options);\n\t}\n\n\texport async function complete<TProtocol extends ProtocolWithOptions>(\n\t\tmodel: Model.TModel<TProtocol>,\n\t\tcontext: Message.Context,\n\t\toptions?: OptionsFor<TProtocol>,\n\t): Promise<Message.AssistantMessage> {\n\t\tconst s = stream(model, context, options);\n\t\treturn s.result();\n\t}\n\n\texport function unregisterProtocolProviders(sourceId: string): void {\n\t\tfor (const [protocol, entry] of protocolRegistry.entries()) {\n\t\t\tif (entry.sourceId === sourceId) {\n\t\t\t\tprotocolRegistry.delete(protocol);\n\t\t\t}\n\t\t}\n\t}\n\n\texport function clearProtocolProviders(): void {\n\t\tprotocolRegistry.clear();\n\t}\n}\n","import { Type, type Static } from \"typebox\";\nimport { type Model } from \"../model/model\";\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});\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, type Static } from \"typebox\";\nimport { Model } from \"../model/model\";\nimport type { Protocol } from \"./protocol\";\nimport { SharedOptions, ThinkingBudgets } from \"./shared\";\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 OpenRouterOptions = AISDKOptions<OpenRouterProviderSettings, { openrouter?: OpenRouterProviderOptions }>;\nexport type XaiOptions = AISDKOptions<XaiProviderSettings, { xai?: XaiLanguageOptions }>;\n\nexport type Options = Static<typeof Options>;\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.openrouter]: OpenRouterOptions;\n\t[Model.KnownProviderEnum.xai]: XaiOptions;\n}\n","/**\n * @description Defines the Generic event stream class for async iteration.\n */\n\nimport type { Event } from \"../event/event\";\nimport type { Message } from \"../message/message\";\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\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\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","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 { Model } from \"../model/model\";\nimport type { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { loadProviderFactory, packageForModel, resolveLanguageModel } from \"./registry\";\nimport { getEnvApiKey, mergeHeaders } from \"./runtime\";\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\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport { parseStreamingJson } from \"../utils/jsonparse\";\nimport { sanitizeSurrogates } from \"../utils/sanitize\";\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: \"image\", image: 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: \"image-data\" as const,\n\t\t\t\tdata: image.data,\n\t\t\t\tmediaType: image.mimeType,\n\t\t\t})),\n\t\t],\n\t};\n}\n\nfunction assistantMessages(message: Message.AssistantMessage): 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({ type: \"text\", text });\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) 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\tanthropic: { signature: part.thinkingSignature },\n\t\t\t\t};\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\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});\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\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(context.messages, model);\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));\n\t}\n\n\treturn messages;\n}\n\nexport function convertTools(tools?: Message.Tool[]): ToolSet | undefined {\n\tif (!tools || tools.length === 0) return;\n\n\tconst result: ToolSet = {};\n\tfor (const tool of tools) {\n\t\tresult[tool.name] = {\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: jsonSchema(tool.parameters as any),\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(usage: LanguageModelUsage | undefined, model: Model.Info): Message.AssistantMessage[\"usage\"] {\n\tconst cacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? usage?.cachedInputTokens ?? 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\ttotalTokens,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tModel.calculateCost(model, result);\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 { Message } from \"../message/message\";\nimport { Model } from \"../model/model\";\nimport { AssistantMessageEventStream } from \"../utils/eventstream\";\nimport { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { resolveAISDKLanguageModel } from \"./provider\";\nimport { formatThrownError } from \"./runtime\";\nimport { applyDefaultMaxTokens } from \"./shared\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tcreateAssistantMessage,\n\tmapFinishReason,\n\tmapUsage,\n\ttoolCallFromPart,\n\tupdateToolCallFromInput,\n\ttype StreamingToolCallBlock,\n} from \"./transform\";\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 === \"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};\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\") {\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 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(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): 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\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(output: Message.AssistantMessage, id: string, stream: AssistantMessageEventStream): 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\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\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): 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\tfinishTextBlock(output, part.id, stream);\n\t\t\tbreak;\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\tfinishThinkingBlock(output, part.id, stream);\n\t\t\tbreak;\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);\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);\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\toutput.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\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\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);\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 activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);\n\n\t\t\tlet params: Parameters<typeof streamText<ToolSet>>[0] = {\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);\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 { Model } from \"../model/model\";\nimport { Options } from \"./options\";\nimport { Protocol } from \"./protocol\";\nimport { stream } from \"./stream\";\n\nexport { Options } from \"./options\";\nexport * from \"./registry\";\nexport { stream } from \"./stream\";\nexport * from \"./transform\";\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.openrouter));\n\tProtocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));\n}\n","import { registerAISDKProtocols } from \"./index\";\n\nregisterAISDKProtocols();\n","import \"./llm/register\";\n\nimport type { Message } from \"./message/message\";\nimport type { Model } from \"./model/model\";\nimport { Protocol } from \"./llm/protocol\";\nimport type { AssistantMessageEventStream } from \"./utils/eventstream\";\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 { Message } from \"../message/message\";\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":";;;;;;;;AAIO,IAAA;;CACC,MAAM,oBAAA,SAAA,oBAAoBA,OAAK,OAAO;EAC5C,MAAMA,OAAK,QAAQ,OAAO;EAC1B,MAAMA,OAAK,QAAQ;EACnB,eAAeA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAC3C,CAAC;CAGK,MAAM,qBAAA,SAAA,qBAAqBA,OAAK,OAAO;EAC7C,MAAMA,OAAK,QAAQ,QAAQ;EAC3B,MAAMA,OAAK,QAAQ;EACnB,UAAUA,OAAK,QAAQ;EACvB,CAAC;CAGK,MAAM,wBAAA,SAAA,wBAAwBA,OAAK,OAAO;EAChD,MAAMA,OAAK,QAAQ,WAAW;EAC9B,UAAUA,OAAK,QAAQ;EACvB,mBAAmBA,OAAK,SAASA,OAAK,QAAQ,CAAC;EAI/C,UAAUA,OAAK,SAASA,OAAK,SAAS,CAAC;EACvC,CAAC;CAGK,MAAM,qBAAA,SAAA,qBAAqBA,OAAK,OAAO;EAC7C,MAAMA,OAAK,QAAQ,WAAW;EAC9B,QAAQA,OAAK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AsB,MAAM,cAAc;;;;;AAMlD,SAAgB,sBACf,MACA,eAC2B;AAC3B,QAAO,eACN,KAAK,YACL,cAAc,SACd,SAAS,cAAc,KAAK,GAC5B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeworksh/aikit",
3
- "version": "0.4.1-dev.20260530184501",
3
+ "version": "0.4.1-dev.20260530191957",
4
4
  "description": "Toolkit for building AI agents and agent harness.",
5
5
  "keywords": [
6
6
  "agent",