@codeworksh/aikit 0.7.2 → 0.8.0-dev.20260905193244

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.
@@ -1,5 +1,359 @@
1
- import { o as getOpenAICodexAccountId } from "./codex-DyQHzQmn.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { a as FailureSchema } from "./schema-rXSoWhic.mjs";
3
+ import { a as KnownProviderEnumSchema, o as ProviderInfo } from "./model-CBnredXj.mjs";
4
+ import { o as getOpenAICodexAccountId } from "./codex-MtP1574D.mjs";
5
+ import Type$1 from "typebox";
6
+ import { uuidv7 } from "uuidv7";
2
7
  import { APICallError, LoadAPIKeyError, NoSuchModelError } from "@ai-sdk/provider";
8
+ import { EventSourceParserStream } from "eventsource-parser/stream";
9
+ //#region src/message/message.ts
10
+ var message_exports = /* @__PURE__ */ __exportAll({
11
+ AssistantMessageSchema: () => AssistantMessageSchema,
12
+ ConstrainedSamplingSchema: () => ConstrainedSamplingSchema,
13
+ ContextSchema: () => ContextSchema,
14
+ GrammarVariantsSchema: () => GrammarVariantsSchema,
15
+ ImageContentSchema: () => ImageContentSchema,
16
+ MessageSchema: () => MessageSchema,
17
+ StopReasonSchema: () => StopReasonSchema,
18
+ TextContentSchema: () => TextContentSchema,
19
+ ThinkingContentSchema: () => ThinkingContentSchema,
20
+ ToolAbortedSchema: () => ToolAbortedSchema,
21
+ ToolCallAbortedPartSchema: () => ToolCallAbortedPartSchema,
22
+ ToolCallBaseSchema: () => ToolCallBaseSchema,
23
+ ToolCallCompletedPartSchema: () => ToolCallCompletedPartSchema,
24
+ ToolCallErrorPartSchema: () => ToolCallErrorPartSchema,
25
+ ToolCallInFlightSchema: () => ToolCallInFlightSchema,
26
+ ToolCallPendingPartSchema: () => ToolCallPendingPartSchema,
27
+ ToolCallRunningPartSchema: () => ToolCallRunningPartSchema,
28
+ ToolCallSchema: () => ToolCallSchema,
29
+ ToolCallSkippedPartSchema: () => ToolCallSkippedPartSchema,
30
+ ToolCallTerminalPartSchema: () => ToolCallTerminalPartSchema,
31
+ ToolCompletedSchema: () => ToolCompletedSchema,
32
+ ToolErrorResult: () => ToolErrorResult,
33
+ ToolErrorSchema: () => ToolErrorSchema,
34
+ ToolRunningPartial: () => ToolRunningPartial,
35
+ ToolRunningSchema: () => ToolRunningSchema,
36
+ ToolSchema: () => ToolSchema,
37
+ ToolSkippedSchema: () => ToolSkippedSchema,
38
+ ToolStatusEnum: () => ToolStatusEnum,
39
+ ToolSuccessResult: () => ToolSuccessResult,
40
+ UsageSchema: () => UsageSchema,
41
+ UserMessageSchema: () => UserMessageSchema,
42
+ createAssistantMessage: () => createAssistantMessage,
43
+ createMessageId: () => createMessageId,
44
+ createUserMessage: () => createUserMessage,
45
+ defineTool: () => defineTool,
46
+ resolveJsonSchemaConstraint: () => resolveJsonSchemaConstraint,
47
+ transformMessages: () => transformMessages
48
+ });
49
+ const TextContentSchema = Type$1.Object({
50
+ type: Type$1.Literal("text"),
51
+ text: Type$1.String(),
52
+ textSignature: Type$1.Optional(Type$1.String())
53
+ });
54
+ const ImageContentSchema = Type$1.Object({
55
+ type: Type$1.Literal("image"),
56
+ data: Type$1.String(),
57
+ mimeType: Type$1.String()
58
+ });
59
+ const ThinkingContentSchema = Type$1.Object({
60
+ type: Type$1.Literal("thinking"),
61
+ thinking: Type$1.String(),
62
+ thinkingSignature: Type$1.Optional(Type$1.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$1.Optional(Type$1.Boolean())
67
+ });
68
+ const ToolCallBaseSchema = Type$1.Object({
69
+ type: Type$1.Literal("toolCall"),
70
+ callID: Type$1.String(),
71
+ name: Type$1.String(),
72
+ arguments: Type$1.Record(Type$1.String(), Type$1.Any()),
73
+ thoughtSignature: Type$1.Optional(Type$1.String()),
74
+ namespace: Type$1.Optional(Type$1.String()),
75
+ /** Names from Context.tools that became available after this tool result. */
76
+ addedToolNames: Type$1.Optional(Type$1.Array(Type$1.String())),
77
+ time: Type$1.Object({
78
+ start: Type$1.Number(),
79
+ end: Type$1.Number()
80
+ })
81
+ });
82
+ const ToolSuccessResult = Type$1.Object({
83
+ content: Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema])),
84
+ details: Type$1.Optional(Type$1.Any()),
85
+ isError: Type$1.Literal(false)
86
+ });
87
+ const ToolErrorResult = Type$1.Object({
88
+ content: Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema])),
89
+ details: Type$1.Optional(Type$1.Any()),
90
+ isError: Type$1.Literal(true)
91
+ });
92
+ const ToolRunningPartial = Type$1.Object({
93
+ content: Type$1.Optional(Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema]))),
94
+ details: Type$1.Optional(Type$1.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$1.Object({
105
+ status: Type$1.Literal(ToolStatusEnum.running),
106
+ partial: Type$1.Optional(ToolRunningPartial)
107
+ });
108
+ const ToolCompletedSchema = Type$1.Object({
109
+ status: Type$1.Literal(ToolStatusEnum.completed),
110
+ result: ToolSuccessResult
111
+ });
112
+ const ToolErrorSchema = Type$1.Object({
113
+ status: Type$1.Literal(ToolStatusEnum.error),
114
+ result: ToolErrorResult
115
+ });
116
+ const ToolSkippedSchema = Type$1.Object({
117
+ status: Type$1.Literal(ToolStatusEnum.skipped),
118
+ result: ToolErrorResult
119
+ });
120
+ const ToolAbortedSchema = Type$1.Object({
121
+ status: Type$1.Literal(ToolStatusEnum.aborted),
122
+ result: ToolErrorResult
123
+ });
124
+ const ToolCallPendingPartSchema = Type$1.Intersect([ToolCallBaseSchema, Type$1.Object({ status: Type$1.Literal(ToolStatusEnum.pending) })]);
125
+ const ToolCallRunningPartSchema = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolRunningSchema]));
126
+ const ToolCallCompletedPartSchema = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolCompletedSchema]));
127
+ const ToolCallErrorPartSchema = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolErrorSchema]));
128
+ const ToolCallSkippedPartSchema = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolSkippedSchema]));
129
+ const ToolCallAbortedPartSchema = Type$1.Evaluate(Type$1.Intersect([ToolCallBaseSchema, ToolAbortedSchema]));
130
+ const ToolCallTerminalPartSchema = Type$1.Union([
131
+ ToolCallCompletedPartSchema,
132
+ ToolCallErrorPartSchema,
133
+ ToolCallSkippedPartSchema,
134
+ ToolCallAbortedPartSchema
135
+ ]);
136
+ const ToolCallInFlightSchema = Type$1.Object({
137
+ callID: Type$1.String(),
138
+ name: Type$1.String(),
139
+ rawArgs: Type$1.Record(Type$1.String(), Type$1.Unknown()),
140
+ args: Type$1.Optional(Type$1.Unknown())
141
+ });
142
+ const ToolCallSchema = Type$1.Union([
143
+ ToolCallPendingPartSchema,
144
+ ToolCallRunningPartSchema,
145
+ ToolCallTerminalPartSchema
146
+ ]);
147
+ const UsageSchema = Type$1.Object({
148
+ input: Type$1.Number(),
149
+ output: Type$1.Number(),
150
+ cacheRead: Type$1.Number(),
151
+ cacheWrite: Type$1.Number(),
152
+ /** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */
153
+ cacheWrite1h: Type$1.Optional(Type$1.Number()),
154
+ reasoning: Type$1.Optional(Type$1.Number()),
155
+ totalTokens: Type$1.Number(),
156
+ cost: Type$1.Object({
157
+ input: Type$1.Number(),
158
+ output: Type$1.Number(),
159
+ cacheRead: Type$1.Number(),
160
+ cacheWrite: Type$1.Number(),
161
+ total: Type$1.Number()
162
+ })
163
+ });
164
+ const StopReasonSchema = Type$1.Union([
165
+ Type$1.Literal("stop"),
166
+ Type$1.Literal("length"),
167
+ Type$1.Literal("toolUse"),
168
+ Type$1.Literal("error"),
169
+ Type$1.Literal("aborted")
170
+ ]);
171
+ const UserMessageSchema = Type$1.Object({
172
+ messageId: Type$1.String(),
173
+ role: Type$1.Literal("user"),
174
+ time: Type$1.Object({ created: Type$1.Number() }),
175
+ parts: Type$1.Array(Type$1.Union([TextContentSchema, ImageContentSchema]))
176
+ });
177
+ const AssistantMessageSchema = Type$1.Object({
178
+ role: Type$1.Literal("assistant"),
179
+ protocol: KnownProviderEnumSchema,
180
+ provider: ProviderInfo,
181
+ model: Type$1.String(),
182
+ usage: UsageSchema,
183
+ stopReason: StopReasonSchema,
184
+ errorMessage: Type$1.Optional(Type$1.String()),
185
+ /**
186
+ * Structured, provider-independent failure details for a failed request.
187
+ * The schema is based on ai-sdk as the underlying provider wire protocol.
188
+ * Depends on ai-sdk
189
+ */
190
+ failure: Type$1.Optional(FailureSchema),
191
+ time: Type$1.Object({
192
+ created: Type$1.Number(),
193
+ completed: Type$1.Number()
194
+ }),
195
+ parts: Type$1.Array(Type$1.Union([
196
+ TextContentSchema,
197
+ ImageContentSchema,
198
+ ThinkingContentSchema,
199
+ ToolCallSchema
200
+ ])),
201
+ responseId: Type$1.Optional(Type$1.String()),
202
+ responseModel: Type$1.Optional(Type$1.String()),
203
+ messageId: Type$1.String()
204
+ });
205
+ const MessageSchema = Type$1.Union([UserMessageSchema, AssistantMessageSchema]);
206
+ function createMessageId() {
207
+ return uuidv7();
208
+ }
209
+ function createUserMessage(message) {
210
+ const { messageId = createMessageId(), ...rest } = message;
211
+ return {
212
+ messageId,
213
+ ...rest
214
+ };
215
+ }
216
+ function createAssistantMessage(message) {
217
+ const { messageId = createMessageId(), ...rest } = message;
218
+ return {
219
+ messageId,
220
+ ...rest
221
+ };
222
+ }
223
+ const GrammarVariantsSchema = Type$1.Partial(Type$1.Object({
224
+ openai_lark: Type$1.String(),
225
+ openai_regex: Type$1.String()
226
+ }));
227
+ const ConstrainedSamplingSchema = Type$1.Union([Type$1.Object({
228
+ type: Type$1.Literal("json_schema"),
229
+ strict: Type$1.Union([Type$1.Literal("prefer"), Type$1.Literal("require")])
230
+ }), Type$1.Object({
231
+ type: Type$1.Literal("grammar"),
232
+ variants: GrammarVariantsSchema
233
+ })]);
234
+ /**
235
+ * Generic tool definition with typed parameter schema.
236
+ * Usage:
237
+ *
238
+ * const search = Message.defineTool({
239
+ * name: "search",
240
+ * description: "Search documents",
241
+ * parameters: Type.Object({
242
+ * query: Type.String(),
243
+ * limit: Type.Optional(Type.Number()),
244
+ * }),
245
+ * });
246
+ *
247
+ * type SearchParams = Static<typeof search.parameters>;
248
+ */
249
+ const ToolSchema = Type$1.Object({
250
+ name: Type$1.String(),
251
+ description: Type$1.String(),
252
+ parameters: Type$1.Unsafe({}),
253
+ constrainedSampling: Type$1.Optional(Type$1.Union([Type$1.Literal(false), ConstrainedSamplingSchema]))
254
+ });
255
+ function defineTool(tool) {
256
+ return tool;
257
+ }
258
+ function resolveJsonSchemaConstraint(tool, compat) {
259
+ const config = tool.constrainedSampling;
260
+ if (!config || config.type !== "json_schema") return;
261
+ if (compat?.supportsStrictMode ?? true) return {
262
+ type: "json_schema",
263
+ strict: true
264
+ };
265
+ if (config.strict === "require") throw new Error(`tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);
266
+ }
267
+ const ContextSchema = Type$1.Object({
268
+ systemPrompt: Type$1.Optional(Type$1.String()),
269
+ messages: Type$1.Array(MessageSchema),
270
+ tools: Type$1.Optional(Type$1.Array(ToolSchema))
271
+ });
272
+ function isUnresolvedToolCall(toolCall) {
273
+ return toolCall.status === ToolStatusEnum.pending || toolCall.status === ToolStatusEnum.running;
274
+ }
275
+ function syntheticSkippedToolCall(toolCall) {
276
+ const { status: _status, partial: _partial, ...base } = toolCall;
277
+ return {
278
+ ...base,
279
+ status: ToolStatusEnum.skipped,
280
+ result: {
281
+ content: [{
282
+ type: "text",
283
+ text: "no result provided"
284
+ }],
285
+ isError: true
286
+ },
287
+ time: {
288
+ ...toolCall.time,
289
+ end: Math.max(toolCall.time.end, Date.now())
290
+ }
291
+ };
292
+ }
293
+ function transformMessages(messages, model, normalizeToolCallId) {
294
+ const toolCallIDMap = /* @__PURE__ */ new Map();
295
+ const transformed = [];
296
+ for (const msg of messages) {
297
+ if (msg.role === "user") {
298
+ transformed.push(msg);
299
+ continue;
300
+ }
301
+ const assistantMsg = msg;
302
+ const isSameModel = assistantMsg.provider.id === model.provider.id && assistantMsg.protocol === model.protocol && assistantMsg.model === model.id;
303
+ const parts = assistantMsg.parts.flatMap((block) => {
304
+ if (block.type === "thinking") {
305
+ if (isSameModel && block.thinkingSignature) return block;
306
+ if (!block.thinking || block.thinking.trim() === "") return [];
307
+ if (isSameModel) return block;
308
+ return {
309
+ type: "text",
310
+ text: block.thinking
311
+ };
312
+ }
313
+ if (block.type === "text") {
314
+ if (isSameModel) return block;
315
+ return {
316
+ type: "text",
317
+ text: block.text
318
+ };
319
+ }
320
+ if (block.type === "toolCall") {
321
+ const toolCall = block;
322
+ let normalizedToolCall = toolCall;
323
+ if (!isSameModel && toolCall.thoughtSignature) {
324
+ normalizedToolCall = { ...toolCall };
325
+ delete normalizedToolCall.thoughtSignature;
326
+ }
327
+ const normalizedID = toolCallIDMap.get(block.callID);
328
+ if (normalizedID && normalizedID !== block.callID) normalizedToolCall = {
329
+ ...normalizedToolCall,
330
+ callID: normalizedID
331
+ };
332
+ else if (!isSameModel && normalizeToolCallId) {
333
+ const nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);
334
+ if (nextID !== toolCall.callID) {
335
+ toolCallIDMap.set(toolCall.callID, nextID);
336
+ normalizedToolCall = {
337
+ ...normalizedToolCall,
338
+ callID: nextID
339
+ };
340
+ }
341
+ }
342
+ return normalizedToolCall;
343
+ }
344
+ return block;
345
+ }).map((block) => {
346
+ if (block.type === "toolCall" && isUnresolvedToolCall(block)) return syntheticSkippedToolCall(block);
347
+ return block;
348
+ });
349
+ transformed.push({
350
+ ...assistantMsg,
351
+ parts
352
+ });
353
+ }
354
+ return transformed;
355
+ }
356
+ //#endregion
3
357
  //#region src/providers/openai-codex/codex-tools.ts
4
358
  function appendOpenAICodexGrammarInputJsonDelta(buffer, inputProperty, nextInput, close) {
5
359
  if (buffer.closed) {
@@ -34,14 +388,7 @@ function inferGrammarInputProperty(parameters) {
34
388
  function resolveOpenAICodexToolConstraint(tool, compat) {
35
389
  const config = tool.constrainedSampling;
36
390
  if (!config) return void 0;
37
- if (config.type === "json_schema") {
38
- if (compat?.supportsStrictMode ?? true) return {
39
- type: "json_schema",
40
- strict: true
41
- };
42
- if (config.strict === "require") throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);
43
- return;
44
- }
391
+ if (config.type === "json_schema") return resolveJsonSchemaConstraint(tool, compat);
45
392
  if (!(compat?.supportsOpenAIGrammarTools ?? false)) return void 0;
46
393
  const lark = config.variants.openai_lark;
47
394
  const regex = config.variants.openai_regex;
@@ -57,7 +404,7 @@ function resolveOpenAICodexToolConstraint(tool, compat) {
57
404
  };
58
405
  } catch (error) {
59
406
  const message = error instanceof Error ? error.message : String(error);
60
- throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`);
407
+ throw new Error(`tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`);
61
408
  }
62
409
  }
63
410
  const openAICodexTools = { custom(args) {
@@ -71,22 +418,9 @@ const openAICodexTools = { custom(args) {
71
418
  }
72
419
  };
73
420
  } };
74
- const TOOL_SEARCH_MODEL_IDS = /* @__PURE__ */ new Set([
75
- "gpt-5.4",
76
- "gpt-5.4-mini",
77
- "gpt-5.5",
78
- "gpt-5.6-luna",
79
- "gpt-5.6-sol",
80
- "gpt-5.6-terra"
81
- ]);
82
- const ADDITIONAL_TOOLS_MODEL_IDS = /* @__PURE__ */ new Set([
83
- "gpt-5.6-luna",
84
- "gpt-5.6-sol",
85
- "gpt-5.6-terra"
86
- ]);
87
- function resolveOpenAICodexDeferredToolsMode(modelId, compat) {
88
- if (compat?.supportsAdditionalTools ?? ADDITIONAL_TOOLS_MODEL_IDS.has(modelId)) return "additional-tools";
89
- return compat?.supportsToolSearch ?? TOOL_SEARCH_MODEL_IDS.has(modelId) ? "tool-search" : void 0;
421
+ function resolveOpenAICodexDeferredToolsMode(compat) {
422
+ if (compat?.supportsAdditionalTools ?? false) return "additional-tools";
423
+ return compat?.supportsToolSearch ?? false ? "tool-search" : void 0;
90
424
  }
91
425
  function prepareOpenAICodexTools({ tools, toolChoice, deferredToolNames }) {
92
426
  const warnings = [];
@@ -171,27 +505,83 @@ function shortHash(value) {
171
505
  }
172
506
  //#endregion
173
507
  //#region src/providers/openai-codex/codex-error.ts
174
- function isTerminalRateLimitError(body) {
175
- return /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(body);
508
+ const asRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
509
+ const asString$1 = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
510
+ function normalizeErrorPayload(value) {
511
+ const record = asRecord$1(value);
512
+ const source = asRecord$1(record?.error) ?? record ?? {};
513
+ const code = asString$1(source.code);
514
+ const type = asString$1(source.type);
515
+ const message = asString$1(source.message);
516
+ const planType = asString$1(source.plan_type);
517
+ return { error: {
518
+ ...code !== void 0 && { code },
519
+ ...type !== void 0 && { type },
520
+ ...message !== void 0 && { message },
521
+ ...planType !== void 0 && { plan_type: planType },
522
+ ...typeof source.resets_at === "number" && { resets_at: source.resets_at }
523
+ } };
524
+ }
525
+ function parseErrorPayload(body) {
526
+ try {
527
+ return normalizeErrorPayload(JSON.parse(body));
528
+ } catch {
529
+ return;
530
+ }
531
+ }
532
+ function errorIdentifiers(error) {
533
+ return `${error?.code ?? ""} ${error?.type ?? ""}`.toLowerCase();
534
+ }
535
+ function hasIdentifier(error, identifiers) {
536
+ const value = errorIdentifiers(error);
537
+ return identifiers.some((identifier) => value.includes(identifier));
538
+ }
539
+ function isUsageLimitError(error) {
540
+ return hasIdentifier(error, [
541
+ "usage_limit_reached",
542
+ "gousagelimiterror",
543
+ "freeusagelimiterror"
544
+ ]);
545
+ }
546
+ function isTerminalRateLimitError(body, payload = parseErrorPayload(body)) {
547
+ return isUsageLimitError(payload?.error) || hasIdentifier(payload?.error, ["usage_not_included", "insufficient_quota"]) || /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|out of budget|quota exceeded|billing/i.test(body);
548
+ }
549
+ function streamErrorStatus(error) {
550
+ if (isUsageLimitError(error) || hasIdentifier(error, [
551
+ "usage_not_included",
552
+ "insufficient_quota",
553
+ "rate_limit"
554
+ ])) return 429;
555
+ if (hasIdentifier(error, ["server_is_overloaded", "slow_down"])) return 503;
556
+ if (hasIdentifier(error, [
557
+ "context_length_exceeded",
558
+ "invalid_prompt",
559
+ "bio_policy",
560
+ "cyber_policy",
561
+ "misalignment_policy_violation"
562
+ ])) return 400;
563
+ return 500;
564
+ }
565
+ function retryAfterHeader(message) {
566
+ const match = message?.match(/try again in\s*(\d+(?:\.\d+)?)\s*(s|ms|seconds?)/i);
567
+ if (!match) return {};
568
+ const value = Number(match[1]);
569
+ if (!Number.isFinite(value)) return {};
570
+ return { "retry-after": String(match[2]?.toLowerCase() === "ms" ? value / 1e3 : value) };
176
571
  }
177
572
  /**
178
- * Turn a Codex error payload into a human-friendly message. ChatGPT plan usage
179
- * limits deserve a clearer message than the raw backend error.
573
+ * Turn a Codex error payload into a human-friendly message. Only terminal
574
+ * ChatGPT plan exhaustion is rewritten; transient 429s retain backend detail.
180
575
  */
181
- function openAICodexErrorMessage(status, body, statusText) {
576
+ function openAICodexErrorMessage(_status, body, statusText) {
182
577
  let message = body || statusText || "OpenAI Codex request failed";
183
- try {
184
- const error = JSON.parse(body)?.error;
185
- if (error) {
186
- const code = error.code ?? error.type ?? "";
187
- if (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || status === 429) {
188
- const plan = error.plan_type ? ` (${error.plan_type.toLowerCase()} plan)` : "";
189
- const minutes = error.resets_at ? Math.max(0, Math.round((error.resets_at * 1e3 - Date.now()) / 6e4)) : void 0;
190
- return `You have hit your ChatGPT usage limit${plan}.${minutes === void 0 ? "" : ` Try again in ~${minutes} min.`}`.trim();
191
- }
192
- message = error.message || message;
193
- }
194
- } catch {}
578
+ const error = parseErrorPayload(body)?.error;
579
+ if (isUsageLimitError(error)) {
580
+ const plan = error?.plan_type ? ` (${error.plan_type.toLowerCase()} plan)` : "";
581
+ const minutes = error?.resets_at ? Math.max(0, Math.round((error.resets_at * 1e3 - Date.now()) / 6e4)) : void 0;
582
+ return `You have hit your ChatGPT usage limit${plan}.${minutes === void 0 ? "" : ` Try again in ~${minutes} min.`}`.trim();
583
+ }
584
+ if (error?.message) message = error.message;
195
585
  return message;
196
586
  }
197
587
  async function createOpenAICodexAPICallError(args) {
@@ -201,6 +591,7 @@ async function createOpenAICodexAPICallError(args) {
201
591
  response.headers.forEach((value, key) => {
202
592
  responseHeaders[key] = value;
203
593
  });
594
+ const data = parseErrorPayload(responseBody);
204
595
  return new APICallError({
205
596
  message: openAICodexErrorMessage(response.status, responseBody, response.statusText),
206
597
  url,
@@ -208,7 +599,40 @@ async function createOpenAICodexAPICallError(args) {
208
599
  statusCode: response.status,
209
600
  responseHeaders,
210
601
  responseBody,
211
- isRetryable: response.status === 408 || response.status === 409 || response.status === 429 && !isTerminalRateLimitError(responseBody) || response.status >= 500
602
+ ...data !== void 0 && { data },
603
+ isRetryable: response.status === 408 || response.status === 409 || response.status === 429 && !isTerminalRateLimitError(responseBody, data) || response.status >= 500
604
+ });
605
+ }
606
+ /** Map an error embedded in a successful SSE response to the same API error shape as HTTP failures. */
607
+ function createOpenAICodexStreamError(args) {
608
+ const { error: value, url, requestBodyValues } = args;
609
+ const data = normalizeErrorPayload(value);
610
+ const error = data.error;
611
+ const statusCode = streamErrorStatus(error);
612
+ const responseBody = JSON.stringify(data);
613
+ const responseHeaders = {
614
+ ...args.responseHeaders,
615
+ ...retryAfterHeader(error?.message)
616
+ };
617
+ return new APICallError({
618
+ message: openAICodexErrorMessage(statusCode, responseBody),
619
+ url,
620
+ requestBodyValues,
621
+ statusCode,
622
+ responseHeaders,
623
+ responseBody,
624
+ data,
625
+ isRetryable: statusCode >= 500 || hasIdentifier(error, ["rate_limit"]) && !isTerminalRateLimitError(responseBody, data)
626
+ });
627
+ }
628
+ /** A transport failure used when an SSE response ends without a terminal Responses event. */
629
+ function createOpenAICodexPrematureCloseError(args) {
630
+ return new APICallError({
631
+ message: "OpenAI Codex stream closed before response.completed",
632
+ url: args.url,
633
+ requestBodyValues: args.requestBodyValues,
634
+ ...args.responseHeaders !== void 0 && { responseHeaders: args.responseHeaders },
635
+ isRetryable: true
212
636
  });
213
637
  }
214
638
  //#endregion
@@ -294,9 +718,9 @@ function toolResultOutput(output, supportsImages) {
294
718
  }
295
719
  }
296
720
  function customToolInput(input, toolName, inputProperty) {
297
- if (typeof input !== "object" || input === null || Array.isArray(input)) throw new Error(`Custom tool "${toolName}" requires object input with string property "${inputProperty}".`);
721
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new Error(`custom tool "${toolName}" requires object input with string property "${inputProperty}".`);
298
722
  const value = input[inputProperty];
299
- if (typeof value !== "string") throw new Error(`Custom tool "${toolName}" requires string input property "${inputProperty}".`);
723
+ if (typeof value !== "string") throw new Error(`custom tool "${toolName}" requires string input property "${inputProperty}".`);
300
724
  return value;
301
725
  }
302
726
  function customToolOutput(output, supportsImages) {
@@ -346,7 +770,7 @@ function collectOpenAICodexDeferredToolNames(prompt) {
346
770
  return deferredNames;
347
771
  }
348
772
  function deferredToolCallId(toolCallId, names) {
349
- return `aikit_tool_load_${shortHash(`${toolCallId}:${names.join(",")}`)}`;
773
+ return `cdwrk_aikit_tool_${shortHash(`${toolCallId}:${names.join(",")}`)}`;
350
774
  }
351
775
  /**
352
776
  * Convert an AI SDK V3 prompt into the Codex Responses request shape.
@@ -432,7 +856,7 @@ function convertToOpenAICodexPrompt(prompt, options) {
432
856
  input.push({
433
857
  type: "message",
434
858
  role: "assistant",
435
- id: typeof messageId === "string" && messageId.length <= 64 ? messageId : `msg_aikit_${syntheticMessageCounter}`,
859
+ id: typeof messageId === "string" && messageId.length <= 64 ? messageId : `msg_cdwrk_aikit_${syntheticMessageCounter}`,
436
860
  content: [{
437
861
  type: "output_text",
438
862
  text: part.text,
@@ -486,40 +910,29 @@ function convertToOpenAICodexPrompt(prompt, options) {
486
910
  }
487
911
  //#endregion
488
912
  //#region src/providers/openai-codex/codex-sse.ts
489
- /**
490
- * Minimal SSE parsing for the Codex Responses endpoint. Each event is a JSON
491
- * payload on `data:` lines; `[DONE]` terminates the stream.
492
- */
913
+ /** Parse standards-compliant event streams from the Codex Responses endpoint. */
493
914
  function parseOpenAICodexSSEStream(body) {
494
915
  const decoder = new TextDecoder();
495
- let buffer = "";
496
- const parseChunk = (chunk, controller) => {
497
- const dataLines = chunk.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim());
498
- if (dataLines.length === 0) return;
499
- const data = dataLines.join("\n").trim();
500
- if (!data || data === "[DONE]") return;
501
- try {
502
- controller.enqueue(JSON.parse(data));
503
- } catch (cause) {
504
- controller.error(new Error(`Invalid OpenAI Codex SSE JSON: ${data.slice(0, 200)}`, { cause }));
505
- }
506
- };
507
916
  return body.pipeThrough(new TransformStream({
508
- transform(value, controller) {
509
- buffer += decoder.decode(value, { stream: true });
510
- let index = buffer.indexOf("\n\n");
511
- while (index !== -1) {
512
- const chunk = buffer.slice(0, index);
513
- buffer = buffer.slice(index + 2);
514
- parseChunk(chunk, controller);
515
- index = buffer.indexOf("\n\n");
516
- }
917
+ transform(chunk, controller) {
918
+ const text = decoder.decode(chunk, { stream: true });
919
+ if (text) controller.enqueue(text);
517
920
  },
518
921
  flush(controller) {
519
- buffer += decoder.decode();
520
- if (buffer.trim()) parseChunk(buffer, controller);
922
+ const text = decoder.decode();
923
+ if (text) controller.enqueue(text);
924
+ }
925
+ })).pipeThrough(new EventSourceParserStream({ onError: "terminate" })).pipeThrough(new TransformStream({ transform(event, controller) {
926
+ const data = event.data.trim();
927
+ if (!data || data === "[DONE]") return;
928
+ try {
929
+ const parsed = JSON.parse(data);
930
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new TypeError("codex SSE data must be a JSON object");
931
+ controller.enqueue(parsed);
932
+ } catch (cause) {
933
+ controller.error(new Error(`invalid OpenAI Codex SSE JSON: ${data.slice(0, 200)}`, { cause }));
521
934
  }
522
- }));
935
+ } }));
523
936
  }
524
937
  //#endregion
525
938
  //#region src/providers/openai-codex/codex-usage.ts
@@ -657,12 +1070,12 @@ var OpenAICodexLanguageModel = class {
657
1070
  type: "unsupported",
658
1071
  feature: "maxOutputTokens"
659
1072
  });
660
- if (options.responseFormat && options.responseFormat.type !== "text") warnings.push({
1073
+ if (options.responseFormat?.type === "json" && options.responseFormat.schema === void 0) warnings.push({
661
1074
  type: "unsupported",
662
1075
  feature: "responseFormat"
663
1076
  });
664
1077
  const codexOptions = options.providerOptions?.["openai-codex"] ?? {};
665
- const deferredToolsMode = resolveOpenAICodexDeferredToolsMode(this.modelId, this.config.compat);
1078
+ const deferredToolsMode = resolveOpenAICodexDeferredToolsMode(this.config.compat);
666
1079
  const deferredToolNames = deferredToolsMode ? collectOpenAICodexDeferredToolNames(options.prompt) : void 0;
667
1080
  const tools = prepareOpenAICodexTools({
668
1081
  tools: options.tools,
@@ -673,9 +1086,16 @@ var OpenAICodexLanguageModel = class {
673
1086
  deferredTools: tools.deferredCodexTools,
674
1087
  ...deferredToolsMode !== void 0 && { deferredToolsMode },
675
1088
  grammarToolInputProperties: tools.grammarToolInputProperties,
676
- supportsImages: this.config.compat?.supportsImages ?? this.modelId !== "gpt-5.3-codex-spark"
1089
+ supportsImages: this.config.compat?.supportsImages ?? false
677
1090
  });
678
1091
  warnings.push(...tools.warnings);
1092
+ const text = { verbosity: codexOptions.textVerbosity ?? "low" };
1093
+ if (options.responseFormat?.type === "json" && options.responseFormat.schema !== void 0) text.format = {
1094
+ type: "json_schema",
1095
+ strict: true,
1096
+ schema: options.responseFormat.schema,
1097
+ name: options.responseFormat.name ?? "codex_output_schema"
1098
+ };
679
1099
  const args = {
680
1100
  model: this.modelId,
681
1101
  store: false,
@@ -683,12 +1103,12 @@ var OpenAICodexLanguageModel = class {
683
1103
  input,
684
1104
  tool_choice: tools.codexToolChoice ?? "auto",
685
1105
  parallel_tool_calls: true,
686
- include: codexOptions.include ?? ["reasoning.encrypted_content"],
687
- text: { verbosity: codexOptions.textVerbosity ?? "low" }
1106
+ include: ["reasoning.encrypted_content"],
1107
+ text
688
1108
  };
689
1109
  if (tools.codexTools) args.tools = tools.codexTools;
690
1110
  if (options.temperature != null) args.temperature = options.temperature;
691
- const promptCacheKey = clampOpenAICodexPromptCacheKey(codexOptions.promptCacheKey ?? this.config.sessionId);
1111
+ const promptCacheKey = clampOpenAICodexPromptCacheKey(this.config.sessionId);
692
1112
  if (promptCacheKey) args.prompt_cache_key = promptCacheKey;
693
1113
  const serviceTier = codexOptions.serviceTier ?? this.config.serviceTier;
694
1114
  if (serviceTier) args.service_tier = serviceTier;
@@ -813,18 +1233,22 @@ var OpenAICodexLanguageModel = class {
813
1233
  url,
814
1234
  requestBodyValues: body
815
1235
  });
816
- if (!response.body) throw new Error("OpenAI Codex response has no body");
1236
+ if (!response.body) throw new Error("openAI codex response has no body");
817
1237
  const responseHeaders = {};
818
1238
  response.headers.forEach((value, key) => {
819
1239
  responseHeaders[key] = value;
820
1240
  });
821
1241
  return {
822
- stream: parseOpenAICodexSSEStream(response.body).pipeThrough(this.createTransformStream(warnings, options.includeRawChunks ?? false, grammarToolInputProperties)),
1242
+ stream: parseOpenAICodexSSEStream(response.body).pipeThrough(this.createTransformStream(warnings, options.includeRawChunks ?? false, grammarToolInputProperties, {
1243
+ url,
1244
+ requestBodyValues: body,
1245
+ responseHeaders
1246
+ })),
823
1247
  request: { body },
824
1248
  response: { headers: responseHeaders }
825
1249
  };
826
1250
  }
827
- createTransformStream(warnings, includeRawChunks, grammarToolInputProperties) {
1251
+ createTransformStream(warnings, includeRawChunks, grammarToolInputProperties, request) {
828
1252
  let finishReason = {
829
1253
  unified: "other",
830
1254
  raw: void 0
@@ -832,6 +1256,7 @@ var OpenAICodexLanguageModel = class {
832
1256
  let usage;
833
1257
  let hasToolCalls = false;
834
1258
  let finished = false;
1259
+ let servedServiceTier;
835
1260
  const toolCallIdsByItemId = /* @__PURE__ */ new Map();
836
1261
  const customToolInputsByItemId = /* @__PURE__ */ new Map();
837
1262
  const finish = (controller) => {
@@ -840,8 +1265,18 @@ var OpenAICodexLanguageModel = class {
840
1265
  controller.enqueue({
841
1266
  type: "finish",
842
1267
  finishReason,
843
- usage: convertOpenAICodexUsage(usage)
1268
+ usage: convertOpenAICodexUsage(usage),
1269
+ ...servedServiceTier === void 0 ? {} : { providerMetadata: { "openai-codex": { serviceTier: servedServiceTier } } }
1270
+ });
1271
+ };
1272
+ const fail = (controller, error) => {
1273
+ if (finished) return;
1274
+ finished = true;
1275
+ controller.enqueue({
1276
+ type: "error",
1277
+ error
844
1278
  });
1279
+ controller.terminate();
845
1280
  };
846
1281
  const handleOutputItemAdded = (item, controller) => {
847
1282
  const itemType = asString(item.type);
@@ -1034,10 +1469,10 @@ var OpenAICodexLanguageModel = class {
1034
1469
  break;
1035
1470
  }
1036
1471
  case "response.completed":
1037
- case "response.done":
1038
1472
  case "response.incomplete": {
1039
1473
  const response = asRecord(event.response);
1040
1474
  usage = response?.usage ?? usage;
1475
+ servedServiceTier = asString(response?.service_tier) ?? servedServiceTier;
1041
1476
  const status = asString(response?.status) ?? (type === "response.incomplete" ? "incomplete" : "completed");
1042
1477
  const incompleteReason = asString(asRecord(response?.incomplete_details)?.reason);
1043
1478
  finishReason = mapOpenAICodexFinishReason(status, hasToolCalls, incompleteReason);
@@ -1051,29 +1486,31 @@ var OpenAICodexLanguageModel = class {
1051
1486
  unified: "error",
1052
1487
  raw: "failed"
1053
1488
  };
1054
- controller.enqueue({
1055
- type: "error",
1056
- error: new Error(asString(error?.message) ?? "OpenAI Codex response failed")
1057
- });
1489
+ fail(controller, createOpenAICodexStreamError({
1490
+ error: error ?? { message: "OpenAI Codex response failed" },
1491
+ ...request
1492
+ }));
1058
1493
  break;
1059
1494
  }
1060
- case "error": {
1061
- const code = asString(event.code);
1062
- const message = asString(event.message);
1495
+ case "error":
1063
1496
  finishReason = {
1064
1497
  unified: "error",
1065
- raw: code ?? "error"
1498
+ raw: asString(event.code) ?? "error"
1066
1499
  };
1067
- controller.enqueue({
1068
- type: "error",
1069
- error: /* @__PURE__ */ new Error(`OpenAI Codex error${code ? ` ${code}` : ""}: ${message ?? JSON.stringify(event)}`)
1070
- });
1071
- break;
1072
- }
1500
+ fail(controller, createOpenAICodexStreamError({
1501
+ error: event,
1502
+ ...request
1503
+ }));
1073
1504
  }
1074
1505
  },
1075
1506
  flush(controller) {
1076
- finish(controller);
1507
+ if (!finished) {
1508
+ finished = true;
1509
+ controller.enqueue({
1510
+ type: "error",
1511
+ error: createOpenAICodexPrematureCloseError(request)
1512
+ });
1513
+ }
1077
1514
  }
1078
1515
  });
1079
1516
  }
@@ -1122,7 +1559,7 @@ function createOpenAICodex(options = {}) {
1122
1559
  ...options.compat !== void 0 && { compat: options.compat }
1123
1560
  });
1124
1561
  const provider = function(modelId) {
1125
- if (new.target) throw new Error("The OpenAI Codex model function cannot be called with the new keyword.");
1562
+ if (new.target) throw new Error("openAI codex model function cannot be called with the new keyword.");
1126
1563
  return createLanguageModel(modelId);
1127
1564
  };
1128
1565
  provider.specificationVersion = "v3";
@@ -1153,6 +1590,6 @@ function createOpenAICodex(options = {}) {
1153
1590
  */
1154
1591
  const openaiCodex = createOpenAICodex();
1155
1592
  //#endregion
1156
- export { appendOpenAICodexGrammarInputJsonDelta as _, OpenAICodexLanguageModel as a, resolveOpenAICodexDeferredToolsMode as b, convertOpenAICodexUsage as c, convertToOpenAICodexPrompt as d, joinToolCallId as f, shortHash as g, openAICodexErrorMessage as h, OPENAI_CODEX_DEFAULT_BASE_URL as i, mapOpenAICodexFinishReason as l, createOpenAICodexAPICallError as m, createOpenAICodex as n, clampOpenAICodexPromptCacheKey as o, splitToolCallId as p, openaiCodex as r, resolveOpenAICodexUrl as s, OPENAI_CODEX_API_KEY_ENV as t, collectOpenAICodexDeferredToolNames as u, openAICodexTools as v, resolveOpenAICodexToolConstraint as x, prepareOpenAICodexTools as y };
1593
+ export { ToolCallSchema as C, transformMessages as D, resolveJsonSchemaConstraint as E, AssistantMessageSchema as S, message_exports as T, appendOpenAICodexGrammarInputJsonDelta as _, OpenAICodexLanguageModel as a, resolveOpenAICodexDeferredToolsMode as b, convertOpenAICodexUsage as c, convertToOpenAICodexPrompt as d, joinToolCallId as f, shortHash as g, openAICodexErrorMessage as h, OPENAI_CODEX_DEFAULT_BASE_URL as i, mapOpenAICodexFinishReason as l, createOpenAICodexAPICallError as m, createOpenAICodex as n, clampOpenAICodexPromptCacheKey as o, splitToolCallId as p, openaiCodex as r, resolveOpenAICodexUrl as s, OPENAI_CODEX_API_KEY_ENV as t, collectOpenAICodexDeferredToolNames as u, openAICodexTools as v, createAssistantMessage as w, resolveOpenAICodexToolConstraint as x, prepareOpenAICodexTools as y };
1157
1594
 
1158
- //# sourceMappingURL=openai-codex-_3XkJ4bs.mjs.map
1595
+ //# sourceMappingURL=openai-codex-t4B7g-gv.mjs.map