@ebowwa/codespaces-types 1.4.0 → 1.4.2

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/runtime/ai.js CHANGED
@@ -1,505 +1,323 @@
1
- "use strict";
2
- /**
3
- * Zod schemas for AI module runtime validation
4
- *
5
- * Provides:
6
- * - Runtime type validation for all AI operations
7
- * - Type inference for TypeScript types
8
- * - Safe parsing with error handling
9
- * - Streaming support for Server-Sent Events
10
- * - Reusable schemas across multiple AI providers
11
- */
12
- var __generator = (this && this.__generator) || function (thisArg, body) {
13
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
14
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
15
- function verb(n) { return function (v) { return step([n, v]); }; }
16
- function step(op) {
17
- if (f) throw new TypeError("Generator is already executing.");
18
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
19
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
20
- if (y = 0, t) op = [op[0] & 2, t.value];
21
- switch (op[0]) {
22
- case 0: case 1: t = op; break;
23
- case 4: _.label++; return { value: op[1], done: false };
24
- case 5: _.label++; y = op[1]; op = [0]; continue;
25
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
26
- default:
27
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
28
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
29
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
30
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
31
- if (t[2]) _.ops.pop();
32
- _.trys.pop(); continue;
33
- }
34
- op = body.call(thisArg, _);
35
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
36
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
37
- }
38
- };
39
- var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
40
- var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
41
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
42
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
43
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
44
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
45
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
46
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
47
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
48
- function fulfill(value) { resume("next", value); }
49
- function reject(value) { resume("throw", value); }
50
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
51
- };
52
- Object.defineProperty(exports, "__esModule", { value: true });
53
- exports.ErrorTypeSchema = exports.APIErrorResponseSchema = exports.StreamChunkSchema = exports.RawStreamChunkSchema = exports.StreamChunkTypeSchema = exports.StreamDeltaSchema = exports.AIChatResponseSchema = exports.AIResponseSchema = exports.ChatCompletionResponseSchema = exports.RawChatCompletionResponseSchema = exports.RawChoiceSchema = exports.LatencyInfoSchema = exports.AIChatModuleRequestSchema = exports.AIRequestSchema = exports.ChatCompletionOptionsSchema = exports.BaseAIRequestOptionsSchema = exports.RawUsageSchema = exports.TokenUsageSchema = exports.ChatMessageSchema = exports.ChatMessageRoleSchema = void 0;
54
- exports.validateChatMessage = validateChatMessage;
55
- exports.validateChatMessages = validateChatMessages;
56
- exports.validateChatCompletionOptions = validateChatCompletionOptions;
57
- exports.validateRawResponse = validateRawResponse;
58
- exports.convertUsage = convertUsage;
59
- exports.categorizeError = categorizeError;
60
- exports.parseSSERow = parseSSERow;
61
- exports.parseSSEStream = parseSSEStream;
62
- var zod_1 = require("zod");
63
- // ============================================================================
64
- // BASE SCHEMAS
65
- // ============================================================================
66
- /**
67
- * Chat message role (OpenAI-compatible)
68
- */
69
- exports.ChatMessageRoleSchema = zod_1.z.enum(["system", "user", "assistant"]);
70
- /**
71
- * Base chat message (OpenAI-compatible)
72
- */
73
- exports.ChatMessageSchema = zod_1.z.object({
74
- role: exports.ChatMessageRoleSchema,
75
- content: zod_1.z.string(),
1
+ // @bun
2
+ // runtime/ai.ts
3
+ import { z } from "zod";
4
+ var ChatMessageRoleSchema = z.enum(["system", "user", "assistant", "tool"]);
5
+ var ToolCallSchema = z.object({
6
+ id: z.string(),
7
+ type: z.literal("function"),
8
+ function: z.object({
9
+ name: z.string(),
10
+ arguments: z.string()
11
+ })
76
12
  });
77
- /**
78
- * Token usage information (camelCase)
79
- */
80
- exports.TokenUsageSchema = zod_1.z.object({
81
- promptTokens: zod_1.z.number().int().nonnegative(),
82
- completionTokens: zod_1.z.number().int().nonnegative(),
83
- totalTokens: zod_1.z.number().int().nonnegative(),
13
+ var ChatMessageSchema = z.object({
14
+ role: ChatMessageRoleSchema,
15
+ content: z.string(),
16
+ tool_calls: z.array(ToolCallSchema).optional(),
17
+ tool_call_id: z.string().optional()
84
18
  });
85
- /**
86
- * Raw API usage (snake_case from most APIs)
87
- */
88
- exports.RawUsageSchema = zod_1.z.object({
89
- prompt_tokens: zod_1.z.number().int().nonnegative(),
90
- completion_tokens: zod_1.z.number().int().nonnegative(),
91
- total_tokens: zod_1.z.number().int().nonnegative(),
19
+ var TokenUsageSchema = z.object({
20
+ promptTokens: z.number().int().nonnegative(),
21
+ completionTokens: z.number().int().nonnegative(),
22
+ totalTokens: z.number().int().nonnegative()
92
23
  });
93
- // ============================================================================
94
- // REQUEST SCHEMAS
95
- // ============================================================================
96
- /**
97
- * Base AI request options shared across all AI requests
98
- */
99
- exports.BaseAIRequestOptionsSchema = zod_1.z.object({
100
- model: zod_1.z.string().optional(),
101
- temperature: zod_1.z.number().min(0).max(2).optional(),
102
- maxTokens: zod_1.z.number().int().positive().optional(),
24
+ var RawUsageSchema = z.object({
25
+ prompt_tokens: z.number().int().nonnegative(),
26
+ completion_tokens: z.number().int().nonnegative(),
27
+ total_tokens: z.number().int().nonnegative()
103
28
  });
104
- /**
105
- * Chat completion options (extends base with stream/timeout/retry)
106
- */
107
- exports.ChatCompletionOptionsSchema = exports.BaseAIRequestOptionsSchema.extend({
108
- stream: zod_1.z.boolean().optional().default(false),
109
- timeout: zod_1.z.number().int().positive().optional().default(30000),
110
- maxRetries: zod_1.z.number().int().nonnegative().optional().default(3),
29
+ var BaseAIRequestOptionsSchema = z.object({
30
+ model: z.string().optional(),
31
+ temperature: z.number().min(0).max(2).optional(),
32
+ maxTokens: z.number().int().positive().optional()
111
33
  });
112
- /**
113
- * Simple prompt-based AI request
114
- */
115
- exports.AIRequestSchema = exports.BaseAIRequestOptionsSchema.extend({
116
- prompt: zod_1.z.string(),
117
- systemPrompt: zod_1.z.string().optional(),
34
+ var ChatCompletionOptionsSchema = BaseAIRequestOptionsSchema.extend({
35
+ stream: z.boolean().optional().default(false),
36
+ timeout: z.number().int().positive().optional().default(30000),
37
+ maxRetries: z.number().int().nonnegative().optional().default(3)
118
38
  });
119
- /**
120
- * Multi-turn chat request
121
- */
122
- exports.AIChatModuleRequestSchema = exports.BaseAIRequestOptionsSchema.extend({
123
- messages: zod_1.z.array(exports.ChatMessageSchema).min(1),
39
+ var AIRequestSchema = BaseAIRequestOptionsSchema.extend({
40
+ prompt: z.string(),
41
+ systemPrompt: z.string().optional()
124
42
  });
125
- // ============================================================================
126
- // RESPONSE SCHEMAS
127
- // ============================================================================
128
- /**
129
- * Latency information
130
- */
131
- exports.LatencyInfoSchema = zod_1.z.object({
132
- totalMs: zod_1.z.number().nonnegative(),
133
- formatted: zod_1.z.string(),
43
+ var AIChatModuleRequestSchema = BaseAIRequestOptionsSchema.extend({
44
+ messages: z.array(ChatMessageSchema).min(1)
134
45
  });
135
- /**
136
- * Raw API response choice (snake_case from API)
137
- */
138
- exports.RawChoiceSchema = zod_1.z.object({
139
- index: zod_1.z.number().int().nonnegative(),
140
- message: zod_1.z.object({
141
- role: zod_1.z.string(),
142
- content: zod_1.z.string(),
143
- }),
144
- finish_reason: zod_1.z.string(),
46
+ var LatencyInfoSchema = z.object({
47
+ totalMs: z.number().nonnegative(),
48
+ formatted: z.string()
145
49
  });
146
- /**
147
- * Raw chat completion response from API (snake_case)
148
- */
149
- exports.RawChatCompletionResponseSchema = zod_1.z.object({
150
- id: zod_1.z.string(),
151
- object: zod_1.z.string(),
152
- created: zod_1.z.number().int().nonnegative(),
153
- model: zod_1.z.string(),
154
- choices: zod_1.z.array(exports.RawChoiceSchema).min(1),
155
- usage: exports.RawUsageSchema.optional(),
50
+ var RawChoiceSchema = z.object({
51
+ index: z.number().int().nonnegative(),
52
+ message: z.object({
53
+ role: z.string(),
54
+ content: z.string().nullable().optional(),
55
+ tool_calls: z.array(ToolCallSchema).optional()
56
+ }),
57
+ finish_reason: z.string().nullable()
156
58
  });
157
- /**
158
- * Chat completion response (internal camelCase)
159
- */
160
- exports.ChatCompletionResponseSchema = zod_1.z.object({
161
- id: zod_1.z.string(),
162
- object: zod_1.z.string(),
163
- created: zod_1.z.number().int().nonnegative(),
164
- model: zod_1.z.string(),
165
- choices: zod_1.z
166
- .array(zod_1.z.object({
167
- index: zod_1.z.number().int().nonnegative(),
168
- message: zod_1.z.object({
169
- role: zod_1.z.string(),
170
- content: zod_1.z.string(),
171
- }),
172
- finish_reason: zod_1.z.string(),
173
- }))
174
- .min(1),
175
- usage: exports.TokenUsageSchema.optional(),
176
- latency: exports.LatencyInfoSchema.optional(),
59
+ var RawChatCompletionResponseSchema = z.object({
60
+ id: z.string(),
61
+ object: z.string(),
62
+ created: z.number().int().nonnegative(),
63
+ model: z.string(),
64
+ choices: z.array(RawChoiceSchema).min(1),
65
+ usage: RawUsageSchema.optional()
177
66
  });
178
- /**
179
- * Simple AI response
180
- */
181
- exports.AIResponseSchema = zod_1.z.object({
182
- success: zod_1.z.boolean(),
183
- content: zod_1.z.string().optional(),
184
- error: zod_1.z.string().optional(),
185
- usage: exports.TokenUsageSchema.optional(),
67
+ var ChatCompletionResponseSchema = z.object({
68
+ id: z.string(),
69
+ object: z.string(),
70
+ created: z.number().int().nonnegative(),
71
+ model: z.string(),
72
+ choices: z.array(z.object({
73
+ index: z.number().int().nonnegative(),
74
+ message: z.object({
75
+ role: z.string(),
76
+ content: z.string().nullable().optional(),
77
+ tool_calls: z.array(ToolCallSchema).optional()
78
+ }),
79
+ finish_reason: z.string().nullable()
80
+ })).min(1),
81
+ usage: TokenUsageSchema.optional(),
82
+ latency: LatencyInfoSchema.optional()
186
83
  });
187
- /**
188
- * Chat response
189
- */
190
- exports.AIChatResponseSchema = zod_1.z.object({
191
- success: zod_1.z.boolean(),
192
- message: zod_1.z.string().optional(),
193
- usage: exports.TokenUsageSchema.optional(),
194
- error: zod_1.z.string().optional(),
84
+ var AIResponseSchema = z.object({
85
+ success: z.boolean(),
86
+ content: z.string().optional(),
87
+ error: z.string().optional(),
88
+ usage: TokenUsageSchema.optional()
195
89
  });
196
- // ============================================================================
197
- // STREAMING SCHEMAS
198
- // ============================================================================
199
- /**
200
- * Stream delta content (incremental content from streaming responses)
201
- */
202
- exports.StreamDeltaSchema = zod_1.z.object({
203
- role: zod_1.z.string().optional(),
204
- content: zod_1.z.string().optional(),
90
+ var AIChatResponseSchema = z.object({
91
+ success: z.boolean(),
92
+ message: z.string().optional(),
93
+ usage: TokenUsageSchema.optional(),
94
+ error: z.string().optional()
205
95
  });
206
- /**
207
- * Stream chunk type
208
- */
209
- exports.StreamChunkTypeSchema = zod_1.z.enum(["text", "done", "error"]);
210
- /**
211
- * Raw stream chunk from API (snake_case)
212
- */
213
- exports.RawStreamChunkSchema = zod_1.z.object({
214
- id: zod_1.z.string(),
215
- object: zod_1.z.string(),
216
- created: zod_1.z.number().int().nonnegative(),
217
- model: zod_1.z.string(),
218
- choices: zod_1.z
219
- .array(zod_1.z.object({
220
- index: zod_1.z.number().int().nonnegative(),
221
- delta: exports.StreamDeltaSchema,
222
- finish_reason: zod_1.z.string().nullable().optional(),
223
- }))
224
- .min(1),
225
- usage: exports.RawUsageSchema.optional(),
96
+ var StreamDeltaSchema = z.object({
97
+ role: z.string().optional(),
98
+ content: z.string().optional()
226
99
  });
227
- /**
228
- * Processed stream chunk (internal camelCase)
229
- */
230
- exports.StreamChunkSchema = zod_1.z.object({
231
- type: exports.StreamChunkTypeSchema,
232
- id: zod_1.z.string().optional(),
233
- content: zod_1.z.string().optional(),
234
- finishReason: zod_1.z.string().optional(),
235
- usage: exports.TokenUsageSchema.optional(),
236
- error: zod_1.z.string().optional(),
100
+ var StreamChunkTypeSchema = z.enum(["text", "done", "error"]);
101
+ var RawStreamChunkSchema = z.object({
102
+ id: z.string(),
103
+ object: z.string(),
104
+ created: z.number().int().nonnegative(),
105
+ model: z.string(),
106
+ choices: z.array(z.object({
107
+ index: z.number().int().nonnegative(),
108
+ delta: StreamDeltaSchema,
109
+ finish_reason: z.string().nullable().optional()
110
+ })).min(1),
111
+ usage: RawUsageSchema.optional()
237
112
  });
238
- // ============================================================================
239
- // ERROR SCHEMAS
240
- // ============================================================================
241
- /**
242
- * Generic API error response (most providers use this format)
243
- */
244
- exports.APIErrorResponseSchema = zod_1.z.object({
245
- error: zod_1.z
246
- .object({
247
- message: zod_1.z.string(),
248
- type: zod_1.z.string().optional(),
249
- code: zod_1.z.string().optional(),
250
- })
251
- .optional(),
113
+ var StreamChunkSchema = z.object({
114
+ type: StreamChunkTypeSchema,
115
+ id: z.string().optional(),
116
+ content: z.string().optional(),
117
+ finishReason: z.string().optional(),
118
+ usage: TokenUsageSchema.optional(),
119
+ error: z.string().optional()
252
120
  });
253
- /**
254
- * Error types categorization
255
- */
256
- exports.ErrorTypeSchema = zod_1.z.enum([
257
- "timeout",
258
- "auth",
259
- "rate_limit",
260
- "network",
261
- "validation",
262
- "unknown",
121
+ var APIErrorResponseSchema = z.object({
122
+ error: z.object({
123
+ message: z.string(),
124
+ type: z.string().optional(),
125
+ code: z.string().optional()
126
+ }).optional()
127
+ });
128
+ var ErrorTypeSchema = z.enum([
129
+ "timeout",
130
+ "auth",
131
+ "rate_limit",
132
+ "network",
133
+ "validation",
134
+ "unknown"
263
135
  ]);
264
- // ============================================================================
265
- // VALIDATION HELPERS
266
- // ============================================================================
267
- /**
268
- * Validate chat message
269
- */
270
136
  function validateChatMessage(data) {
271
- return exports.ChatMessageSchema.safeParse(data);
137
+ return ChatMessageSchema.safeParse(data);
272
138
  }
273
- /**
274
- * Validate chat messages array
275
- */
276
139
  function validateChatMessages(data) {
277
- return zod_1.z.array(exports.ChatMessageSchema).min(1).safeParse(data);
140
+ return z.array(ChatMessageSchema).min(1).safeParse(data);
278
141
  }
279
- /**
280
- * Validate chat completion options
281
- */
282
142
  function validateChatCompletionOptions(data) {
283
- return exports.ChatCompletionOptionsSchema.safeParse(data);
143
+ return ChatCompletionOptionsSchema.safeParse(data);
284
144
  }
285
- /**
286
- * Validate raw API response
287
- */
288
145
  function validateRawResponse(data) {
289
- return exports.RawChatCompletionResponseSchema.safeParse(data);
146
+ return RawChatCompletionResponseSchema.safeParse(data);
290
147
  }
291
- /**
292
- * Validate and convert raw usage to internal format
293
- */
294
148
  function convertUsage(raw) {
295
- var result = exports.RawUsageSchema.safeParse(raw);
296
- if (!result.success)
297
- return null;
298
- return {
299
- promptTokens: result.data.prompt_tokens,
300
- completionTokens: result.data.completion_tokens,
301
- totalTokens: result.data.total_tokens,
302
- };
149
+ const result = RawUsageSchema.safeParse(raw);
150
+ if (!result.success)
151
+ return null;
152
+ return {
153
+ promptTokens: result.data.prompt_tokens,
154
+ completionTokens: result.data.completion_tokens,
155
+ totalTokens: result.data.total_tokens
156
+ };
303
157
  }
304
- /**
305
- * Categorize error from unknown data
306
- * Generic error categorization that works across providers
307
- */
308
158
  function categorizeError(data) {
309
- if (data instanceof Error) {
310
- if (data.message.includes("timeout")) {
311
- return "timeout";
312
- }
313
- if (data.message.includes("unauthorized") || data.message.includes("401")) {
314
- return "auth";
315
- }
316
- if (data.message.includes("rate limit") || data.message.includes("429")) {
317
- return "rate_limit";
318
- }
319
- if (data instanceof TypeError || data.message.includes("fetch")) {
320
- return "network";
321
- }
159
+ if (data instanceof Error) {
160
+ if (data.message.includes("timeout")) {
161
+ return "timeout";
162
+ }
163
+ if (data.message.includes("unauthorized") || data.message.includes("401")) {
164
+ return "auth";
322
165
  }
323
- var errorResult = exports.APIErrorResponseSchema.safeParse(data);
324
- if (errorResult.success && errorResult.data.error) {
325
- var errorMsg = errorResult.data.error.message.toLowerCase();
326
- if (errorMsg.includes("timeout"))
327
- return "timeout";
328
- if (errorMsg.includes("unauthorized") ||
329
- errorMsg.includes("invalid api key") ||
330
- errorMsg.includes("401"))
331
- return "auth";
332
- if (errorMsg.includes("rate limit") || errorMsg.includes("429"))
333
- return "rate_limit";
166
+ if (data.message.includes("rate limit") || data.message.includes("429")) {
167
+ return "rate_limit";
334
168
  }
335
- return "unknown";
169
+ if (data instanceof TypeError || data.message.includes("fetch")) {
170
+ return "network";
171
+ }
172
+ }
173
+ const errorResult = APIErrorResponseSchema.safeParse(data);
174
+ if (errorResult.success && errorResult.data.error) {
175
+ const errorMsg = errorResult.data.error.message.toLowerCase();
176
+ if (errorMsg.includes("timeout"))
177
+ return "timeout";
178
+ if (errorMsg.includes("unauthorized") || errorMsg.includes("invalid api key") || errorMsg.includes("401"))
179
+ return "auth";
180
+ if (errorMsg.includes("rate limit") || errorMsg.includes("429"))
181
+ return "rate_limit";
182
+ }
183
+ return "unknown";
336
184
  }
337
- // ============================================================================
338
- // STREAMING HELPERS
339
- // ============================================================================
340
- /**
341
- * Parse a single SSE line
342
- * Returns null if line is empty or just whitespace
343
- */
344
185
  function parseSSERow(line) {
345
- var trimmed = line.trim();
346
- if (!trimmed || trimmed === "")
347
- return null;
348
- if (!trimmed.startsWith("data: "))
349
- return null;
350
- var data = trimmed.slice(6);
351
- if (data === "[DONE]")
352
- return data;
186
+ const trimmed = line.trim();
187
+ if (!trimmed || trimmed === "")
188
+ return null;
189
+ if (!trimmed.startsWith("data: "))
190
+ return null;
191
+ const data = trimmed.slice(6);
192
+ if (data === "[DONE]")
353
193
  return data;
194
+ return data;
354
195
  }
355
- /**
356
- * Parse SSE response body and yield stream chunks
357
- * Converts raw SSE lines to processed StreamChunk objects
358
- */
359
- function parseSSEStream(response) {
360
- return __asyncGenerator(this, arguments, function parseSSEStream_1() {
361
- var reader, decoder, buffer, _a, done, value, lines, _i, lines_1, line, data, raw, rawChunkResult, rawChunk, delta, usage, error_1;
362
- return __generator(this, function (_b) {
363
- switch (_b.label) {
364
- case 0:
365
- if (!!response.body) return [3 /*break*/, 4];
366
- return [4 /*yield*/, __await({
367
- type: "error",
368
- error: "Response body is null",
369
- })];
370
- case 1: return [4 /*yield*/, _b.sent()];
371
- case 2:
372
- _b.sent();
373
- return [4 /*yield*/, __await(void 0)];
374
- case 3: return [2 /*return*/, _b.sent()];
375
- case 4:
376
- reader = response.body.getReader();
377
- decoder = new TextDecoder();
378
- buffer = "";
379
- _b.label = 5;
380
- case 5:
381
- _b.trys.push([5, , 24, 25]);
382
- _b.label = 6;
383
- case 6:
384
- if (!true) return [3 /*break*/, 23];
385
- return [4 /*yield*/, __await(reader.read())];
386
- case 7:
387
- _a = _b.sent(), done = _a.done, value = _a.value;
388
- if (done)
389
- return [3 /*break*/, 23];
390
- buffer += decoder.decode(value, { stream: true });
391
- lines = buffer.split("\n");
392
- buffer = lines.pop() || ""; // Keep the last incomplete line in buffer
393
- _i = 0, lines_1 = lines;
394
- _b.label = 8;
395
- case 8:
396
- if (!(_i < lines_1.length)) return [3 /*break*/, 22];
397
- line = lines_1[_i];
398
- data = parseSSERow(line);
399
- if (!data)
400
- return [3 /*break*/, 21];
401
- if (!(data === "[DONE]")) return [3 /*break*/, 12];
402
- return [4 /*yield*/, __await({
403
- type: "done",
404
- })];
405
- case 9: return [4 /*yield*/, _b.sent()];
406
- case 10:
407
- _b.sent();
408
- return [4 /*yield*/, __await(void 0)];
409
- case 11: return [2 /*return*/, _b.sent()];
410
- case 12:
411
- _b.trys.push([12, 18, , 21]);
412
- raw = JSON.parse(data);
413
- rawChunkResult = exports.RawStreamChunkSchema.safeParse(raw);
414
- if (!!rawChunkResult.success) return [3 /*break*/, 15];
415
- return [4 /*yield*/, __await({
416
- type: "error",
417
- error: "Invalid stream chunk: ".concat(rawChunkResult.error.message),
418
- })];
419
- case 13: return [4 /*yield*/, _b.sent()];
420
- case 14:
421
- _b.sent();
422
- return [3 /*break*/, 21];
423
- case 15:
424
- rawChunk = rawChunkResult.data;
425
- delta = rawChunk.choices[0].delta;
426
- usage = rawChunk.usage
427
- ? {
428
- promptTokens: rawChunk.usage.prompt_tokens,
429
- completionTokens: rawChunk.usage.completion_tokens,
430
- totalTokens: rawChunk.usage.total_tokens,
431
- }
432
- : undefined;
433
- return [4 /*yield*/, __await({
434
- type: "text",
435
- id: rawChunk.id,
436
- content: delta.content || "",
437
- finishReason: rawChunk.choices[0].finish_reason || undefined,
438
- usage: usage,
439
- })];
440
- case 16: return [4 /*yield*/, _b.sent()];
441
- case 17:
442
- _b.sent();
443
- return [3 /*break*/, 21];
444
- case 18:
445
- error_1 = _b.sent();
446
- return [4 /*yield*/, __await({
447
- type: "error",
448
- error: "Failed to parse stream chunk: ".concat(error_1 instanceof Error ? error_1.message : String(error_1)),
449
- })];
450
- case 19: return [4 /*yield*/, _b.sent()];
451
- case 20:
452
- _b.sent();
453
- return [3 /*break*/, 21];
454
- case 21:
455
- _i++;
456
- return [3 /*break*/, 8];
457
- case 22: return [3 /*break*/, 6];
458
- case 23: return [3 /*break*/, 25];
459
- case 24:
460
- reader.releaseLock();
461
- return [7 /*endfinally*/];
462
- case 25: return [2 /*return*/];
463
- }
464
- });
465
- });
196
+ async function* parseSSEStream(response) {
197
+ if (!response.body) {
198
+ yield {
199
+ type: "error",
200
+ error: "Response body is null"
201
+ };
202
+ return;
203
+ }
204
+ const reader = response.body.getReader();
205
+ const decoder = new TextDecoder;
206
+ let buffer = "";
207
+ try {
208
+ while (true) {
209
+ const { done, value } = await reader.read();
210
+ if (done)
211
+ break;
212
+ buffer += decoder.decode(value, { stream: true });
213
+ const lines = buffer.split(`
214
+ `);
215
+ buffer = lines.pop() || "";
216
+ for (const line of lines) {
217
+ const data = parseSSERow(line);
218
+ if (!data)
219
+ continue;
220
+ if (data === "[DONE]") {
221
+ yield {
222
+ type: "done"
223
+ };
224
+ return;
225
+ }
226
+ try {
227
+ const raw = JSON.parse(data);
228
+ const rawChunkResult = RawStreamChunkSchema.safeParse(raw);
229
+ if (!rawChunkResult.success) {
230
+ yield {
231
+ type: "error",
232
+ error: `Invalid stream chunk: ${rawChunkResult.error.message}`
233
+ };
234
+ continue;
235
+ }
236
+ const rawChunk = rawChunkResult.data;
237
+ const delta = rawChunk.choices[0].delta;
238
+ const usage = rawChunk.usage ? {
239
+ promptTokens: rawChunk.usage.prompt_tokens,
240
+ completionTokens: rawChunk.usage.completion_tokens,
241
+ totalTokens: rawChunk.usage.total_tokens
242
+ } : undefined;
243
+ yield {
244
+ type: "text",
245
+ id: rawChunk.id,
246
+ content: delta.content || "",
247
+ finishReason: rawChunk.choices[0].finish_reason || undefined,
248
+ usage
249
+ };
250
+ } catch (error) {
251
+ yield {
252
+ type: "error",
253
+ error: `Failed to parse stream chunk: ${error instanceof Error ? error.message : String(error)}`
254
+ };
255
+ }
256
+ }
257
+ }
258
+ } finally {
259
+ reader.releaseLock();
260
+ }
466
261
  }
467
- // ============================================================================
468
- // EXPORTS
469
- // ============================================================================
470
- exports.default = {
471
- // Messages
472
- ChatMessageSchema: exports.ChatMessageSchema,
473
- ChatMessageRoleSchema: exports.ChatMessageRoleSchema,
474
- // Usage
475
- TokenUsageSchema: exports.TokenUsageSchema,
476
- RawUsageSchema: exports.RawUsageSchema,
477
- // Requests
478
- BaseAIRequestOptionsSchema: exports.BaseAIRequestOptionsSchema,
479
- ChatCompletionOptionsSchema: exports.ChatCompletionOptionsSchema,
480
- AIRequestSchema: exports.AIRequestSchema,
481
- AIChatModuleRequestSchema: exports.AIChatModuleRequestSchema,
482
- // Responses
483
- LatencyInfoSchema: exports.LatencyInfoSchema,
484
- RawChatCompletionResponseSchema: exports.RawChatCompletionResponseSchema,
485
- ChatCompletionResponseSchema: exports.ChatCompletionResponseSchema,
486
- AIResponseSchema: exports.AIResponseSchema,
487
- AIChatResponseSchema: exports.AIChatResponseSchema,
488
- // Streaming
489
- StreamDeltaSchema: exports.StreamDeltaSchema,
490
- StreamChunkTypeSchema: exports.StreamChunkTypeSchema,
491
- RawStreamChunkSchema: exports.RawStreamChunkSchema,
492
- StreamChunkSchema: exports.StreamChunkSchema,
493
- // Errors
494
- APIErrorResponseSchema: exports.APIErrorResponseSchema,
495
- ErrorTypeSchema: exports.ErrorTypeSchema,
496
- // Helpers
497
- validateChatMessage: validateChatMessage,
498
- validateChatMessages: validateChatMessages,
499
- validateChatCompletionOptions: validateChatCompletionOptions,
500
- validateRawResponse: validateRawResponse,
501
- convertUsage: convertUsage,
502
- categorizeError: categorizeError,
503
- parseSSERow: parseSSERow,
504
- parseSSEStream: parseSSEStream,
262
+ var ai_default = {
263
+ ChatMessageSchema,
264
+ ChatMessageRoleSchema,
265
+ ToolCallSchema,
266
+ TokenUsageSchema,
267
+ RawUsageSchema,
268
+ BaseAIRequestOptionsSchema,
269
+ ChatCompletionOptionsSchema,
270
+ AIRequestSchema,
271
+ AIChatModuleRequestSchema,
272
+ LatencyInfoSchema,
273
+ RawChatCompletionResponseSchema,
274
+ ChatCompletionResponseSchema,
275
+ AIResponseSchema,
276
+ AIChatResponseSchema,
277
+ StreamDeltaSchema,
278
+ StreamChunkTypeSchema,
279
+ RawStreamChunkSchema,
280
+ StreamChunkSchema,
281
+ APIErrorResponseSchema,
282
+ ErrorTypeSchema,
283
+ validateChatMessage,
284
+ validateChatMessages,
285
+ validateChatCompletionOptions,
286
+ validateRawResponse,
287
+ convertUsage,
288
+ categorizeError,
289
+ parseSSERow,
290
+ parseSSEStream
291
+ };
292
+ export {
293
+ validateRawResponse,
294
+ validateChatMessages,
295
+ validateChatMessage,
296
+ validateChatCompletionOptions,
297
+ parseSSEStream,
298
+ parseSSERow,
299
+ ai_default as default,
300
+ convertUsage,
301
+ categorizeError,
302
+ ToolCallSchema,
303
+ TokenUsageSchema,
304
+ StreamDeltaSchema,
305
+ StreamChunkTypeSchema,
306
+ StreamChunkSchema,
307
+ RawUsageSchema,
308
+ RawStreamChunkSchema,
309
+ RawChoiceSchema,
310
+ RawChatCompletionResponseSchema,
311
+ LatencyInfoSchema,
312
+ ErrorTypeSchema,
313
+ ChatMessageSchema,
314
+ ChatMessageRoleSchema,
315
+ ChatCompletionResponseSchema,
316
+ ChatCompletionOptionsSchema,
317
+ BaseAIRequestOptionsSchema,
318
+ APIErrorResponseSchema,
319
+ AIResponseSchema,
320
+ AIRequestSchema,
321
+ AIChatResponseSchema,
322
+ AIChatModuleRequestSchema
505
323
  };