@codeworksh/aikit 0.6.0-dev.20260613095948 → 0.7.0

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 CHANGED
@@ -1,580 +1,673 @@
1
- import { d as NamedError, i as packageForModel, o as resolveLanguageModel, r as loadProviderFactory, s as Model } from "./registry-DUKrGxt4.mjs";
2
- import { n as createOpenAICodex, r as openaiCodex } from "./openai-codex-CZrBnLAJ.mjs";
3
- import Type$1, { Type, Type as Type$2 } from "typebox";
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { E as NamedError, _ as getProviders, c as APIMethodEnumSchema, d as KnownProviderEnumSchema, f as ProviderInfo, g as getModels, h as getModel, i as packageForModel, l as ActiveThinkingLevel, m as clampThinkingLevel, o as resolveLanguageModel, p as calculateCost, r as loadProviderFactory, u as KnownProviderEnum, v as model_exports, x as registry, y as modelsAreEqual } from "./registry-CMkIE_B4.mjs";
3
+ import { g as shortHash, n as createOpenAICodex, r as openaiCodex, v as openAICodexTools, x as resolveOpenAICodexToolConstraint } from "./openai-codex-_3XkJ4bs.mjs";
4
+ import Type$2, { Type, Type as Type$1 } from "typebox";
4
5
  import { uuidv7 } from "uuidv7";
5
6
  import Value from "typebox/value";
6
7
  import { jsonSchema, streamText } from "ai";
7
8
  import { parse } from "partial-json";
8
9
  import Schema from "typebox/schema";
9
10
  //#region src/message/message.ts
10
- let Message;
11
- (function(_Message) {
12
- const TextContentSchema = _Message.TextContentSchema = Type$1.Object({
13
- type: Type$1.Literal("text"),
14
- text: Type$1.String(),
15
- textSignature: Type$1.Optional(Type$1.String())
16
- });
17
- const ImageContentSchema = _Message.ImageContentSchema = Type$1.Object({
18
- type: Type$1.Literal("image"),
19
- data: Type$1.String(),
20
- mimeType: Type$1.String()
21
- });
22
- const ThinkingContentSchema = _Message.ThinkingContentSchema = Type$1.Object({
23
- type: Type$1.Literal("thinking"),
24
- thinking: Type$1.String(),
25
- thinkingSignature: Type$1.Optional(Type$1.String()),
26
- redacted: Type$1.Optional(Type$1.Boolean())
27
- });
28
- const ToolCallBaseSchema = _Message.ToolCallBaseSchema = Type$1.Object({
29
- type: Type$1.Literal("toolCall"),
30
- callID: Type$1.String(),
31
- name: Type$1.String(),
32
- arguments: Type$1.Record(Type$1.String(), Type$1.Any()),
33
- thoughtSignature: Type$1.Optional(Type$1.String()),
34
- time: Type$1.Object({
35
- start: Type$1.Number(),
36
- end: Type$1.Number()
37
- })
38
- });
39
- const ToolSuccessResult = _Message.ToolSuccessResult = Type$1.Object({
40
- content: Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema])),
41
- details: Type$1.Optional(Type$1.Any()),
42
- isError: Type$1.Literal(false)
43
- });
44
- const ToolErrorResult = _Message.ToolErrorResult = Type$1.Object({
45
- content: Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema])),
46
- details: Type$1.Optional(Type$1.Any()),
47
- isError: Type$1.Literal(true)
48
- });
49
- const ToolRunningPartial = _Message.ToolRunningPartial = Type$1.Object({
50
- content: Type$1.Optional(Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema]))),
51
- details: Type$1.Optional(Type$1.Any())
52
- });
53
- const ToolStatusEnum = _Message.ToolStatusEnum = {
54
- pending: "pending",
55
- running: "running",
56
- completed: "completed",
57
- error: "error",
58
- skipped: "skipped",
59
- aborted: "aborted"
11
+ var message_exports = /* @__PURE__ */ __exportAll({
12
+ AssistantMessageSchema: () => AssistantMessageSchema,
13
+ ConstrainedSamplingSchema: () => ConstrainedSamplingSchema,
14
+ ContextSchema: () => ContextSchema,
15
+ GrammarVariantsSchema: () => GrammarVariantsSchema,
16
+ ImageContentSchema: () => ImageContentSchema,
17
+ MessageSchema: () => MessageSchema,
18
+ StopReasonSchema: () => StopReasonSchema,
19
+ TextContentSchema: () => TextContentSchema,
20
+ ThinkingContentSchema: () => ThinkingContentSchema,
21
+ ToolAbortedSchema: () => ToolAbortedSchema,
22
+ ToolCallAbortedPartSchema: () => ToolCallAbortedPartSchema,
23
+ ToolCallBaseSchema: () => ToolCallBaseSchema,
24
+ ToolCallCompletedPartSchema: () => ToolCallCompletedPartSchema,
25
+ ToolCallErrorPartSchema: () => ToolCallErrorPartSchema,
26
+ ToolCallInFlightSchema: () => ToolCallInFlightSchema,
27
+ ToolCallPendingPartSchema: () => ToolCallPendingPartSchema,
28
+ ToolCallRunningPartSchema: () => ToolCallRunningPartSchema,
29
+ ToolCallSchema: () => ToolCallSchema,
30
+ ToolCallSkippedPartSchema: () => ToolCallSkippedPartSchema,
31
+ ToolCallTerminalPartSchema: () => ToolCallTerminalPartSchema,
32
+ ToolCompletedSchema: () => ToolCompletedSchema,
33
+ ToolErrorResult: () => ToolErrorResult,
34
+ ToolErrorSchema: () => ToolErrorSchema,
35
+ ToolRunningPartial: () => ToolRunningPartial,
36
+ ToolRunningSchema: () => ToolRunningSchema,
37
+ ToolSchema: () => ToolSchema,
38
+ ToolSkippedSchema: () => ToolSkippedSchema,
39
+ ToolStatusEnum: () => ToolStatusEnum,
40
+ ToolSuccessResult: () => ToolSuccessResult,
41
+ UsageSchema: () => UsageSchema,
42
+ UserMessageSchema: () => UserMessageSchema,
43
+ createAssistantMessage: () => createAssistantMessage$1,
44
+ createMessageId: () => createMessageId,
45
+ createUserMessage: () => createUserMessage,
46
+ defineTool: () => defineTool,
47
+ transformMessages: () => transformMessages
48
+ });
49
+ const TextContentSchema = Type$2.Object({
50
+ type: Type$2.Literal("text"),
51
+ text: Type$2.String(),
52
+ textSignature: Type$2.Optional(Type$2.String())
53
+ });
54
+ const ImageContentSchema = Type$2.Object({
55
+ type: Type$2.Literal("image"),
56
+ data: Type$2.String(),
57
+ mimeType: Type$2.String()
58
+ });
59
+ const ThinkingContentSchema = Type$2.Object({
60
+ type: Type$2.Literal("thinking"),
61
+ thinking: Type$2.String(),
62
+ thinkingSignature: Type$2.Optional(Type$2.String()),
63
+ /** When true, the thinking content was redacted by safety filters. The opaque
64
+ * encrypted payload is stored in `thinkingSignature` so it can be passed back
65
+ * to the API for multi-turn continuity. */
66
+ redacted: Type$2.Optional(Type$2.Boolean())
67
+ });
68
+ const ToolCallBaseSchema = Type$2.Object({
69
+ type: Type$2.Literal("toolCall"),
70
+ callID: Type$2.String(),
71
+ name: Type$2.String(),
72
+ arguments: Type$2.Record(Type$2.String(), Type$2.Any()),
73
+ thoughtSignature: Type$2.Optional(Type$2.String()),
74
+ namespace: Type$2.Optional(Type$2.String()),
75
+ /** Names from Context.tools that became available after this tool result. */
76
+ addedToolNames: Type$2.Optional(Type$2.Array(Type$2.String())),
77
+ time: Type$2.Object({
78
+ start: Type$2.Number(),
79
+ end: Type$2.Number()
80
+ })
81
+ });
82
+ const ToolSuccessResult = Type$2.Object({
83
+ content: Type$2.Array(Type$2.Union([TextContentSchema, ImageContentSchema])),
84
+ details: Type$2.Optional(Type$2.Any()),
85
+ isError: Type$2.Literal(false)
86
+ });
87
+ const ToolErrorResult = Type$2.Object({
88
+ content: Type$2.Array(Type$2.Union([TextContentSchema, ImageContentSchema])),
89
+ details: Type$2.Optional(Type$2.Any()),
90
+ isError: Type$2.Literal(true)
91
+ });
92
+ const ToolRunningPartial = Type$2.Object({
93
+ content: Type$2.Optional(Type$2.Array(Type$2.Union([TextContentSchema, ImageContentSchema]))),
94
+ details: Type$2.Optional(Type$2.Any())
95
+ });
96
+ const ToolStatusEnum = {
97
+ pending: "pending",
98
+ running: "running",
99
+ completed: "completed",
100
+ error: "error",
101
+ skipped: "skipped",
102
+ aborted: "aborted"
103
+ };
104
+ const ToolRunningSchema = Type$2.Object({
105
+ status: Type$2.Literal(ToolStatusEnum.running),
106
+ partial: Type$2.Optional(ToolRunningPartial)
107
+ });
108
+ const ToolCompletedSchema = Type$2.Object({
109
+ status: Type$2.Literal(ToolStatusEnum.completed),
110
+ result: ToolSuccessResult
111
+ });
112
+ const ToolErrorSchema = Type$2.Object({
113
+ status: Type$2.Literal(ToolStatusEnum.error),
114
+ result: ToolErrorResult
115
+ });
116
+ const ToolSkippedSchema = Type$2.Object({
117
+ status: Type$2.Literal(ToolStatusEnum.skipped),
118
+ result: ToolErrorResult
119
+ });
120
+ const ToolAbortedSchema = Type$2.Object({
121
+ status: Type$2.Literal(ToolStatusEnum.aborted),
122
+ result: ToolErrorResult
123
+ });
124
+ const ToolCallPendingPartSchema = Type$2.Intersect([ToolCallBaseSchema, Type$2.Object({ status: Type$2.Literal(ToolStatusEnum.pending) })]);
125
+ const ToolCallRunningPartSchema = Type$2.Evaluate(Type$2.Intersect([ToolCallBaseSchema, ToolRunningSchema]));
126
+ const ToolCallCompletedPartSchema = Type$2.Evaluate(Type$2.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));
127
+ const ToolCallErrorPartSchema = Type$2.Evaluate(Type$2.Intersect([ToolCallBaseSchema, ToolErrorSchema]));
128
+ const ToolCallSkippedPartSchema = Type$2.Evaluate(Type$2.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));
129
+ const ToolCallAbortedPartSchema = Type$2.Evaluate(Type$2.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));
130
+ const ToolCallTerminalPartSchema = Type$2.Union([
131
+ ToolCallCompletedPartSchema,
132
+ ToolCallErrorPartSchema,
133
+ ToolCallSkippedPartSchema,
134
+ ToolCallAbortedPartSchema
135
+ ]);
136
+ const ToolCallInFlightSchema = Type$2.Object({
137
+ callID: Type$2.String(),
138
+ name: Type$2.String(),
139
+ rawArgs: Type$2.Record(Type$2.String(), Type$2.Unknown()),
140
+ args: Type$2.Optional(Type$2.Unknown())
141
+ });
142
+ const ToolCallSchema = Type$2.Union([
143
+ ToolCallPendingPartSchema,
144
+ ToolCallRunningPartSchema,
145
+ ToolCallTerminalPartSchema
146
+ ]);
147
+ const UsageSchema = Type$2.Object({
148
+ input: Type$2.Number(),
149
+ output: Type$2.Number(),
150
+ cacheRead: Type$2.Number(),
151
+ cacheWrite: Type$2.Number(),
152
+ reasoning: Type$2.Optional(Type$2.Number()),
153
+ totalTokens: Type$2.Number(),
154
+ cost: Type$2.Object({
155
+ input: Type$2.Number(),
156
+ output: Type$2.Number(),
157
+ cacheRead: Type$2.Number(),
158
+ cacheWrite: Type$2.Number(),
159
+ total: Type$2.Number()
160
+ })
161
+ });
162
+ const StopReasonSchema = Type$2.Union([
163
+ Type$2.Literal("stop"),
164
+ Type$2.Literal("length"),
165
+ Type$2.Literal("toolUse"),
166
+ Type$2.Literal("error"),
167
+ Type$2.Literal("aborted")
168
+ ]);
169
+ const UserMessageSchema = Type$2.Object({
170
+ messageId: Type$2.String(),
171
+ role: Type$2.Literal("user"),
172
+ time: Type$2.Object({ created: Type$2.Number() }),
173
+ parts: Type$2.Array(Type$2.Union([TextContentSchema, ImageContentSchema]))
174
+ });
175
+ const AssistantMessageSchema = Type$2.Object({
176
+ role: Type$2.Literal("assistant"),
177
+ protocol: KnownProviderEnumSchema,
178
+ provider: ProviderInfo,
179
+ model: Type$2.String(),
180
+ usage: UsageSchema,
181
+ stopReason: StopReasonSchema,
182
+ errorMessage: Type$2.Optional(Type$2.String()),
183
+ time: Type$2.Object({
184
+ created: Type$2.Number(),
185
+ completed: Type$2.Number()
186
+ }),
187
+ parts: Type$2.Array(Type$2.Union([
188
+ TextContentSchema,
189
+ ImageContentSchema,
190
+ ThinkingContentSchema,
191
+ ToolCallSchema
192
+ ])),
193
+ responseId: Type$2.Optional(Type$2.String()),
194
+ responseModel: Type$2.Optional(Type$2.String()),
195
+ messageId: Type$2.String()
196
+ });
197
+ const MessageSchema = Type$2.Union([UserMessageSchema, AssistantMessageSchema]);
198
+ function createMessageId() {
199
+ return uuidv7();
200
+ }
201
+ function createUserMessage(message) {
202
+ const { messageId = createMessageId(), ...rest } = message;
203
+ return {
204
+ messageId,
205
+ ...rest
60
206
  };
61
- const ToolRunningSchema = _Message.ToolRunningSchema = Type$1.Object({
62
- status: Type$1.Literal(ToolStatusEnum.running),
63
- partial: Type$1.Optional(ToolRunningPartial)
64
- });
65
- const ToolCompletedSchema = _Message.ToolCompletedSchema = Type$1.Object({
66
- status: Type$1.Literal(ToolStatusEnum.completed),
67
- result: ToolSuccessResult
68
- });
69
- const ToolErrorSchema = _Message.ToolErrorSchema = Type$1.Object({
70
- status: Type$1.Literal(ToolStatusEnum.error),
71
- result: ToolErrorResult
72
- });
73
- const ToolSkippedSchema = _Message.ToolSkippedSchema = Type$1.Object({
74
- status: Type$1.Literal(ToolStatusEnum.skipped),
75
- result: ToolErrorResult
76
- });
77
- const ToolAbortedSchema = _Message.ToolAbortedSchema = Type$1.Object({
78
- status: Type$1.Literal(ToolStatusEnum.aborted),
79
- result: ToolErrorResult
80
- });
81
- const ToolCallPendingPart = Type$1.Intersect([ToolCallBaseSchema, Type$1.Object({ status: Type$1.Literal(ToolStatusEnum.pending) })]);
82
- const ToolCallRunningPart = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolRunningSchema]));
83
- const ToolCallCompletedPart = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));
84
- const ToolCallErrorPart = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolErrorSchema]));
85
- const ToolCallSkippedPart = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));
86
- const ToolCallAbortedPart = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));
87
- _Message.ToolCallInFlightSchema = Type$1.Object({
88
- callID: Type$1.String(),
89
- name: Type$1.String(),
90
- rawArgs: Type$1.Record(Type$1.String(), Type$1.Unknown()),
91
- args: Type$1.Optional(Type$1.Unknown())
92
- });
93
- const ToolCallSchema = _Message.ToolCallSchema = Type$1.Union([
94
- ToolCallPendingPart,
95
- ToolCallRunningPart,
96
- ToolCallCompletedPart,
97
- ToolCallErrorPart,
98
- ToolCallSkippedPart,
99
- ToolCallAbortedPart
100
- ]);
101
- const UsageSchema = _Message.UsageSchema = Type$1.Object({
102
- input: Type$1.Number(),
103
- output: Type$1.Number(),
104
- cacheRead: Type$1.Number(),
105
- cacheWrite: Type$1.Number(),
106
- totalTokens: Type$1.Number(),
107
- cost: Type$1.Object({
108
- input: Type$1.Number(),
109
- output: Type$1.Number(),
110
- cacheRead: Type$1.Number(),
111
- cacheWrite: Type$1.Number(),
112
- total: Type$1.Number()
113
- })
114
- });
115
- const StopReasonSchema = _Message.StopReasonSchema = Type$1.Union([
116
- Type$1.Literal("stop"),
117
- Type$1.Literal("length"),
118
- Type$1.Literal("toolUse"),
119
- Type$1.Literal("error"),
120
- Type$1.Literal("aborted")
121
- ]);
122
- const UserMessageSchema = _Message.UserMessageSchema = Type$1.Object({
123
- messageId: Type$1.String(),
124
- role: Type$1.Literal("user"),
125
- time: Type$1.Object({ created: Type$1.Number() }),
126
- parts: Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema]))
127
- });
128
- const AssistantMessageSchema = _Message.AssistantMessageSchema = Type$1.Object({
129
- role: Type$1.Literal("assistant"),
130
- protocol: Model.KnownProviderEnumSchema,
131
- provider: Model.ProviderInfo,
132
- model: Type$1.String(),
133
- usage: UsageSchema,
134
- stopReason: StopReasonSchema,
135
- errorMessage: Type$1.Optional(Type$1.String()),
136
- time: Type$1.Object({
137
- created: Type$1.Number(),
138
- completed: Type$1.Number()
139
- }),
140
- parts: Type$1.Array(Type$1.Union([
141
- TextContentSchema,
142
- ImageContentSchema,
143
- ThinkingContentSchema,
144
- ToolCallSchema
145
- ])),
146
- responseId: Type$1.Optional(Type$1.String()),
147
- responseModel: Type$1.Optional(Type$1.String()),
148
- messageId: Type$1.String()
149
- });
150
- const MessageSchema = _Message.MessageSchema = Type$1.Union([UserMessageSchema, AssistantMessageSchema]);
151
- function createMessageId() {
152
- return uuidv7();
153
- }
154
- _Message.createMessageId = createMessageId;
155
- function createUserMessage(message) {
156
- const { messageId = createMessageId(), ...rest } = message;
157
- return {
158
- messageId,
159
- ...rest
160
- };
161
- }
162
- _Message.createUserMessage = createUserMessage;
163
- function createAssistantMessage(message) {
164
- const { messageId = createMessageId(), ...rest } = message;
165
- return {
166
- messageId,
167
- ...rest
168
- };
169
- }
170
- _Message.createAssistantMessage = createAssistantMessage;
171
- const ToolSchema = _Message.ToolSchema = Type$1.Object({
172
- name: Type$1.String(),
173
- description: Type$1.String(),
174
- parameters: Type$1.Unsafe({})
175
- });
176
- function defineTool(tool) {
177
- return tool;
178
- }
179
- _Message.defineTool = defineTool;
180
- _Message.ContextSchema = Type$1.Object({
181
- systemPrompt: Type$1.Optional(Type$1.String()),
182
- messages: Type$1.Array(MessageSchema),
183
- tools: Type$1.Optional(Type$1.Array(ToolSchema))
184
- });
185
- function isUnresolvedToolCall(toolCall) {
186
- return toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;
187
- }
188
- function syntheticSkippedToolCall(toolCall) {
189
- const { status: _status, partial: _partial, ...base } = toolCall;
190
- return {
191
- ...base,
192
- status: ToolStatusEnum.skipped,
193
- result: {
194
- content: [{
207
+ }
208
+ function createAssistantMessage$1(message) {
209
+ const { messageId = createMessageId(), ...rest } = message;
210
+ return {
211
+ messageId,
212
+ ...rest
213
+ };
214
+ }
215
+ const GrammarVariantsSchema = Type$2.Partial(Type$2.Object({
216
+ openai_lark: Type$2.String(),
217
+ openai_regex: Type$2.String()
218
+ }));
219
+ const ConstrainedSamplingSchema = Type$2.Union([Type$2.Object({
220
+ type: Type$2.Literal("json_schema"),
221
+ strict: Type$2.Union([Type$2.Literal("prefer"), Type$2.Literal("require")])
222
+ }), Type$2.Object({
223
+ type: Type$2.Literal("grammar"),
224
+ variants: GrammarVariantsSchema
225
+ })]);
226
+ /**
227
+ * Generic tool definition with typed parameter schema.
228
+ * Usage:
229
+ *
230
+ * const search = Message.defineTool({
231
+ * name: "search",
232
+ * description: "Search documents",
233
+ * parameters: Type.Object({
234
+ * query: Type.String(),
235
+ * limit: Type.Optional(Type.Number()),
236
+ * }),
237
+ * });
238
+ *
239
+ * type SearchParams = Static<typeof search.parameters>;
240
+ */
241
+ const ToolSchema = Type$2.Object({
242
+ name: Type$2.String(),
243
+ description: Type$2.String(),
244
+ parameters: Type$2.Unsafe({}),
245
+ constrainedSampling: Type$2.Optional(Type$2.Union([Type$2.Literal(false), ConstrainedSamplingSchema]))
246
+ });
247
+ function defineTool(tool) {
248
+ return tool;
249
+ }
250
+ const ContextSchema = Type$2.Object({
251
+ systemPrompt: Type$2.Optional(Type$2.String()),
252
+ messages: Type$2.Array(MessageSchema),
253
+ tools: Type$2.Optional(Type$2.Array(ToolSchema))
254
+ });
255
+ function isUnresolvedToolCall(toolCall) {
256
+ return toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;
257
+ }
258
+ function syntheticSkippedToolCall(toolCall) {
259
+ const { status: _status, partial: _partial, ...base } = toolCall;
260
+ return {
261
+ ...base,
262
+ status: ToolStatusEnum.skipped,
263
+ result: {
264
+ content: [{
265
+ type: "text",
266
+ text: "No result provided"
267
+ }],
268
+ isError: true
269
+ },
270
+ time: {
271
+ ...toolCall.time,
272
+ end: Math.max(toolCall.time.end, Date.now())
273
+ }
274
+ };
275
+ }
276
+ function transformMessages(messages, model, normalizeToolCallId) {
277
+ const toolCallIDMap = /* @__PURE__ */ new Map();
278
+ const transformed = [];
279
+ for (const msg of messages) {
280
+ if (msg.role === "user") {
281
+ transformed.push(msg);
282
+ continue;
283
+ }
284
+ const assistantMsg = msg;
285
+ const isSameModel = assistantMsg.provider.id === model.provider.id && assistantMsg.protocol === model.protocol && assistantMsg.model === model.id;
286
+ const parts = assistantMsg.parts.flatMap((block) => {
287
+ if (block.type === "thinking") {
288
+ if (isSameModel && block.thinkingSignature) return block;
289
+ if (!block.thinking || block.thinking.trim() === "") return [];
290
+ if (isSameModel) return block;
291
+ return {
195
292
  type: "text",
196
- text: "No result provided"
197
- }],
198
- isError: true
199
- },
200
- time: {
201
- ...toolCall.time,
202
- end: Math.max(toolCall.time.end, Date.now())
293
+ text: block.thinking
294
+ };
203
295
  }
204
- };
205
- }
206
- function transformMessages(messages, model, normalizeToolCallId) {
207
- const toolCallIDMap = /* @__PURE__ */ new Map();
208
- const transformed = [];
209
- for (const msg of messages) {
210
- if (msg.role === "user") {
211
- transformed.push(msg);
212
- continue;
296
+ if (block.type === "text") {
297
+ if (isSameModel) return block;
298
+ return {
299
+ type: "text",
300
+ text: block.text
301
+ };
213
302
  }
214
- const assistantMsg = msg;
215
- const isSameModel = assistantMsg.provider.id === model.provider.id && assistantMsg.protocol === model.protocol && assistantMsg.model === model.id;
216
- const parts = assistantMsg.parts.flatMap((block) => {
217
- if (block.type === "thinking") {
218
- if (isSameModel && block.thinkingSignature) return block;
219
- if (!block.thinking || block.thinking.trim() === "") return [];
220
- if (isSameModel) return block;
221
- return {
222
- type: "text",
223
- text: block.thinking
224
- };
225
- }
226
- if (block.type === "text") {
227
- if (isSameModel) return block;
228
- return {
229
- type: "text",
230
- text: block.text
231
- };
303
+ if (block.type === "toolCall") {
304
+ const toolCall = block;
305
+ let normalizedToolCall = toolCall;
306
+ if (!isSameModel && toolCall.thoughtSignature) {
307
+ normalizedToolCall = { ...toolCall };
308
+ delete normalizedToolCall.thoughtSignature;
232
309
  }
233
- if (block.type === "toolCall") {
234
- const toolCall = block;
235
- let normalizedToolCall = toolCall;
236
- if (!isSameModel && toolCall.thoughtSignature) {
237
- normalizedToolCall = { ...toolCall };
238
- delete normalizedToolCall.thoughtSignature;
310
+ const normalizedID = toolCallIDMap.get(block.callID);
311
+ if (normalizedID && normalizedID !== block.callID) normalizedToolCall = {
312
+ ...normalizedToolCall,
313
+ callID: normalizedID
314
+ };
315
+ else if (!isSameModel && normalizeToolCallId) {
316
+ const nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);
317
+ if (nextID !== toolCall.callID) {
318
+ toolCallIDMap.set(toolCall.callID, nextID);
319
+ normalizedToolCall = {
320
+ ...normalizedToolCall,
321
+ callID: nextID
322
+ };
239
323
  }
240
- const normalizedID = toolCallIDMap.get(block.callID);
241
- if (normalizedID && normalizedID !== block.callID) normalizedToolCall = {
242
- ...normalizedToolCall,
243
- callID: normalizedID
244
- };
245
- else if (!isSameModel && normalizeToolCallId) {
246
- const nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);
247
- if (nextID !== toolCall.callID) {
248
- toolCallIDMap.set(toolCall.callID, nextID);
249
- normalizedToolCall = {
250
- ...normalizedToolCall,
251
- callID: nextID
252
- };
253
- }
254
- }
255
- return normalizedToolCall;
256
324
  }
257
- return block;
258
- }).map((block) => {
259
- if (block.type === "toolCall" && isUnresolvedToolCall(block)) return syntheticSkippedToolCall(block);
260
- return block;
261
- });
262
- transformed.push({
263
- ...assistantMsg,
264
- parts
265
- });
266
- }
267
- return transformed;
325
+ return normalizedToolCall;
326
+ }
327
+ return block;
328
+ }).map((block) => {
329
+ if (block.type === "toolCall" && isUnresolvedToolCall(block)) return syntheticSkippedToolCall(block);
330
+ return block;
331
+ });
332
+ transformed.push({
333
+ ...assistantMsg,
334
+ parts
335
+ });
268
336
  }
269
- _Message.transformMessages = transformMessages;
270
- })(Message || (Message = {}));
337
+ return transformed;
338
+ }
271
339
  //#endregion
272
340
  //#region src/event/event.ts
273
- let Event;
274
- (function(_Event) {
275
- const LLMMessageEventType = _Event.LLMMessageEventType = {
276
- start: "start",
277
- textStart: "text.start",
278
- textDelta: "text.delta",
279
- textEnd: "text.end",
280
- thinkingStart: "thinking.start",
281
- thinkingDelta: "thinking.delta",
282
- thinkingEnd: "thinking.end",
283
- toolcallStart: "toolcall.start",
284
- toolcallDelta: "toolcall.delta",
285
- toolcallEnd: "toolcall.end",
286
- toolcallFinal: "toolcall.final",
287
- done: "done",
288
- error: "error"
289
- };
290
- _Event.LLMMessageEventSchema = Type$1.Union([
291
- Type$1.Object({
292
- type: Type$1.Literal(LLMMessageEventType.start),
293
- partial: Message.AssistantMessageSchema
294
- }),
295
- Type$1.Object({
296
- type: Type$1.Literal(LLMMessageEventType.textStart),
297
- partIndex: Type$1.Number(),
298
- partial: Message.AssistantMessageSchema
299
- }),
300
- Type$1.Object({
301
- type: Type$1.Literal(LLMMessageEventType.textDelta),
302
- partIndex: Type$1.Number(),
303
- delta: Type$1.String(),
304
- partial: Message.AssistantMessageSchema
305
- }),
306
- Type$1.Object({
307
- type: Type$1.Literal(LLMMessageEventType.textEnd),
308
- partIndex: Type$1.Number(),
309
- content: Type$1.String(),
310
- partial: Message.AssistantMessageSchema
311
- }),
312
- Type$1.Object({
313
- type: Type$1.Literal(LLMMessageEventType.thinkingStart),
314
- partIndex: Type$1.Number(),
315
- partial: Message.AssistantMessageSchema
316
- }),
317
- Type$1.Object({
318
- type: Type$1.Literal(LLMMessageEventType.thinkingDelta),
319
- partIndex: Type$1.Number(),
320
- delta: Type$1.String(),
321
- partial: Message.AssistantMessageSchema
322
- }),
323
- Type$1.Object({
324
- type: Type$1.Literal(LLMMessageEventType.thinkingEnd),
325
- partIndex: Type$1.Number(),
326
- content: Type$1.String(),
327
- partial: Message.AssistantMessageSchema
328
- }),
329
- Type$1.Object({
330
- type: Type$1.Literal(LLMMessageEventType.toolcallStart),
331
- partIndex: Type$1.Number(),
332
- partial: Message.AssistantMessageSchema
333
- }),
334
- Type$1.Object({
335
- type: Type$1.Literal(LLMMessageEventType.toolcallDelta),
336
- partIndex: Type$1.Number(),
337
- delta: Type$1.String(),
338
- partial: Message.AssistantMessageSchema
339
- }),
340
- Type$1.Object({
341
- type: Type$1.Literal(LLMMessageEventType.toolcallEnd),
342
- partIndex: Type$1.Number(),
343
- toolCall: Message.ToolCallSchema,
344
- partial: Message.AssistantMessageSchema
345
- }),
346
- Type$1.Object({
347
- type: Type$1.Literal(LLMMessageEventType.toolcallFinal),
348
- partIndex: Type$1.Number(),
349
- toolCall: Message.ToolCallSchema,
350
- partial: Message.AssistantMessageSchema
351
- }),
352
- Type$1.Object({
353
- type: Type$1.Literal(LLMMessageEventType.done),
354
- reason: Type$1.Union([
355
- Type$1.Literal("stop"),
356
- Type$1.Literal("length"),
357
- Type$1.Literal("toolUse")
358
- ]),
359
- message: Message.AssistantMessageSchema
360
- }),
361
- Type$1.Object({
362
- type: Type$1.Literal(LLMMessageEventType.error),
363
- reason: Type$1.Union([Type$1.Literal("aborted"), Type$1.Literal("error")]),
364
- error: Message.AssistantMessageSchema
365
- })
366
- ]);
367
- const AgentEventType = _Event.AgentEventType = {
368
- agentStart: "agent.start",
369
- agentEnd: "agent.end",
370
- turnStart: "turn.start",
371
- turnEnd: "turn.end",
372
- messageStart: "message.start",
373
- messagePartStart: "message.part.start",
374
- messagePartUpdate: "message.part.update",
375
- messagePartEnd: "message.part.end",
376
- messageUpdate: "message.update",
377
- messageEnd: "message.end",
378
- toolExecutionStart: "tool.execution.start",
379
- toolExecutionUpdate: "tool.execution.update",
380
- toolExecutionEnd: "tool.execution.end"
381
- };
382
- const UserMessagePart = Type$1.Union([Message.TextContentSchema, Message.ImageContentSchema]);
383
- const AssistantMessagePart = Type$1.Union([
384
- Message.TextContentSchema,
385
- Message.ImageContentSchema,
386
- Message.ThinkingContentSchema,
387
- Message.ToolCallSchema
388
- ]);
389
- const UserMessagePartStart = Type$1.Object({
390
- type: Type$1.Literal(AgentEventType.messagePartStart),
391
- message: Message.UserMessageSchema,
392
- partIndex: Type$1.Number(),
393
- part: UserMessagePart
394
- });
395
- const UserMessagePartEnd = Type$1.Object({
396
- type: Type$1.Literal(AgentEventType.messagePartEnd),
397
- message: Message.UserMessageSchema,
398
- partIndex: Type$1.Number(),
399
- part: UserMessagePart
400
- });
401
- const AssistantMessagePartStart = Type$1.Object({
402
- type: Type$1.Literal(AgentEventType.messagePartStart),
403
- message: Message.AssistantMessageSchema,
404
- partIndex: Type$1.Number(),
405
- part: AssistantMessagePart
406
- });
407
- const AssistantMessagePartLLMUpdate = Type$1.Object({
408
- type: Type$1.Literal(AgentEventType.messagePartUpdate),
409
- message: Message.AssistantMessageSchema,
410
- partIndex: Type$1.Number(),
411
- part: AssistantMessagePart,
412
- source: Type$1.Literal("llm")
413
- });
414
- const AssistantMessagePartToolUpdate = Type$1.Object({
415
- type: Type$1.Literal(AgentEventType.messagePartUpdate),
416
- message: Message.AssistantMessageSchema,
417
- partIndex: Type$1.Number(),
418
- part: AssistantMessagePart,
419
- source: Type$1.Literal("tool")
420
- });
421
- const AssistantMessagePartEnd = Type$1.Object({
422
- type: Type$1.Literal(AgentEventType.messagePartEnd),
423
- message: Message.AssistantMessageSchema,
424
- partIndex: Type$1.Number(),
425
- part: AssistantMessagePart
426
- });
427
- const ToolExecutionStartSchema = Type$1.Evaluate(Type$1.Intersect([Message.ToolCallInFlightSchema, Type$1.Object({ type: Type$1.Literal(AgentEventType.toolExecutionStart) })]));
428
- const ToolExecutionUpdateSchema = Type$1.Evaluate(Type$1.Intersect([
429
- Message.ToolCallInFlightSchema,
430
- Type$1.Object({ type: Type$1.Literal(AgentEventType.toolExecutionUpdate) }),
431
- Message.ToolRunningSchema
432
- ]));
433
- const ToolExecutionEndSchema = Type$1.Evaluate(Type$1.Intersect([
434
- Message.ToolCallInFlightSchema,
435
- Type$1.Object({ type: Type$1.Literal(AgentEventType.toolExecutionEnd) }),
436
- Type$1.Union([Message.ToolCompletedSchema, Message.ToolErrorSchema])
437
- ]));
438
- _Event.AgentEventSchema = Type$1.Union([
439
- Type$1.Object({ type: Type$1.Literal(AgentEventType.agentStart) }),
440
- Type$1.Object({
441
- type: Type$1.Literal(AgentEventType.agentEnd),
442
- messages: Type$1.Array(Message.MessageSchema)
443
- }),
444
- Type$1.Object({ type: Type$1.Literal(AgentEventType.turnStart) }),
445
- Type$1.Object({
446
- type: Type$1.Literal(AgentEventType.turnEnd),
447
- message: Message.AssistantMessageSchema
448
- }),
449
- Type$1.Object({
450
- type: Type$1.Literal(AgentEventType.messageStart),
451
- message: Message.MessageSchema
452
- }),
453
- Type$1.Union([UserMessagePartStart, UserMessagePartEnd]),
454
- Type$1.Union([
455
- AssistantMessagePartStart,
456
- AssistantMessagePartLLMUpdate,
457
- AssistantMessagePartToolUpdate,
458
- AssistantMessagePartEnd
341
+ var event_exports = /* @__PURE__ */ __exportAll({
342
+ AgentEventSchema: () => AgentEventSchema,
343
+ AgentEventType: () => AgentEventType,
344
+ LLMMessageEventSchema: () => LLMMessageEventSchema,
345
+ LLMMessageEventType: () => LLMMessageEventType
346
+ });
347
+ const LLMMessageEventType = {
348
+ start: "start",
349
+ textStart: "text.start",
350
+ textDelta: "text.delta",
351
+ textEnd: "text.end",
352
+ thinkingStart: "thinking.start",
353
+ thinkingDelta: "thinking.delta",
354
+ thinkingEnd: "thinking.end",
355
+ toolcallStart: "toolcall.start",
356
+ toolcallDelta: "toolcall.delta",
357
+ toolcallEnd: "toolcall.end",
358
+ toolcallFinal: "toolcall.final",
359
+ done: "done",
360
+ error: "error"
361
+ };
362
+ /**
363
+ * Event protocol for AssistantMessageEventStream.
364
+ *
365
+ * Streams should emit `start` before partial updates, then terminate with either:
366
+ * - `done` carrying the final successful AssistantMessage, or
367
+ * - `error` carrying the final AssistantMessage with stopReason "error" or "aborted"
368
+ * and errorMessage.
369
+ */
370
+ const LLMMessageEventSchema = Type$2.Union([
371
+ Type$2.Object({
372
+ type: Type$2.Literal(LLMMessageEventType.start),
373
+ partial: AssistantMessageSchema
374
+ }),
375
+ Type$2.Object({
376
+ type: Type$2.Literal(LLMMessageEventType.textStart),
377
+ partIndex: Type$2.Number(),
378
+ partial: AssistantMessageSchema
379
+ }),
380
+ Type$2.Object({
381
+ type: Type$2.Literal(LLMMessageEventType.textDelta),
382
+ partIndex: Type$2.Number(),
383
+ delta: Type$2.String(),
384
+ partial: AssistantMessageSchema
385
+ }),
386
+ Type$2.Object({
387
+ type: Type$2.Literal(LLMMessageEventType.textEnd),
388
+ partIndex: Type$2.Number(),
389
+ content: Type$2.String(),
390
+ partial: AssistantMessageSchema
391
+ }),
392
+ Type$2.Object({
393
+ type: Type$2.Literal(LLMMessageEventType.thinkingStart),
394
+ partIndex: Type$2.Number(),
395
+ partial: AssistantMessageSchema
396
+ }),
397
+ Type$2.Object({
398
+ type: Type$2.Literal(LLMMessageEventType.thinkingDelta),
399
+ partIndex: Type$2.Number(),
400
+ delta: Type$2.String(),
401
+ partial: AssistantMessageSchema
402
+ }),
403
+ Type$2.Object({
404
+ type: Type$2.Literal(LLMMessageEventType.thinkingEnd),
405
+ partIndex: Type$2.Number(),
406
+ content: Type$2.String(),
407
+ partial: AssistantMessageSchema
408
+ }),
409
+ Type$2.Object({
410
+ type: Type$2.Literal(LLMMessageEventType.toolcallStart),
411
+ partIndex: Type$2.Number(),
412
+ partial: AssistantMessageSchema
413
+ }),
414
+ Type$2.Object({
415
+ type: Type$2.Literal(LLMMessageEventType.toolcallDelta),
416
+ partIndex: Type$2.Number(),
417
+ delta: Type$2.String(),
418
+ partial: AssistantMessageSchema
419
+ }),
420
+ Type$2.Object({
421
+ type: Type$2.Literal(LLMMessageEventType.toolcallEnd),
422
+ partIndex: Type$2.Number(),
423
+ toolCall: ToolCallSchema,
424
+ partial: AssistantMessageSchema
425
+ }),
426
+ Type$2.Object({
427
+ type: Type$2.Literal(LLMMessageEventType.toolcallFinal),
428
+ partIndex: Type$2.Number(),
429
+ toolCall: ToolCallSchema,
430
+ partial: AssistantMessageSchema
431
+ }),
432
+ Type$2.Object({
433
+ type: Type$2.Literal(LLMMessageEventType.done),
434
+ reason: Type$2.Union([
435
+ Type$2.Literal("stop"),
436
+ Type$2.Literal("length"),
437
+ Type$2.Literal("toolUse")
459
438
  ]),
460
- Type$1.Object({
461
- type: Type$1.Literal(AgentEventType.messageUpdate),
462
- message: Message.MessageSchema
463
- }),
464
- Type$1.Object({
465
- type: Type$1.Literal(AgentEventType.messageEnd),
466
- message: Message.MessageSchema
467
- }),
468
- ToolExecutionStartSchema,
469
- ToolExecutionUpdateSchema,
470
- ToolExecutionEndSchema
471
- ]);
472
- })(Event || (Event = {}));
439
+ message: AssistantMessageSchema
440
+ }),
441
+ Type$2.Object({
442
+ type: Type$2.Literal(LLMMessageEventType.error),
443
+ reason: Type$2.Union([Type$2.Literal("aborted"), Type$2.Literal("error")]),
444
+ error: AssistantMessageSchema
445
+ })
446
+ ]);
447
+ const AgentEventType = {
448
+ agentStart: "agent.start",
449
+ agentEnd: "agent.end",
450
+ turnStart: "turn.start",
451
+ turnEnd: "turn.end",
452
+ messageStart: "message.start",
453
+ messagePartStart: "message.part.start",
454
+ messagePartUpdate: "message.part.update",
455
+ messagePartEnd: "message.part.end",
456
+ messageUpdate: "message.update",
457
+ messageEnd: "message.end",
458
+ toolExecutionStart: "tool.execution.start",
459
+ toolExecutionUpdate: "tool.execution.update",
460
+ toolExecutionEnd: "tool.execution.end"
461
+ };
462
+ const UserMessagePart = Type$2.Union([TextContentSchema, ImageContentSchema]);
463
+ const AssistantMessagePart = Type$2.Union([
464
+ TextContentSchema,
465
+ ImageContentSchema,
466
+ ThinkingContentSchema,
467
+ ToolCallSchema
468
+ ]);
469
+ const UserMessagePartStart = Type$2.Object({
470
+ type: Type$2.Literal(AgentEventType.messagePartStart),
471
+ message: UserMessageSchema,
472
+ partIndex: Type$2.Number(),
473
+ part: UserMessagePart
474
+ });
475
+ const UserMessagePartEnd = Type$2.Object({
476
+ type: Type$2.Literal(AgentEventType.messagePartEnd),
477
+ message: UserMessageSchema,
478
+ partIndex: Type$2.Number(),
479
+ part: UserMessagePart
480
+ });
481
+ const AssistantMessagePartStart = Type$2.Object({
482
+ type: Type$2.Literal(AgentEventType.messagePartStart),
483
+ message: AssistantMessageSchema,
484
+ partIndex: Type$2.Number(),
485
+ part: AssistantMessagePart
486
+ });
487
+ const AssistantMessagePartLLMUpdate = Type$2.Object({
488
+ type: Type$2.Literal(AgentEventType.messagePartUpdate),
489
+ message: AssistantMessageSchema,
490
+ partIndex: Type$2.Number(),
491
+ part: AssistantMessagePart,
492
+ source: Type$2.Literal("llm")
493
+ });
494
+ const AssistantMessagePartToolUpdate = Type$2.Object({
495
+ type: Type$2.Literal(AgentEventType.messagePartUpdate),
496
+ message: AssistantMessageSchema,
497
+ partIndex: Type$2.Number(),
498
+ part: AssistantMessagePart,
499
+ source: Type$2.Literal("tool")
500
+ });
501
+ const AssistantMessagePartEnd = Type$2.Object({
502
+ type: Type$2.Literal(AgentEventType.messagePartEnd),
503
+ message: AssistantMessageSchema,
504
+ partIndex: Type$2.Number(),
505
+ part: AssistantMessagePart
506
+ });
507
+ const ToolExecutionStartSchema = Type$2.Object({
508
+ type: Type$2.Literal(AgentEventType.toolExecutionStart),
509
+ messageId: Type$2.String(),
510
+ partIndex: Type$2.Number(),
511
+ toolCall: ToolCallPendingPartSchema
512
+ });
513
+ const ToolExecutionUpdateSchema = Type$2.Object({
514
+ type: Type$2.Literal(AgentEventType.toolExecutionUpdate),
515
+ messageId: Type$2.String(),
516
+ partIndex: Type$2.Number(),
517
+ toolCall: ToolCallRunningPartSchema
518
+ });
519
+ const ToolExecutionEndSchema = Type$2.Object({
520
+ type: Type$2.Literal(AgentEventType.toolExecutionEnd),
521
+ messageId: Type$2.String(),
522
+ partIndex: Type$2.Number(),
523
+ toolCall: ToolCallTerminalPartSchema
524
+ });
525
+ /**
526
+ * Events emitted by the Agent lifecycle
527
+ * These events provide fine-grained lifecycle information for messages, turns, and tool execution.
528
+ */
529
+ const AgentEventSchema = Type$2.Union([
530
+ Type$2.Object({ type: Type$2.Literal(AgentEventType.agentStart) }),
531
+ Type$2.Object({
532
+ type: Type$2.Literal(AgentEventType.agentEnd),
533
+ messages: Type$2.Array(MessageSchema)
534
+ }),
535
+ Type$2.Object({ type: Type$2.Literal(AgentEventType.turnStart) }),
536
+ Type$2.Object({
537
+ type: Type$2.Literal(AgentEventType.turnEnd),
538
+ message: AssistantMessageSchema
539
+ }),
540
+ Type$2.Object({
541
+ type: Type$2.Literal(AgentEventType.messageStart),
542
+ message: MessageSchema
543
+ }),
544
+ Type$2.Union([UserMessagePartStart, UserMessagePartEnd]),
545
+ Type$2.Union([
546
+ AssistantMessagePartStart,
547
+ AssistantMessagePartLLMUpdate,
548
+ AssistantMessagePartToolUpdate,
549
+ AssistantMessagePartEnd
550
+ ]),
551
+ Type$2.Object({
552
+ type: Type$2.Literal(AgentEventType.messageUpdate),
553
+ message: MessageSchema
554
+ }),
555
+ Type$2.Object({
556
+ type: Type$2.Literal(AgentEventType.messageEnd),
557
+ message: MessageSchema
558
+ }),
559
+ ToolExecutionStartSchema,
560
+ ToolExecutionUpdateSchema,
561
+ ToolExecutionEndSchema
562
+ ]);
473
563
  //#endregion
474
564
  //#region src/llm.ts
475
- const llmImpl = async (provider, model, overrides) => Model.getModel(provider, model, overrides);
565
+ const llmImpl = async (provider, model, overrides) => getModel(provider, model, overrides);
476
566
  const llm = Object.assign(llmImpl, {
477
- model: Model.getModel,
478
- models: Model.getModels,
479
- providers: Model.getProviders,
480
- registry: Model.registry,
481
- modelsAreEqual: Model.modelsAreEqual
567
+ model: getModel,
568
+ models: getModels,
569
+ providers: getProviders,
570
+ registry,
571
+ modelsAreEqual
482
572
  });
483
573
  //#endregion
484
574
  //#region src/llm/protocol.ts
485
- let Protocol;
486
- (function(_Protocol) {
487
- const ProviderProtocolNotFoundError = _Protocol.ProviderProtocolNotFoundError = NamedError.create("ProviderProtocolNotFoundError", Type$1.Object({ protocol: Model.KnownProviderEnumSchema }));
488
- const ProtocolMismatchError = _Protocol.ProtocolMismatchError = NamedError.create("ProtocolMismatchError", Type$1.Object({
489
- actual: Model.KnownProviderEnumSchema,
490
- expected: Model.KnownProviderEnumSchema
491
- }));
492
- _Protocol.ProtocolAuthError = NamedError.create("ProtocolAuthError", Type$1.Object({
493
- message: Type$1.String(),
494
- protocol: Type$1.String()
495
- }));
496
- const protocolRegistry = /* @__PURE__ */ new Map();
497
- function wrapStream(protocol, stream) {
498
- return (model, context, options) => {
499
- if (model.protocol !== protocol) throw new ProtocolMismatchError({
500
- actual: model.protocol,
501
- expected: protocol
502
- });
503
- return stream(model, context, options);
504
- };
505
- }
506
- function registerProtocolProvider(provider, sourceId) {
507
- const registered = {
508
- protocol: provider.protocol,
509
- stream: wrapStream(provider.protocol, provider.stream)
510
- };
511
- protocolRegistry.set(provider.protocol, {
512
- provider: registered,
513
- sourceId
575
+ var protocol_exports = /* @__PURE__ */ __exportAll({
576
+ ProtocolAuthError: () => ProtocolAuthError,
577
+ ProtocolMismatchError: () => ProtocolMismatchError,
578
+ ProviderProtocolNotFoundError: () => ProviderProtocolNotFoundError,
579
+ clearProtocolProviders: () => clearProtocolProviders,
580
+ complete: () => complete,
581
+ getProtocolProvider: () => getProtocolProvider,
582
+ getProtocolProviders: () => getProtocolProviders,
583
+ registerProtocolProvider: () => registerProtocolProvider,
584
+ resolveProtocolProvider: () => resolveProtocolProvider,
585
+ stream: () => stream$2,
586
+ unregisterProtocolProviders: () => unregisterProtocolProviders
587
+ });
588
+ const ProviderProtocolNotFoundError = NamedError.create("ProviderProtocolNotFoundError", Type$2.Object({ protocol: KnownProviderEnumSchema }));
589
+ const ProtocolMismatchError = NamedError.create("ProtocolMismatchError", Type$2.Object({
590
+ actual: KnownProviderEnumSchema,
591
+ expected: KnownProviderEnumSchema
592
+ }));
593
+ const ProtocolAuthError = NamedError.create("ProtocolAuthError", Type$2.Object({
594
+ message: Type$2.String(),
595
+ protocol: Type$2.String()
596
+ }));
597
+ const protocolRegistry = /* @__PURE__ */ new Map();
598
+ function wrapStream(protocol, stream) {
599
+ return (model, context, options) => {
600
+ if (model.protocol !== protocol) throw new ProtocolMismatchError({
601
+ actual: model.protocol,
602
+ expected: protocol
514
603
  });
515
- }
516
- _Protocol.registerProtocolProvider = registerProtocolProvider;
517
- function getProtocolProvider(protocol) {
518
- return protocolRegistry.get(protocol)?.provider;
519
- }
520
- _Protocol.getProtocolProvider = getProtocolProvider;
521
- function resolveProtocolProvider(model) {
522
- const provider = getProtocolProvider(model.protocol);
523
- if (!provider) throw new ProviderProtocolNotFoundError({ protocol: model.protocol });
524
- return provider;
525
- }
526
- _Protocol.resolveProtocolProvider = resolveProtocolProvider;
527
- function getProtocolProviders() {
528
- return Array.from(protocolRegistry.values(), (entry) => entry.provider);
529
- }
530
- _Protocol.getProtocolProviders = getProtocolProviders;
531
- function stream(model, context, options) {
532
- return resolveProtocolProvider(model).stream(model, context, options);
533
- }
534
- _Protocol.stream = stream;
535
- async function complete(model, context, options) {
536
- return stream(model, context, options).result();
537
- }
538
- _Protocol.complete = complete;
539
- function unregisterProtocolProviders(sourceId) {
540
- for (const [protocol, entry] of protocolRegistry.entries()) if (entry.sourceId === sourceId) protocolRegistry.delete(protocol);
541
- }
542
- _Protocol.unregisterProtocolProviders = unregisterProtocolProviders;
543
- function clearProtocolProviders() {
544
- protocolRegistry.clear();
545
- }
546
- _Protocol.clearProtocolProviders = clearProtocolProviders;
547
- })(Protocol || (Protocol = {}));
604
+ return stream(model, context, options);
605
+ };
606
+ }
607
+ function registerProtocolProvider(provider, sourceId) {
608
+ const registered = {
609
+ protocol: provider.protocol,
610
+ stream: wrapStream(provider.protocol, provider.stream)
611
+ };
612
+ protocolRegistry.set(provider.protocol, {
613
+ provider: registered,
614
+ ...sourceId !== void 0 && { sourceId }
615
+ });
616
+ }
617
+ function getProtocolProvider(protocol) {
618
+ return protocolRegistry.get(protocol)?.provider;
619
+ }
620
+ function resolveProtocolProvider(model) {
621
+ const provider = getProtocolProvider(model.protocol);
622
+ if (!provider) throw new ProviderProtocolNotFoundError({ protocol: model.protocol });
623
+ return provider;
624
+ }
625
+ function getProtocolProviders() {
626
+ return Array.from(protocolRegistry.values(), (entry) => entry.provider);
627
+ }
628
+ function stream$2(model, context, options) {
629
+ return resolveProtocolProvider(model).stream(model, context, options);
630
+ }
631
+ async function complete(model, context, options) {
632
+ return stream$2(model, context, options).result();
633
+ }
634
+ function unregisterProtocolProviders(sourceId) {
635
+ for (const [protocol, entry] of protocolRegistry.entries()) if (entry.sourceId === sourceId) protocolRegistry.delete(protocol);
636
+ }
637
+ function clearProtocolProviders() {
638
+ protocolRegistry.clear();
639
+ }
548
640
  //#endregion
549
641
  //#region src/llm/shared.ts
550
- const CacheRetention = Type$2.Union([
551
- Type$2.Literal("none"),
552
- Type$2.Literal("short"),
553
- Type$2.Literal("long")
642
+ const CacheRetention = Type$1.Union([
643
+ Type$1.Literal("none"),
644
+ Type$1.Literal("short"),
645
+ Type$1.Literal("long")
554
646
  ]);
555
- const GenerationOptions = Type$2.Object({
556
- maxTokens: Type$2.Optional(Type$2.Number()),
557
- temperature: Type$2.Optional(Type$2.Number()),
558
- cacheRetention: Type$2.Optional(CacheRetention)
647
+ const GenerationOptions = Type$1.Object({
648
+ maxTokens: Type$1.Optional(Type$1.Number()),
649
+ temperature: Type$1.Optional(Type$1.Number()),
650
+ cacheRetention: Type$1.Optional(CacheRetention)
559
651
  });
560
- const HelperOptions = Type$2.Object({
561
- headers: Type$2.Optional(Type$2.Record(Type$2.String(), Type$2.String())),
562
- sessionId: Type$2.Optional(Type$2.String()),
563
- apiKey: Type$2.Optional(Type$2.String()),
564
- timeoutMs: Type$2.Optional(Type$2.Number()),
565
- maxRetries: Type$2.Optional(Type$2.Number()),
566
- signal: Type$2.Optional(Type$2.Unsafe({})),
567
- onPayload: Type$2.Optional(Type$2.Unsafe({})),
568
- metadata: Type$2.Optional(Type$2.Record(Type$2.String(), Type$2.Unknown()))
652
+ const HelperOptions = Type$1.Object({
653
+ headers: Type$1.Optional(Type$1.Record(Type$1.String(), Type$1.String())),
654
+ sessionId: Type$1.Optional(Type$1.String()),
655
+ apiKey: Type$1.Optional(Type$1.String()),
656
+ timeoutMs: Type$1.Optional(Type$1.Number()),
657
+ maxRetries: Type$1.Optional(Type$1.Number()),
658
+ signal: Type$1.Optional(Type$1.Unsafe({})),
659
+ onPayload: Type$1.Optional(Type$1.Unsafe({})),
660
+ metadata: Type$1.Optional(Type$1.Record(Type$1.String(), Type$1.Unknown()))
569
661
  });
570
- const ThinkingBudgets = Type$2.Object({
571
- minimal: Type$2.Optional(Type$2.Number()),
572
- low: Type$2.Optional(Type$2.Number()),
573
- medium: Type$2.Optional(Type$2.Number()),
574
- high: Type$2.Optional(Type$2.Number()),
575
- xhigh: Type$2.Optional(Type$2.Number())
662
+ const ThinkingBudgets = Type$1.Object({
663
+ minimal: Type$1.Optional(Type$1.Number()),
664
+ low: Type$1.Optional(Type$1.Number()),
665
+ medium: Type$1.Optional(Type$1.Number()),
666
+ high: Type$1.Optional(Type$1.Number()),
667
+ xhigh: Type$1.Optional(Type$1.Number()),
668
+ max: Type$1.Optional(Type$1.Number())
576
669
  });
577
- const SharedOptions = Type$2.Evaluate(Type$2.Intersect([GenerationOptions, HelperOptions]));
670
+ const SharedOptions = Type$1.Evaluate(Type$1.Intersect([GenerationOptions, HelperOptions]));
578
671
  const DEFAULT_MAX_OUTPUT_TOKENS = 32e3;
579
672
  const CONTEXT_WINDOW_OUTPUT_TOLERANCE = 1024;
580
673
  function applyDefaultMaxTokens(model, options) {
@@ -584,16 +677,16 @@ function applyDefaultMaxTokens(model, options) {
584
677
  maxTokens: options?.maxTokens ?? defaultMaxTokens
585
678
  };
586
679
  }
587
- Type$2.Evaluate(Type$2.Intersect([SharedOptions, Type$2.Object({
588
- baseURL: Type$2.Optional(Type$2.String()),
589
- method: Type$2.Optional(Model.APIMethodEnumSchema),
590
- modelId: Type$2.Optional(Type$2.String()),
591
- reasoning: Type$2.Optional(Model.ActiveThinkingLevel),
592
- thinkingBudgets: Type$2.Optional(ThinkingBudgets),
593
- toolChoice: Type$2.Optional(Type$2.Any()),
594
- activeTools: Type$2.Optional(Type$2.Array(Type$2.String())),
595
- factoryOptions: Type$2.Optional(Type$2.Record(Type$2.String(), Type$2.Unknown())),
596
- providerOptions: Type$2.Optional(Type$2.Record(Type$2.String(), Type$2.Record(Type$2.String(), Type$2.Unknown())))
680
+ Type$1.Evaluate(Type$1.Intersect([SharedOptions, Type$1.Object({
681
+ baseURL: Type$1.Optional(Type$1.String()),
682
+ method: Type$1.Optional(APIMethodEnumSchema),
683
+ modelId: Type$1.Optional(Type$1.String()),
684
+ reasoning: Type$1.Optional(ActiveThinkingLevel),
685
+ thinkingBudgets: Type$1.Optional(ThinkingBudgets),
686
+ toolChoice: Type$1.Optional(Type$1.Any()),
687
+ activeTools: Type$1.Optional(Type$1.Array(Type$1.String())),
688
+ factoryOptions: Type$1.Optional(Type$1.Record(Type$1.String(), Type$1.Unknown())),
689
+ providerOptions: Type$1.Optional(Type$1.Record(Type$1.String(), Type$1.Record(Type$1.String(), Type$1.Unknown())))
597
690
  })]));
598
691
  //#endregion
599
692
  //#region src/utils/eventstream.ts
@@ -603,6 +696,8 @@ var EventStream = class {
603
696
  done = false;
604
697
  finalResultPromise;
605
698
  resolveFinalResult;
699
+ isComplete;
700
+ extractResult;
606
701
  constructor(isComplete, extractResult) {
607
702
  this.isComplete = isComplete;
608
703
  this.extractResult = extractResult;
@@ -658,6 +753,21 @@ function createAssistantMessageEventStream() {
658
753
  return new AssistantMessageEventStream();
659
754
  }
660
755
  //#endregion
756
+ //#region src/utils/helpers.ts
757
+ /**
758
+ * Drops keys whose value is `undefined`.
759
+ *
760
+ * Under `exactOptionalPropertyTypes` an explicit `undefined` is not assignable to an optional
761
+ * property, so a literal built from optional inputs has to omit the key rather than pass it
762
+ * through. Only worth reaching for when a literal forwards many optional values at once — for a
763
+ * handful of keys a conditional spread reads better.
764
+ */
765
+ function compact(value) {
766
+ const result = {};
767
+ for (const [key, entry] of Object.entries(value)) if (entry !== void 0) result[key] = entry;
768
+ return result;
769
+ }
770
+ //#endregion
661
771
  //#region src/llm/runtime.ts
662
772
  function mergeHeaders(...headerSources) {
663
773
  const merged = {};
@@ -705,15 +815,23 @@ async function resolveAISDKLanguageModel(model, options) {
705
815
  if (Object.keys(headers).length > 0) factoryOptions.headers = headers;
706
816
  if (baseURL) factoryOptions.baseURL = baseURL;
707
817
  if (npm === "@ai-sdk/openai-compatible") {
708
- if (!baseURL) throw new Protocol.ProtocolAuthError({
818
+ if (!baseURL) throw new ProtocolAuthError({
709
819
  protocol: model.protocol,
710
820
  message: "AI SDK openai-compatible transport requires model.baseUrl, model.api.url, or options.baseURL"
711
821
  });
712
822
  factoryOptions.name ??= model.provider.id;
713
823
  factoryOptions.includeUsage ??= true;
714
824
  }
715
- if (npm === "@codeworksh/ai-sdk-openai-codex" && options.sessionId) factoryOptions.sessionId ??= options.sessionId;
716
- return resolveLanguageModel(createProvider(factoryOptions), model, options.method);
825
+ if (npm === "@codeworksh/ai-sdk-openai-codex") {
826
+ const cacheDisabled = options.cacheRetention === "none" || typeof process !== "undefined" && process.env.CODEWORK_CACHE_RETENTION === "none";
827
+ if (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;
828
+ factoryOptions.compat ??= {
829
+ ...model.compat,
830
+ supportsImages: model.input.includes("image")
831
+ };
832
+ }
833
+ const provider = createProvider(factoryOptions);
834
+ return resolveLanguageModel(provider, model, options.method);
717
835
  }
718
836
  //#endregion
719
837
  //#region src/utils/jsonparse.ts
@@ -788,9 +906,7 @@ function repairInvalidJsonStringContent(input) {
788
906
  case " ":
789
907
  output += "\\t";
790
908
  break;
791
- default:
792
- output += char;
793
- break;
909
+ default: output += char;
794
910
  }
795
911
  }
796
912
  if (escaping) output += "\\\\";
@@ -824,7 +940,7 @@ function sanitizeSurrogates(text) {
824
940
  //#endregion
825
941
  //#region src/llm/transform.ts
826
942
  function createAssistantMessage(model) {
827
- return Message.createAssistantMessage({
943
+ return createAssistantMessage$1({
828
944
  role: "assistant",
829
945
  parts: [],
830
946
  protocol: model.protocol,
@@ -863,8 +979,8 @@ function userContent(parts, supportsImages) {
863
979
  continue;
864
980
  }
865
981
  if (supportsImages) content.push({
866
- type: "image",
867
- image: part.data,
982
+ type: "file",
983
+ data: part.data,
868
984
  mediaType: part.mimeType
869
985
  });
870
986
  }
@@ -904,13 +1020,27 @@ function toolResultOutput(toolCall) {
904
1020
  type: "text",
905
1021
  text
906
1022
  }] : [], ...images.map((image) => ({
907
- type: "image-data",
908
- data: image.data,
1023
+ type: "file",
1024
+ data: {
1025
+ type: "data",
1026
+ data: image.data
1027
+ },
909
1028
  mediaType: image.mimeType
910
1029
  }))]
911
1030
  };
912
1031
  }
913
- function assistantMessages(message) {
1032
+ function normalizeOpenAICodexIdPart(value) {
1033
+ return value.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64).replace(/_+$/, "");
1034
+ }
1035
+ function normalizeOpenAICodexToolCallId(id, model, source) {
1036
+ if (!id.includes("|")) return normalizeOpenAICodexIdPart(id);
1037
+ const [callId, itemId = ""] = id.split("|");
1038
+ const normalizedCallId = normalizeOpenAICodexIdPart(callId ?? "");
1039
+ let normalizedItemId = source.provider.id !== model.provider.id || source.protocol !== model.protocol ? `fc_${shortHash(itemId)}` : normalizeOpenAICodexIdPart(itemId);
1040
+ if (!normalizedItemId.startsWith("fc_") && !normalizedItemId.startsWith("ctc_")) normalizedItemId = normalizeOpenAICodexIdPart(`fc_${normalizedItemId}`);
1041
+ return `${normalizedCallId}|${normalizedItemId}`;
1042
+ }
1043
+ function assistantMessages(message, model) {
914
1044
  if (message.stopReason === "error" || message.stopReason === "aborted") return [];
915
1045
  const assistantContent = [];
916
1046
  const toolResults = [];
@@ -920,33 +1050,39 @@ function assistantMessages(message) {
920
1050
  if (text.trim().length === 0) continue;
921
1051
  assistantContent.push({
922
1052
  type: "text",
923
- text
1053
+ text,
1054
+ ...part.textSignature && message.protocol === KnownProviderEnum.openaiCodex ? { providerOptions: { "openai-codex": { messageId: part.textSignature } } } : {}
924
1055
  });
925
1056
  continue;
926
1057
  }
927
1058
  if (part.type === "thinking") {
928
1059
  const thinking = sanitizeSurrogates(part.thinking);
929
- if (thinking.trim().length === 0) continue;
1060
+ if (thinking.trim().length === 0 && !part.thinkingSignature) continue;
930
1061
  const reasoning = {
931
1062
  type: "reasoning",
932
1063
  text: thinking
933
1064
  };
934
- if (part.thinkingSignature) reasoning.providerOptions = { anthropic: { signature: part.thinkingSignature } };
1065
+ if (part.thinkingSignature) reasoning.providerOptions = message.protocol === KnownProviderEnum.openaiCodex ? { "openai-codex": { reasoningItem: part.thinkingSignature } } : { anthropic: { signature: part.thinkingSignature } };
935
1066
  assistantContent.push(reasoning);
936
1067
  continue;
937
1068
  }
938
1069
  if (part.type !== "toolCall") continue;
1070
+ const codexToolMetadata = {};
1071
+ if (part.namespace && message.protocol === KnownProviderEnum.openaiCodex) codexToolMetadata.namespace = part.namespace;
1072
+ if (model.protocol === KnownProviderEnum.openaiCodex && message.protocol === model.protocol && message.provider.id === model.provider.id && message.model !== model.id) codexToolMetadata.omitItemId = true;
939
1073
  assistantContent.push({
940
1074
  type: "tool-call",
941
1075
  toolCallId: part.callID,
942
1076
  toolName: part.name,
943
- input: sanitizeRecord(part.arguments ?? {})
1077
+ input: sanitizeRecord(part.arguments ?? {}),
1078
+ ...Object.keys(codexToolMetadata).length > 0 ? { providerOptions: { "openai-codex": codexToolMetadata } } : {}
944
1079
  });
945
1080
  const terminal = part.status === "pending" || part.status === "running" ? void 0 : part;
946
1081
  toolResults.push({
947
1082
  type: "tool-result",
948
1083
  toolCallId: part.callID,
949
1084
  toolName: part.name,
1085
+ ...terminal?.addedToolNames?.length ? { providerOptions: { "openai-codex": { addedToolNames: terminal.addedToolNames } } } : {},
950
1086
  output: terminal ? toolResultOutput(terminal) : {
951
1087
  type: "error-text",
952
1088
  value: "No result provided"
@@ -966,23 +1102,28 @@ function assistantMessages(message) {
966
1102
  }
967
1103
  function convertMessages(context, model) {
968
1104
  const messages = [];
969
- const transformedMessages = Message.transformMessages(context.messages, model);
1105
+ const transformedMessages = transformMessages(context.messages, model, model.protocol === KnownProviderEnum.openaiCodex ? normalizeOpenAICodexToolCallId : void 0);
970
1106
  for (const msg of transformedMessages) {
971
1107
  if (msg.role === "user") {
972
1108
  messages.push(...userContent(msg.parts, model.input.includes("image")));
973
1109
  continue;
974
1110
  }
975
- messages.push(...assistantMessages(msg));
1111
+ messages.push(...assistantMessages(msg, model));
976
1112
  }
977
1113
  return messages;
978
1114
  }
979
- function convertTools(tools) {
1115
+ function convertTools(tools, model) {
980
1116
  if (!tools || tools.length === 0) return;
981
1117
  const result = {};
982
- for (const tool of tools) result[tool.name] = {
983
- description: tool.description,
984
- inputSchema: jsonSchema(tool.parameters)
985
- };
1118
+ for (const tool of tools) {
1119
+ const constraint = model?.protocol === KnownProviderEnum.openaiCodex ? resolveOpenAICodexToolConstraint(tool, model.compat) : void 0;
1120
+ result[tool.name] = {
1121
+ description: tool.description,
1122
+ inputSchema: jsonSchema(tool.parameters),
1123
+ ...constraint?.type === "json_schema" ? { strict: true } : {},
1124
+ ...constraint?.type === "grammar" ? { providerOptions: { "openai-codex": { grammar: constraint } } } : {}
1125
+ };
1126
+ }
986
1127
  return result;
987
1128
  }
988
1129
  function mapFinishReason(reason) {
@@ -995,17 +1136,19 @@ function mapFinishReason(reason) {
995
1136
  default: return "stop";
996
1137
  }
997
1138
  }
998
- function mapUsage(usage, model) {
999
- const cacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? usage?.cachedInputTokens ?? 0;
1139
+ function mapUsage(usage, model, costMultiplier = 1) {
1140
+ const cacheRead = usage?.inputTokenDetails.cacheReadTokens ?? 0;
1000
1141
  const cacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;
1001
1142
  const input = usage?.inputTokenDetails?.noCacheTokens ?? Math.max((usage?.inputTokens ?? 0) - cacheRead - cacheWrite, 0);
1002
1143
  const output = usage?.outputTokens ?? 0;
1144
+ const totalTokens = usage?.totalTokens ?? input + cacheRead + cacheWrite + output;
1003
1145
  const result = {
1004
1146
  input,
1005
1147
  output,
1006
1148
  cacheRead,
1007
1149
  cacheWrite,
1008
- totalTokens: usage?.totalTokens ?? input + cacheRead + cacheWrite + output,
1150
+ ...usage?.outputTokenDetails?.reasoningTokens !== void 0 ? { reasoning: usage.outputTokenDetails.reasoningTokens } : {},
1151
+ totalTokens,
1009
1152
  cost: {
1010
1153
  input: 0,
1011
1154
  output: 0,
@@ -1014,7 +1157,14 @@ function mapUsage(usage, model) {
1014
1157
  total: 0
1015
1158
  }
1016
1159
  };
1017
- Model.calculateCost(model, result);
1160
+ calculateCost(model, result);
1161
+ if (costMultiplier !== 1) {
1162
+ result.cost.input *= costMultiplier;
1163
+ result.cost.output *= costMultiplier;
1164
+ result.cost.cacheRead *= costMultiplier;
1165
+ result.cost.cacheWrite *= costMultiplier;
1166
+ result.cost.total = result.cost.input + result.cost.output + result.cost.cacheRead + result.cost.cacheWrite;
1167
+ }
1018
1168
  return result;
1019
1169
  }
1020
1170
  function toolCallFromPart(part) {
@@ -1082,7 +1232,8 @@ const DEFAULT_THINKING_BUDGET_FRACTIONS = {
1082
1232
  low: .1,
1083
1233
  medium: .25,
1084
1234
  high: .5,
1085
- xhigh: .8
1235
+ xhigh: .8,
1236
+ max: .95
1086
1237
  };
1087
1238
  const MIN_THINKING_BUDGET = 1024;
1088
1239
  function resolveThinkingBudget(model, options, level) {
@@ -1097,7 +1248,7 @@ function resolveThinkingBudget(model, options, level) {
1097
1248
  function reasoningProviderOptions(model, options) {
1098
1249
  const requestedLevel = options.reasoning;
1099
1250
  if (!requestedLevel) return {};
1100
- const level = Model.clampThinkingLevel(model, requestedLevel);
1251
+ const level = clampThinkingLevel(model, requestedLevel);
1101
1252
  if (level === "off") return {};
1102
1253
  const mapped = model.thinkingLevelMap?.[level] ?? level;
1103
1254
  if (!mapped) return {};
@@ -1125,6 +1276,11 @@ function resolveProviderOptions(model, options) {
1125
1276
  function partIndex(output, block) {
1126
1277
  return output.parts.indexOf(block);
1127
1278
  }
1279
+ function openAICodexMetadata(value) {
1280
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1281
+ const metadata = value["openai-codex"];
1282
+ return typeof metadata === "object" && metadata !== null && !Array.isArray(metadata) ? metadata : void 0;
1283
+ }
1128
1284
  function ensureTextBlock(output, id, stream) {
1129
1285
  const existing = output.parts.find((part) => part.type === "text" && part.streamId === id);
1130
1286
  if (existing) return existing;
@@ -1182,9 +1338,10 @@ function ensureToolCallBlock(output, id, name, stream, emitStart) {
1182
1338
  });
1183
1339
  return block;
1184
1340
  }
1185
- function finishTextBlock(output, id, stream) {
1341
+ function finishTextBlock(output, id, stream, textSignature) {
1186
1342
  const block = output.parts.find((part) => part.type === "text" && part.streamId === id);
1187
1343
  if (!block) return;
1344
+ if (textSignature) block.textSignature = textSignature;
1188
1345
  const index = partIndex(output, block);
1189
1346
  delete block.streamId;
1190
1347
  stream.push({
@@ -1194,9 +1351,10 @@ function finishTextBlock(output, id, stream) {
1194
1351
  partial: output
1195
1352
  });
1196
1353
  }
1197
- function finishThinkingBlock(output, id, stream) {
1354
+ function finishThinkingBlock(output, id, stream, thinkingSignature) {
1198
1355
  const block = output.parts.find((part) => part.type === "thinking" && part.streamId === id);
1199
1356
  if (!block) return;
1357
+ if (thinkingSignature) block.thinkingSignature = thinkingSignature;
1200
1358
  const index = partIndex(output, block);
1201
1359
  delete block.streamId;
1202
1360
  stream.push({
@@ -1224,6 +1382,8 @@ function finalizeToolCall(output, part, stream) {
1224
1382
  block.callID = part.toolCallId;
1225
1383
  block.name = part.toolName;
1226
1384
  block.arguments = typeof part.input === "object" && part.input !== null ? part.input : {};
1385
+ const namespace = openAICodexMetadata(part.providerMetadata)?.namespace;
1386
+ if (typeof namespace === "string") block.namespace = namespace;
1227
1387
  block.time.end = Date.now();
1228
1388
  delete block.partialJson;
1229
1389
  if (!existing) output.parts.push(block);
@@ -1235,7 +1395,7 @@ function finalizeToolCall(output, part, stream) {
1235
1395
  partial: output
1236
1396
  });
1237
1397
  }
1238
- function handlePart(part, output, model, stream) {
1398
+ function handlePart(part, output, model, stream, costMultiplier) {
1239
1399
  switch (part.type) {
1240
1400
  case "text-start":
1241
1401
  ensureTextBlock(output, part.id, stream);
@@ -1251,9 +1411,11 @@ function handlePart(part, output, model, stream) {
1251
1411
  });
1252
1412
  break;
1253
1413
  }
1254
- case "text-end":
1255
- finishTextBlock(output, part.id, stream);
1414
+ case "text-end": {
1415
+ const messageId = openAICodexMetadata(part.providerMetadata)?.messageId;
1416
+ finishTextBlock(output, part.id, stream, typeof messageId === "string" ? messageId : void 0);
1256
1417
  break;
1418
+ }
1257
1419
  case "reasoning-start":
1258
1420
  ensureThinkingBlock(output, part.id, stream);
1259
1421
  break;
@@ -1270,9 +1432,11 @@ function handlePart(part, output, model, stream) {
1270
1432
  });
1271
1433
  break;
1272
1434
  }
1273
- case "reasoning-end":
1274
- finishThinkingBlock(output, part.id, stream);
1435
+ case "reasoning-end": {
1436
+ const reasoningItem = openAICodexMetadata(part.providerMetadata)?.reasoningItem;
1437
+ finishThinkingBlock(output, part.id, stream, typeof reasoningItem === "string" ? reasoningItem : void 0);
1275
1438
  break;
1439
+ }
1276
1440
  case "tool-input-start":
1277
1441
  ensureToolCallBlock(output, part.id, part.toolName, stream, true);
1278
1442
  break;
@@ -1296,20 +1460,30 @@ function handlePart(part, output, model, stream) {
1296
1460
  case "finish-step":
1297
1461
  output.responseId ||= part.response.id;
1298
1462
  if (part.response.modelId && part.response.modelId !== model.id) output.responseModel ||= part.response.modelId;
1299
- output.usage = mapUsage(part.usage, model);
1463
+ output.usage = mapUsage(part.usage, model, costMultiplier);
1300
1464
  output.stopReason = mapFinishReason(part.finishReason);
1301
1465
  break;
1302
1466
  case "finish":
1303
- output.usage = mapUsage(part.totalUsage, model);
1467
+ output.usage = mapUsage(part.totalUsage, model, costMultiplier);
1304
1468
  output.stopReason = mapFinishReason(part.finishReason);
1305
1469
  break;
1306
1470
  case "abort":
1307
1471
  output.stopReason = "aborted";
1308
- output.errorMessage = part.reason;
1472
+ if (part.reason !== void 0) output.errorMessage = part.reason;
1309
1473
  break;
1310
1474
  case "error": throw part.error instanceof Error ? part.error : new Error(formatThrownError(part.error));
1311
1475
  }
1312
1476
  }
1477
+ function resolveCostMultiplier(model, options, providerOptions) {
1478
+ if (providerOptionsKey(model) !== "openai-codex") return 1;
1479
+ const providerTier = providerOptions["openai-codex"]?.serviceTier;
1480
+ const factoryTier = options.factoryOptions?.serviceTier;
1481
+ const modelTier = model.options?.serviceTier;
1482
+ const serviceTier = providerTier ?? factoryTier ?? modelTier;
1483
+ if (serviceTier === "flex") return .5;
1484
+ if (serviceTier === "priority") return model.id === "gpt-5.5" ? 2.5 : 2;
1485
+ return 1;
1486
+ }
1313
1487
  /**
1314
1488
  * Resolve maxOutputTokens so that (maxOutputTokens + thinkingBudget) does not exceed model.maxTokens.
1315
1489
  * Without this adjustment @ai-sdk/anthropic logs a warning and silently caps the value.
@@ -1332,11 +1506,12 @@ const stream$1 = (model, context, options) => {
1332
1506
  const output = createAssistantMessage(model);
1333
1507
  try {
1334
1508
  const languageModel = await resolveAISDKLanguageModel(model, runtimeOptions);
1335
- const tools = convertTools(context.tools);
1509
+ const tools = convertTools(context.tools, model);
1336
1510
  const messages = convertMessages(context, model);
1337
1511
  const providerOptions = resolveProviderOptions(model, runtimeOptions);
1512
+ const costMultiplier = resolveCostMultiplier(model, runtimeOptions, providerOptions);
1338
1513
  const activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);
1339
- let params = {
1514
+ let params = compact({
1340
1515
  model: languageModel,
1341
1516
  system: context.systemPrompt,
1342
1517
  messages,
@@ -1350,7 +1525,7 @@ const stream$1 = (model, context, options) => {
1350
1525
  timeout: runtimeOptions.timeoutMs,
1351
1526
  maxRetries: runtimeOptions.maxRetries,
1352
1527
  headers: runtimeOptions.headers
1353
- };
1528
+ });
1354
1529
  const payload = await runtimeOptions.onPayload?.(params, model);
1355
1530
  if (payload !== void 0) params = payload;
1356
1531
  const result = streamText(params);
@@ -1358,7 +1533,7 @@ const stream$1 = (model, context, options) => {
1358
1533
  type: "start",
1359
1534
  partial: output
1360
1535
  });
1361
- for await (const part of result.fullStream) handlePart(part, output, model, stream);
1536
+ for await (const part of result.fullStream) handlePart(part, output, model, stream, costMultiplier);
1362
1537
  if (runtimeOptions.signal?.aborted || output.stopReason === "aborted") throw new Error(output.errorMessage || "Request was aborted");
1363
1538
  if (output.stopReason === "error") throw new Error(output.errorMessage || "Provider returned an error stop reason");
1364
1539
  output.time.completed = Date.now();
@@ -1396,22 +1571,22 @@ function createAISDKProtocol(protocol) {
1396
1571
  };
1397
1572
  }
1398
1573
  function registerAISDKProtocols() {
1399
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.anthropic));
1400
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.google));
1401
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertex));
1402
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.googleVertexAnthropic));
1403
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openai));
1404
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCompatible));
1405
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openaiCodex));
1406
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.openrouter));
1407
- Protocol.registerProtocolProvider(createAISDKProtocol(Model.KnownProviderEnum.xai));
1574
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.anthropic));
1575
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.google));
1576
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.googleVertex));
1577
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.googleVertexAnthropic));
1578
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.openai));
1579
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.openaiCompatible));
1580
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.openaiCodex));
1581
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.openrouter));
1582
+ registerProtocolProvider(createAISDKProtocol(KnownProviderEnum.xai));
1408
1583
  }
1409
1584
  //#endregion
1410
1585
  //#region src/llm/register.ts
1411
1586
  registerAISDKProtocols();
1412
1587
  //#endregion
1413
1588
  //#region src/stream.ts
1414
- const streamImpl = (model, context, options) => Protocol.stream(model, context, options);
1589
+ const streamImpl = (model, context, options) => stream$2(model, context, options);
1415
1590
  /**
1416
1591
  * Start a streaming assistant response for a model/context pair.
1417
1592
  *
@@ -1422,10 +1597,9 @@ const streamImpl = (model, context, options) => Protocol.stream(model, context,
1422
1597
  * - `stream.resolveProtocolProvider(...)` exposes protocol resolution for advanced integrations.
1423
1598
  */
1424
1599
  const stream = Object.assign(streamImpl, {
1425
- complete: Protocol.complete,
1426
- resolveProtocolProvider: Protocol.resolveProtocolProvider
1600
+ complete,
1601
+ resolveProtocolProvider
1427
1602
  });
1428
- Protocol.complete;
1429
1603
  //#endregion
1430
1604
  //#region src/utils/validation.ts
1431
1605
  const validators = /* @__PURE__ */ new WeakMap();
@@ -1478,6 +1652,6 @@ function validateToolArguments(tool, toolExecution) {
1478
1652
  return validateSchema(tool.parameters, toolExecution.rawArgs, `Tool "${toolExecution.name}"`);
1479
1653
  }
1480
1654
  //#endregion
1481
- export { Event, EventStream, Message, Model, Protocol, ThinkingBudgets, Type, createAssistantMessageEventStream, createOpenAICodex, llm, openaiCodex, stream, validateSchema, validateToolArguments, validateToolCall };
1655
+ export { event_exports as Event, EventStream, message_exports as Message, model_exports as Model, protocol_exports as Protocol, ThinkingBudgets, Type, createAssistantMessageEventStream, createOpenAICodex, llm, openAICodexTools, openaiCodex, stream, validateSchema, validateToolArguments, validateToolCall };
1482
1656
 
1483
1657
  //# sourceMappingURL=index.mjs.map