@nonoun/native-chat 0.5.17 → 0.5.21

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.
@@ -8,8 +8,9 @@ var e = class extends Error {
8
8
  super(e.message), this.name = "GatewayRequestError", this.kind = e.kind, this.status = e.status ?? 0, this.body = e.body ?? "", this.requestId = e.requestId, this.contentType = e.contentType;
9
9
  }
10
10
  };
11
- async function t(e) {
12
- return r(e, e.retryPolicy ?? {
11
+ const t = 3e4;
12
+ async function n(e) {
13
+ return i(e, e.retryPolicy ?? {
13
14
  delaysMs: [
14
15
  1e3,
15
16
  2e3,
@@ -18,7 +19,7 @@ async function t(e) {
18
19
  jitterRatio: 0
19
20
  }, 0);
20
21
  }
21
- function n(e, t) {
22
+ function r(e, t) {
22
23
  let n = { ...e };
23
24
  if (!t) return n;
24
25
  if (t instanceof Headers) return t.forEach((e, t) => {
@@ -33,103 +34,104 @@ function n(e, t) {
33
34
  ...t
34
35
  };
35
36
  }
36
- async function r(t, a, o) {
37
- let { url: u, init: d, onEvent: f } = t, p = performance.now();
38
- f?.({
37
+ async function i(t, n, o) {
38
+ let { url: s, init: u, onEvent: d } = t, p = performance.now();
39
+ d?.({
39
40
  type: "request:start",
40
- requestId: d.requestId,
41
- endpoint: u,
42
- method: d.method ?? "GET",
41
+ requestId: u.requestId,
42
+ endpoint: s,
43
+ method: u.method ?? "GET",
43
44
  attempt: o,
44
- maxAttempts: a.delaysMs.length + 1
45
+ maxAttempts: n.delaysMs.length + 1
45
46
  });
46
47
  try {
47
- let m = n(t.defaultHeaders ?? {}, d.headers), h = t.auth;
48
+ let m = r(t.defaultHeaders ?? {}, u.headers), h = t.auth;
48
49
  if (h?.token) {
49
50
  let e = h.headerName ?? "Authorization";
50
51
  m[e] = h.scheme === "raw" ? h.token : `Bearer ${h.token}`;
51
52
  }
52
53
  if (h?.additionalHeaders) for (let [e, t] of Object.entries(h.additionalHeaders)) m[e] = t;
53
- let g = await fetch(u, {
54
- ...d,
54
+ let g = t.timeoutMs ?? 3e4, _ = AbortSignal.timeout(g), v = u.signal ? AbortSignal.any([u.signal, _]) : _, y = await fetch(s, {
55
+ ...u,
55
56
  credentials: "include",
56
- headers: m
57
- }), _ = Math.round(performance.now() - p);
58
- if (!g.ok) {
59
- let n = await g.text(), p = i(g.status), m = g.headers.get("content-type") ?? void 0;
60
- if ((p === "rate-limit" || p === "server") && o < a.delaysMs.length) return f?.({
57
+ headers: m,
58
+ signal: v
59
+ }), b = Math.round(performance.now() - p);
60
+ if (!y.ok) {
61
+ let r = await y.text(), p = a(y.status), m = y.headers.get("content-type") ?? void 0;
62
+ if (!t.noRetry && (p === "rate-limit" || p === "server") && o < n.delaysMs.length) return d?.({
61
63
  type: "request:retry",
62
- requestId: d.requestId,
63
- endpoint: u,
64
- method: d.method ?? "GET",
64
+ requestId: u.requestId,
65
+ endpoint: s,
66
+ method: u.method ?? "GET",
65
67
  attempt: o,
66
- maxAttempts: a.delaysMs.length + 1,
67
- durationMs: _,
68
- status: g.status,
68
+ maxAttempts: n.delaysMs.length + 1,
69
+ durationMs: b,
70
+ status: y.status,
69
71
  errorKind: p
70
- }), await c(s(a.delaysMs[o], a.jitterRatio ?? 0)), r(t, a, o + 1);
71
- throw f?.({
72
+ }), await l(c(n.delaysMs[o], n.jitterRatio ?? 0)), i(t, n, o + 1);
73
+ throw d?.({
72
74
  type: "request:error",
73
- requestId: d.requestId,
74
- endpoint: u,
75
- method: d.method ?? "GET",
75
+ requestId: u.requestId,
76
+ endpoint: s,
77
+ method: u.method ?? "GET",
76
78
  attempt: o,
77
- maxAttempts: a.delaysMs.length + 1,
78
- durationMs: _,
79
- status: g.status,
79
+ maxAttempts: n.delaysMs.length + 1,
80
+ durationMs: b,
81
+ status: y.status,
80
82
  errorKind: p
81
83
  }), new e({
82
- message: l(g.status, n, m),
84
+ message: f(y.status, r, m),
83
85
  kind: p,
84
- requestId: d.requestId,
85
- status: g.status,
86
- body: n,
86
+ requestId: u.requestId,
87
+ status: y.status,
88
+ body: r,
87
89
  contentType: m
88
90
  });
89
91
  }
90
- return f?.({
92
+ return d?.({
91
93
  type: "request:success",
92
- requestId: d.requestId,
93
- endpoint: u,
94
- method: d.method ?? "GET",
94
+ requestId: u.requestId,
95
+ endpoint: s,
96
+ method: u.method ?? "GET",
95
97
  attempt: o,
96
- maxAttempts: a.delaysMs.length + 1,
97
- durationMs: _,
98
- status: g.status
99
- }), g;
100
- } catch (n) {
101
- if (n instanceof DOMException && n.name === "AbortError" || n instanceof e) throw n;
102
- let i = Math.round(performance.now() - p);
103
- if (o < a.delaysMs.length) return f?.({
98
+ maxAttempts: n.delaysMs.length + 1,
99
+ durationMs: b,
100
+ status: y.status
101
+ }), y;
102
+ } catch (r) {
103
+ if (r instanceof DOMException && r.name === "AbortError" || r instanceof e) throw r;
104
+ let a = Math.round(performance.now() - p);
105
+ if (!t.noRetry && o < n.delaysMs.length) return d?.({
104
106
  type: "request:retry",
105
- requestId: d.requestId,
106
- endpoint: u,
107
- method: d.method ?? "GET",
107
+ requestId: u.requestId,
108
+ endpoint: s,
109
+ method: u.method ?? "GET",
108
110
  attempt: o,
109
- maxAttempts: a.delaysMs.length + 1,
110
- durationMs: i,
111
+ maxAttempts: n.delaysMs.length + 1,
112
+ durationMs: a,
111
113
  errorKind: "network"
112
- }), await c(s(a.delaysMs[o], a.jitterRatio ?? 0)), r(t, a, o + 1);
113
- throw f?.({
114
+ }), await l(c(n.delaysMs[o], n.jitterRatio ?? 0)), i(t, n, o + 1);
115
+ throw d?.({
114
116
  type: "request:error",
115
- requestId: d.requestId,
116
- endpoint: u,
117
- method: d.method ?? "GET",
117
+ requestId: u.requestId,
118
+ endpoint: s,
119
+ method: u.method ?? "GET",
118
120
  attempt: o,
119
- maxAttempts: a.delaysMs.length + 1,
120
- durationMs: i,
121
+ maxAttempts: n.delaysMs.length + 1,
122
+ durationMs: a,
121
123
  errorKind: "network"
122
124
  }), new e({
123
- message: n instanceof Error ? n.message : "Network error",
125
+ message: r instanceof Error ? r.message : "Network error",
124
126
  kind: "network",
125
- requestId: d.requestId
127
+ requestId: u.requestId
126
128
  });
127
129
  }
128
130
  }
129
- function i(e) {
131
+ function a(e) {
130
132
  return e === 401 || e === 403 ? "auth" : e === 429 ? "rate-limit" : e >= 500 ? "server" : e >= 400 ? "client" : "unknown";
131
133
  }
132
- async function a(t, n) {
134
+ async function o(t, n) {
133
135
  let r = t.headers.get("content-type") ?? "", i = await t.text();
134
136
  if (!i.trim()) throw new e({
135
137
  message: "Empty response body",
@@ -151,18 +153,31 @@ async function a(t, n) {
151
153
  });
152
154
  }
153
155
  }
154
- function o() {
156
+ function s() {
155
157
  return crypto.randomUUID();
156
158
  }
157
- function s(e, t) {
159
+ function c(e, t) {
158
160
  if (t <= 0) return e;
159
161
  let n = 1 + Math.random() * t;
160
162
  return Math.round(e * n);
161
163
  }
162
- function c(e) {
164
+ function l(e) {
163
165
  return new Promise((t) => setTimeout(t, e));
164
166
  }
165
- function l(e, t, n) {
167
+ function u(e) {
168
+ let t = e.split("\n"), n = "message", r = [];
169
+ for (let e of t) e.startsWith(":") || (e.startsWith("event:") ? n = e.slice(6).trim() : e.startsWith("data:") && r.push(e.slice(5).replace(/^ /, "")));
170
+ return r.length ? {
171
+ event: n,
172
+ data: r.join("\n")
173
+ } : null;
174
+ }
175
+ const d = [
176
+ 1e3,
177
+ 2e3,
178
+ 4e3
179
+ ];
180
+ function f(e, t, n) {
166
181
  let r = `Request failed with ${e}`;
167
182
  if (!t.trim()) return r;
168
183
  if ((n ?? "").toLowerCase().includes("application/json") || t.trim().startsWith("{")) try {
@@ -173,11 +188,7 @@ function l(e, t, n) {
173
188
  }
174
189
  return (n ?? "").toLowerCase().includes("text/html") ? `${r} (received HTML instead of API JSON)` : r;
175
190
  }
176
- var u = [
177
- 1e3,
178
- 2e3,
179
- 4e3
180
- ], d = class {
191
+ var p = class {
181
192
  clientId;
182
193
  baseUrl;
183
194
  model;
@@ -193,15 +204,15 @@ var u = [
193
204
  }
194
205
  async bootstrapSession() {
195
206
  return {
196
- id: this.defaultSessionId ?? o(),
207
+ id: this.defaultSessionId ?? s(),
197
208
  messages: []
198
209
  };
199
210
  }
200
211
  async sendMessage(e) {
201
- let t = e.requestId ?? o();
212
+ let t = e.requestId ?? s();
202
213
  return {
203
214
  role: "assistant",
204
- message: (await a(await this.request({
215
+ message: (await o(await this.request({
205
216
  url: `${this.baseUrl}/chat/completions`,
206
217
  init: {
207
218
  method: "POST",
@@ -216,7 +227,7 @@ var u = [
216
227
  };
217
228
  }
218
229
  async sendMessageStream(e) {
219
- let t = e.requestId ?? o(), n = await this.request({
230
+ let t = e.requestId ?? s(), n = await this.request({
220
231
  url: `${this.baseUrl}/chat/completions`,
221
232
  init: {
222
233
  method: "POST",
@@ -227,36 +238,63 @@ var u = [
227
238
  Accept: "text/event-stream, application/json, text/plain, */*"
228
239
  },
229
240
  body: JSON.stringify(this.buildRequestPayload(e.messages, e.query, !0, e.model))
230
- }
241
+ },
242
+ noRetry: !0
231
243
  }), r = (n.headers.get("content-type") ?? "").toLowerCase();
232
- return n.body && r.includes("text/event-stream") ? (e.onMode?.("sse", r), e.onStreamEvent?.({
244
+ if (n.body && r.includes("text/event-stream")) return e.onMode?.("sse", r), e.onStreamEvent?.({
233
245
  phase: "start",
234
246
  mode: "sse",
235
247
  contentType: r
236
- }), this.parseEventStream(n, t, e.onChunk, e.onStreamEvent, r)) : (e.onMode?.("json", r), e.onStreamEvent?.({
248
+ }), this.parseEventStream(n, t, e.onChunk, e.onStreamEvent, r);
249
+ e.onMode?.("json", r), e.onStreamEvent?.({
237
250
  phase: "start",
238
251
  mode: "json",
239
252
  contentType: r
240
- }), this.sendMessage({
241
- ...e,
242
- requestId: t
243
- }));
244
- }
245
- async checkHealth(e) {
246
- let t = e?.requestId ?? o(), n = performance.now(), r = await this.request({
247
- url: `${this.baseUrl}/models`,
248
- init: {
249
- method: "GET",
250
- signal: e?.signal,
251
- requestId: t
252
- }
253
253
  });
254
- return {
255
- healthy: r.ok,
256
- requestId: t,
257
- status: r.status,
258
- durationMs: Math.round(performance.now() - n)
254
+ let i = (await o(n, t)).choices?.[0]?.message?.content?.trim() || "No response returned.", a = {
255
+ role: "assistant",
256
+ message: i,
257
+ datetime: Date.now(),
258
+ partial: !1
259
259
  };
260
+ return e.onChunk?.({
261
+ delta: i,
262
+ fullMessage: i,
263
+ role: "assistant",
264
+ datetime: a.datetime ?? Date.now(),
265
+ done: !0
266
+ }), e.onStreamEvent?.({
267
+ phase: "complete",
268
+ mode: "json",
269
+ contentType: r,
270
+ fullMessage: i
271
+ }), a;
272
+ }
273
+ async checkHealth(t) {
274
+ let n = t?.requestId ?? s(), r = performance.now();
275
+ try {
276
+ let e = await this.request({
277
+ url: `${this.baseUrl}/models`,
278
+ init: {
279
+ method: "GET",
280
+ signal: t?.signal,
281
+ requestId: n
282
+ }
283
+ });
284
+ return {
285
+ healthy: e.ok,
286
+ requestId: n,
287
+ status: e.status,
288
+ durationMs: Math.round(performance.now() - r)
289
+ };
290
+ } catch (t) {
291
+ return {
292
+ healthy: !1,
293
+ requestId: n,
294
+ status: t instanceof e ? t.status : 0,
295
+ durationMs: Math.round(performance.now() - r)
296
+ };
297
+ }
260
298
  }
261
299
  async getClientMetadata() {
262
300
  return {
@@ -266,14 +304,14 @@ var u = [
266
304
  };
267
305
  }
268
306
  async listModels(e) {
269
- let t = e?.requestId ?? o(), n = ((await a(await this.request({
307
+ let t = e?.requestId ?? s(), n = ((await o(await this.request({
270
308
  url: `${this.baseUrl}/models`,
271
309
  init: {
272
310
  method: "GET",
273
311
  signal: e?.signal,
274
312
  requestId: t
275
313
  }
276
- }), t)).data ?? []).filter((e) => typeof e.id == "string" && e.id.length > 0).map((e) => e.id), r = n.filter((e) => m(e));
314
+ }), t)).data ?? []).filter((e) => typeof e.id == "string" && e.id.length > 0).map((e) => e.id), r = n.filter((e) => g(e));
277
315
  return (r.length ? r : n).map((e) => ({
278
316
  id: e,
279
317
  label: e,
@@ -296,10 +334,7 @@ var u = [
296
334
  }), n.push(...e.filter((e) => e.role === "user" || e.role === "assistant").filter((e) => e.message.trim().length > 0).map((e) => ({
297
335
  role: e.role,
298
336
  content: e.message
299
- }))), (!n.length || n[n.length - 1]?.role !== "user") && n.push({
300
- role: "user",
301
- content: t
302
- }), n;
337
+ }))), n;
303
338
  }
304
339
  async parseEventStream(t, n, r, i, a) {
305
340
  if (!t.body) throw new e({
@@ -308,60 +343,65 @@ var u = [
308
343
  requestId: n,
309
344
  status: t.status
310
345
  });
311
- let o = t.body.getReader(), s = new TextDecoder(), c = "", l = "", u = Date.now(), d = !1;
312
- for (;;) {
313
- let { value: f, done: p } = await o.read();
314
- if (p) break;
315
- c += s.decode(f, { stream: !0 }).replace(/\r\n/g, "\n");
316
- let m = c.indexOf("\n\n");
317
- for (; m !== -1;) {
318
- let o = c.slice(0, m);
319
- c = c.slice(m + 2), m = c.indexOf("\n\n");
320
- let s = this.parseSseEvent(o);
321
- if (!s) continue;
322
- if (s.data === "[DONE]") {
323
- d = !0;
324
- continue;
325
- }
326
- let f = {};
327
- try {
328
- f = JSON.parse(s.data);
329
- } catch {
330
- continue;
331
- }
332
- let p = f.error;
333
- if (p) {
334
- let r = typeof p.message == "string" && p.message || typeof f.message == "string" && f.message || "OpenAI stream error";
335
- throw i?.({
336
- phase: "error",
346
+ let o = t.body.getReader(), s = new TextDecoder(), c = "", l = "", d = Date.now(), f = !1;
347
+ try {
348
+ for (;;) {
349
+ let { value: p, done: m } = await o.read();
350
+ if (m) break;
351
+ c += s.decode(p, { stream: !0 }).replace(/\r\n/g, "\n");
352
+ let h = c.indexOf("\n\n");
353
+ for (; h !== -1;) {
354
+ let o = c.slice(0, h);
355
+ c = c.slice(h + 2), h = c.indexOf("\n\n");
356
+ let s = u(o);
357
+ if (!s) continue;
358
+ if (s.data === "[DONE]") {
359
+ f = !0;
360
+ continue;
361
+ }
362
+ let p = {};
363
+ try {
364
+ p = JSON.parse(s.data);
365
+ } catch {
366
+ continue;
367
+ }
368
+ let m = p.error;
369
+ if (m) {
370
+ let r = typeof m.message == "string" && m.message || typeof p.message == "string" && p.message || "OpenAI stream error";
371
+ throw i?.({
372
+ phase: "error",
373
+ mode: "sse",
374
+ contentType: a,
375
+ message: r
376
+ }), new e({
377
+ message: r,
378
+ kind: "server",
379
+ requestId: n,
380
+ status: t.status,
381
+ body: s.data
382
+ });
383
+ }
384
+ let g = (Array.isArray(p.choices) ? p.choices : [])[0], _ = g?.delta, v = typeof _?.content == "string" ? _.content : "", y = typeof p.delta == "string" ? p.delta : "", b = v || y;
385
+ b && (l += b, r?.({
386
+ delta: b,
387
+ fullMessage: l,
388
+ role: "assistant",
389
+ datetime: d,
390
+ done: !1
391
+ }), i?.({
392
+ phase: "delta",
337
393
  mode: "sse",
338
394
  contentType: a,
339
- message: r
340
- }), new e({
341
- message: r,
342
- kind: "server",
343
- requestId: n,
344
- status: t.status,
345
- body: s.data
346
- });
395
+ delta: b,
396
+ fullMessage: l
397
+ }));
398
+ let x = typeof g?.finish_reason == "string" ? g.finish_reason : null;
399
+ x && x !== "null" && (f = !0);
347
400
  }
348
- let h = (Array.isArray(f.choices) ? f.choices : [])[0], g = h?.delta, _ = typeof g?.content == "string" ? g.content : "", v = typeof f.delta == "string" ? f.delta : "", y = _ || v;
349
- y && (l += y, r?.({
350
- delta: y,
351
- fullMessage: l,
352
- role: "assistant",
353
- datetime: u,
354
- done: !1
355
- }), i?.({
356
- phase: "delta",
357
- mode: "sse",
358
- contentType: a,
359
- delta: y,
360
- fullMessage: l
361
- }));
362
- let b = typeof h?.finish_reason == "string" ? h.finish_reason : null;
363
- b && b !== "null" && (d = !0);
364
401
  }
402
+ c += s.decode();
403
+ } finally {
404
+ o.releaseLock();
365
405
  }
366
406
  if (!l.trim()) throw new e({
367
407
  message: "Empty stream response body",
@@ -373,9 +413,9 @@ var u = [
373
413
  delta: "",
374
414
  fullMessage: l,
375
415
  role: "assistant",
376
- datetime: u,
416
+ datetime: d,
377
417
  done: !0,
378
- partial: !d
418
+ partial: !f
379
419
  }), i?.({
380
420
  phase: "complete",
381
421
  mode: "sse",
@@ -384,23 +424,16 @@ var u = [
384
424
  }), {
385
425
  role: "assistant",
386
426
  message: l,
387
- datetime: u,
388
- partial: !d
427
+ datetime: d,
428
+ partial: !f
389
429
  };
390
430
  }
391
- parseSseEvent(e) {
392
- let t = e.split("\n"), n = "message", r = [];
393
- for (let e of t) e.startsWith("event:") && (n = e.slice(6).trim()), e.startsWith("data:") && r.push(e.slice(5).trimStart());
394
- return r.length ? {
395
- event: n,
396
- data: r.join("\n")
397
- } : null;
398
- }
399
431
  request(e) {
400
- return t({
432
+ return n({
401
433
  url: e.url,
402
434
  init: e.init,
403
- retryPolicy: { delaysMs: u },
435
+ noRetry: e.noRetry,
436
+ retryPolicy: { delaysMs: d },
404
437
  auth: {
405
438
  token: this.apiKey,
406
439
  headerName: "Authorization",
@@ -415,9 +448,9 @@ var u = [
415
448
  });
416
449
  }
417
450
  };
418
- const f = ({ clientId: e, baseUrl: t, gatewayConfig: n, onEvent: r, auth: i }) => {
451
+ const m = ({ clientId: e, baseUrl: t, gatewayConfig: n, onEvent: r, auth: i }) => {
419
452
  let a = n?.model ?? "gpt-4.1-mini", o = Number(n?.max_tokens ?? n?.maxTokens ?? 1024), s = n?.temperature, c = n?.api_key ?? n?.apiKey ?? i?.token ?? null, l = n?.organization ?? n?.openai_organization ?? n?.openaiOrganization ?? null, u = n?.session_id ?? n?.sessionId ?? null;
420
- return new d({
453
+ return new p({
421
454
  clientId: e,
422
455
  baseUrl: t,
423
456
  model: String(a),
@@ -430,7 +463,7 @@ const f = ({ clientId: e, baseUrl: t, gatewayConfig: n, onEvent: r, auth: i }) =
430
463
  onEvent: r
431
464
  });
432
465
  };
433
- function p(e) {
466
+ function h(e) {
434
467
  let t = e.model;
435
468
  if (t !== void 0 && (typeof t != "string" || !t.trim())) throw Error("Invalid `gateway-config`: openai model must be a non-empty string.");
436
469
  let n = e.max_tokens ?? e.maxTokens;
@@ -445,15 +478,11 @@ function p(e) {
445
478
  }
446
479
  return e;
447
480
  }
448
- function m(e) {
481
+ function g(e) {
449
482
  let t = e.trim().toLowerCase();
450
483
  return t ? t.startsWith("gpt-") || t.startsWith("chatgpt-") : !1;
451
484
  }
452
- var h = [
453
- 1e3,
454
- 2e3,
455
- 4e3
456
- ], g = class {
485
+ var _ = class {
457
486
  clientId;
458
487
  baseUrl;
459
488
  model;
@@ -465,16 +494,16 @@ var h = [
465
494
  defaultSessionId;
466
495
  onEvent;
467
496
  constructor(e) {
468
- this.clientId = e.clientId, this.baseUrl = e.baseUrl.replace(/\/+$/, ""), this.model = e.model, this.maxTokens = e.maxTokens, this.system = e.system, this.temperature = e.temperature, this.apiKey = e.apiKey, this.anthropicVersion = e.anthropicVersion, this.defaultSessionId = e.defaultSessionId, this.onEvent = e.onEvent;
497
+ this.clientId = e.clientId, this.baseUrl = e.baseUrl.replace(/\/+$/, ""), this.model = e.model, this.maxTokens = e.maxTokens, this.system = e.system, this.temperature = e.temperature, this.apiKey = e.apiKey, this.anthropicVersion = e.anthropicVersion, this.defaultSessionId = e.defaultSessionId, this.onEvent = e.onEvent, e.apiKey && typeof window < "u" && console.warn("[native-chat] ClaudeGatewayAdapter: API key is exposed in the browser. This is for development only. In production, proxy requests through a backend gateway.");
469
498
  }
470
499
  async bootstrapSession() {
471
500
  return {
472
- id: this.defaultSessionId ?? o(),
501
+ id: this.defaultSessionId ?? s(),
473
502
  messages: []
474
503
  };
475
504
  }
476
505
  async sendMessage(e) {
477
- let t = e.requestId ?? o(), n = await a(await this.request({
506
+ let t = e.requestId ?? s(), n = await o(await this.request({
478
507
  url: `${this.baseUrl}/messages`,
479
508
  init: {
480
509
  method: "POST",
@@ -491,7 +520,7 @@ var h = [
491
520
  };
492
521
  }
493
522
  async sendMessageStream(e) {
494
- let t = e.requestId ?? o(), n = await this.request({
523
+ let t = e.requestId ?? s(), n = await this.request({
495
524
  url: `${this.baseUrl}/messages`,
496
525
  init: {
497
526
  method: "POST",
@@ -499,36 +528,63 @@ var h = [
499
528
  requestId: t,
500
529
  headers: { Accept: "text/event-stream, application/json, text/plain, */*" },
501
530
  body: JSON.stringify(this.buildRequestPayload(e.messages, e.query, !0, e.model))
502
- }
531
+ },
532
+ noRetry: !0
503
533
  }), r = (n.headers.get("content-type") ?? "").toLowerCase();
504
- return n.body && r.includes("text/event-stream") ? (e.onMode?.("sse", r), e.onStreamEvent?.({
534
+ if (n.body && r.includes("text/event-stream")) return e.onMode?.("sse", r), e.onStreamEvent?.({
505
535
  phase: "start",
506
536
  mode: "sse",
507
537
  contentType: r
508
- }), this.parseEventStream(n, t, e.onChunk, e.onStreamEvent, r)) : (e.onMode?.("json", r), e.onStreamEvent?.({
538
+ }), this.parseEventStream(n, t, e.onChunk, e.onStreamEvent, r);
539
+ e.onMode?.("json", r), e.onStreamEvent?.({
509
540
  phase: "start",
510
541
  mode: "json",
511
542
  contentType: r
512
- }), this.sendMessage({
513
- ...e,
514
- requestId: t
515
- }));
516
- }
517
- async checkHealth(e) {
518
- let t = e?.requestId ?? o(), n = performance.now(), r = await this.request({
519
- url: `${this.baseUrl}/models`,
520
- init: {
521
- method: "GET",
522
- signal: e?.signal,
523
- requestId: t
524
- }
525
543
  });
526
- return {
527
- healthy: r.ok,
528
- requestId: t,
529
- status: r.status,
530
- durationMs: Math.round(performance.now() - n)
544
+ let i = await o(n, t), a = {
545
+ role: "assistant",
546
+ message: this.extractTextFromMessage(i),
547
+ datetime: Date.now(),
548
+ partial: !1
531
549
  };
550
+ return e.onChunk?.({
551
+ delta: a.message,
552
+ fullMessage: a.message,
553
+ role: "assistant",
554
+ datetime: a.datetime ?? Date.now(),
555
+ done: !0
556
+ }), e.onStreamEvent?.({
557
+ phase: "complete",
558
+ mode: "json",
559
+ contentType: r,
560
+ fullMessage: a.message
561
+ }), a;
562
+ }
563
+ async checkHealth(t) {
564
+ let n = t?.requestId ?? s(), r = performance.now();
565
+ try {
566
+ let e = await this.request({
567
+ url: `${this.baseUrl}/models`,
568
+ init: {
569
+ method: "GET",
570
+ signal: t?.signal,
571
+ requestId: n
572
+ }
573
+ });
574
+ return {
575
+ healthy: e.ok,
576
+ requestId: n,
577
+ status: e.status,
578
+ durationMs: Math.round(performance.now() - r)
579
+ };
580
+ } catch (t) {
581
+ return {
582
+ healthy: !1,
583
+ requestId: n,
584
+ status: t instanceof e ? t.status : 0,
585
+ durationMs: Math.round(performance.now() - r)
586
+ };
587
+ }
532
588
  }
533
589
  async getClientMetadata() {
534
590
  return {
@@ -538,8 +594,8 @@ var h = [
538
594
  };
539
595
  }
540
596
  async listModels(e) {
541
- let t = e?.requestId ?? o();
542
- return ((await a(await this.request({
597
+ let t = e?.requestId ?? s();
598
+ return ((await o(await this.request({
543
599
  url: `${this.baseUrl}/models`,
544
600
  init: {
545
601
  method: "GET",
@@ -562,14 +618,10 @@ var h = [
562
618
  return this.system && (a.system = this.system), typeof this.temperature == "number" && (a.temperature = this.temperature), a;
563
619
  }
564
620
  mapMessages(e, t) {
565
- let n = e.filter((e) => e.role === "user" || e.role === "assistant").filter((e) => e.message.trim().length > 0).map((e) => ({
621
+ return e.filter((e) => e.role === "user" || e.role === "assistant").filter((e) => e.message.trim().length > 0).map((e) => ({
566
622
  role: e.role,
567
623
  content: e.message
568
624
  }));
569
- return (!n.length || n[n.length - 1]?.role !== "user") && n.push({
570
- role: "user",
571
- content: t
572
- }), n;
573
625
  }
574
626
  extractTextFromMessage(e) {
575
627
  return (e.content ?? []).filter((e) => e.type === "text").map((e) => e.text ?? "").join("") || "No response returned.";
@@ -581,62 +633,67 @@ var h = [
581
633
  requestId: n,
582
634
  status: t.status
583
635
  });
584
- let o = t.body.getReader(), s = new TextDecoder(), c = "", l = "", u = Date.now(), d = !1;
585
- for (;;) {
586
- let { value: f, done: p } = await o.read();
587
- if (p) break;
588
- c += s.decode(f, { stream: !0 }).replace(/\r\n/g, "\n");
589
- let m = c.indexOf("\n\n");
590
- for (; m !== -1;) {
591
- let o = c.slice(0, m);
592
- c = c.slice(m + 2), m = c.indexOf("\n\n");
593
- let s = this.parseSseEvent(o);
594
- if (!s) continue;
595
- if (s.data === "[DONE]") {
596
- d = !0;
597
- continue;
598
- }
599
- let f = {};
600
- try {
601
- f = JSON.parse(s.data);
602
- } catch {
603
- continue;
604
- }
605
- if (s.event === "error" || f.type === "error") {
606
- let r = f.error, o = typeof r?.message == "string" && r.message || typeof f.message == "string" && f.message || "Claude stream error";
607
- throw i?.({
608
- phase: "error",
636
+ let o = t.body.getReader(), s = new TextDecoder(), c = "", l = "", d = Date.now(), f = !1;
637
+ try {
638
+ for (;;) {
639
+ let { value: p, done: m } = await o.read();
640
+ if (m) break;
641
+ c += s.decode(p, { stream: !0 }).replace(/\r\n/g, "\n");
642
+ let h = c.indexOf("\n\n");
643
+ for (; h !== -1;) {
644
+ let o = c.slice(0, h);
645
+ c = c.slice(h + 2), h = c.indexOf("\n\n");
646
+ let s = u(o);
647
+ if (!s) continue;
648
+ if (s.data === "[DONE]") {
649
+ f = !0;
650
+ continue;
651
+ }
652
+ let p = {};
653
+ try {
654
+ p = JSON.parse(s.data);
655
+ } catch {
656
+ continue;
657
+ }
658
+ if (s.event === "error" || p.type === "error") {
659
+ let r = p.error, o = typeof r?.message == "string" && r.message || typeof p.message == "string" && p.message || "Claude stream error";
660
+ throw i?.({
661
+ phase: "error",
662
+ mode: "sse",
663
+ contentType: a,
664
+ message: o
665
+ }), new e({
666
+ message: o,
667
+ kind: "server",
668
+ requestId: n,
669
+ status: t.status,
670
+ body: s.data
671
+ });
672
+ }
673
+ if (s.event === "message_stop" || p.type === "message_stop") {
674
+ f = !0;
675
+ continue;
676
+ }
677
+ if (!(s.event === "content_block_delta" || p.type === "content_block_delta")) continue;
678
+ let m = p.delta;
679
+ !m || m.type !== "text_delta" || typeof m.text != "string" || (l += m.text, r?.({
680
+ delta: m.text,
681
+ fullMessage: l,
682
+ role: "assistant",
683
+ datetime: d,
684
+ done: !1
685
+ }), i?.({
686
+ phase: "delta",
609
687
  mode: "sse",
610
688
  contentType: a,
611
- message: o
612
- }), new e({
613
- message: o,
614
- kind: "server",
615
- requestId: n,
616
- status: t.status,
617
- body: s.data
618
- });
619
- }
620
- if (s.event === "message_stop" || f.type === "message_stop") {
621
- d = !0;
622
- continue;
689
+ delta: m.text,
690
+ fullMessage: l
691
+ }));
623
692
  }
624
- if (!(s.event === "content_block_delta" || f.type === "content_block_delta")) continue;
625
- let p = f.delta;
626
- !p || p.type !== "text_delta" || typeof p.text != "string" || (l += p.text, r?.({
627
- delta: p.text,
628
- fullMessage: l,
629
- role: "assistant",
630
- datetime: u,
631
- done: !1
632
- }), i?.({
633
- phase: "delta",
634
- mode: "sse",
635
- contentType: a,
636
- delta: p.text,
637
- fullMessage: l
638
- }));
639
693
  }
694
+ c += s.decode();
695
+ } finally {
696
+ o.releaseLock();
640
697
  }
641
698
  if (!l.trim()) throw new e({
642
699
  message: "Empty stream response body",
@@ -648,9 +705,9 @@ var h = [
648
705
  delta: "",
649
706
  fullMessage: l,
650
707
  role: "assistant",
651
- datetime: u,
708
+ datetime: d,
652
709
  done: !0,
653
- partial: !d
710
+ partial: !f
654
711
  }), i?.({
655
712
  phase: "complete",
656
713
  mode: "sse",
@@ -659,23 +716,16 @@ var h = [
659
716
  }), {
660
717
  role: "assistant",
661
718
  message: l,
662
- datetime: u,
663
- partial: !d
719
+ datetime: d,
720
+ partial: !f
664
721
  };
665
722
  }
666
- parseSseEvent(e) {
667
- let t = e.split("\n"), n = "message", r = [];
668
- for (let e of t) e.startsWith("event:") && (n = e.slice(6).trim()), e.startsWith("data:") && r.push(e.slice(5).trimStart());
669
- return r.length ? {
670
- event: n,
671
- data: r.join("\n")
672
- } : null;
673
- }
674
723
  request(e) {
675
- return t({
724
+ return n({
676
725
  url: e.url,
677
726
  init: e.init,
678
- retryPolicy: { delaysMs: h },
727
+ noRetry: e.noRetry,
728
+ retryPolicy: { delaysMs: d },
679
729
  auth: {
680
730
  token: this.apiKey,
681
731
  headerName: "x-api-key",
@@ -691,9 +741,9 @@ var h = [
691
741
  });
692
742
  }
693
743
  };
694
- const _ = ({ clientId: e, baseUrl: t, gatewayConfig: n, onEvent: r, auth: i }) => {
744
+ const v = ({ clientId: e, baseUrl: t, gatewayConfig: n, onEvent: r, auth: i }) => {
695
745
  let a = n?.model ?? "claude-sonnet-4-6", o = Number(n?.max_tokens ?? n?.maxTokens ?? 1024), s = n?.temperature, c = n?.anthropic_version ?? n?.anthropicVersion ?? "2023-06-01", l = n?.api_key ?? n?.apiKey ?? i?.token ?? null, u = n?.session_id ?? n?.sessionId ?? null;
696
- return new g({
746
+ return new _({
697
747
  clientId: e,
698
748
  baseUrl: t,
699
749
  model: String(a),
@@ -706,7 +756,7 @@ const _ = ({ clientId: e, baseUrl: t, gatewayConfig: n, onEvent: r, auth: i }) =
706
756
  onEvent: r
707
757
  });
708
758
  };
709
- function v(e) {
759
+ function y(e) {
710
760
  let t = e.model;
711
761
  if (t !== void 0 && (typeof t != "string" || !t.trim())) throw Error("Invalid `gateway-config`: claude model must be a non-empty string.");
712
762
  let n = e.max_tokens ?? e.maxTokens;
@@ -721,17 +771,17 @@ function v(e) {
721
771
  }
722
772
  return e;
723
773
  }
724
- var y = [
774
+ var b = [
725
775
  "That's a great question! Here's what I think:\n\n**Web components** are built on three main browser APIs:\n\n1. **Custom Elements** — define your own HTML tags\n2. **Shadow DOM** — encapsulated styling and markup\n3. **HTML Templates** — reusable content fragments\n\nThey work natively in all modern browsers.",
726
776
  "Sure, I can help with that! Let me break it down:\n\n- First, you'll want to understand the **component lifecycle**\n- Then look at how **attributes** map to **properties**\n- Finally, consider your **event strategy**\n\n```js\nclass MyElement extends HTMLElement {\n connectedCallback() {\n console.log('Connected!');\n }\n}\n```",
727
777
  "Here are some key points to consider:\n\n> The best code is the code you don't have to write.\n\n1. Keep components **small and focused**\n2. Use **composition** over inheritance\n3. Leverage **CSS custom properties** for theming\n4. Always consider **accessibility**\n\nLet me know if you'd like more detail on any of these!"
728
- ], b = 25, x = class {
778
+ ], x = 25, S = class {
729
779
  #e = 0;
730
780
  bootstrapSession() {
731
781
  return Promise.resolve({ id: "mock-session" });
732
782
  }
733
783
  sendMessage(e) {
734
- let t = y[this.#e++ % y.length];
784
+ let t = b[this.#e++ % b.length];
735
785
  return Promise.resolve({
736
786
  role: "assistant",
737
787
  message: t,
@@ -739,7 +789,7 @@ var y = [
739
789
  });
740
790
  }
741
791
  async sendMessageStream(e) {
742
- let t = y[this.#e++ % y.length], n = t.split(/(\s+)/);
792
+ let t = b[this.#e++ % b.length], n = t.split(/(\s+)/);
743
793
  e.onMode?.("sse", "text/event-stream"), e.onStreamEvent?.({
744
794
  phase: "start",
745
795
  mode: "sse"
@@ -755,7 +805,7 @@ var y = [
755
805
  role: "assistant",
756
806
  datetime: Date.now(),
757
807
  done: i
758
- }), i || await new Promise((e) => setTimeout(e, b));
808
+ }), i || await new Promise((e) => setTimeout(e, x));
759
809
  }
760
810
  return e.onStreamEvent?.({
761
811
  phase: "complete",
@@ -789,7 +839,7 @@ var y = [
789
839
  }]);
790
840
  }
791
841
  };
792
- function S(e) {
793
- return new x();
842
+ function C(e) {
843
+ return new S();
794
844
  }
795
- export { d as a, e as c, t as d, a as f, v as i, i as l, g as n, f as o, _ as r, p as s, S as t, o as u };
845
+ export { p as a, t as c, a as d, s as f, u as h, y as i, d as l, o as m, _ as n, m as o, n as p, v as r, h as s, C as t, e as u };