agent-stream-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +220 -2
  3. package/dist/adapters/openai.d.ts +42 -0
  4. package/dist/adapters/openai.d.ts.map +1 -0
  5. package/dist/agent-stream-ui.css +2 -0
  6. package/dist/agent-stream-ui.js +1418 -0
  7. package/dist/agent-stream-ui.js.map +1 -0
  8. package/dist/core/reducer.d.ts +33 -0
  9. package/dist/core/reducer.d.ts.map +1 -0
  10. package/dist/core/scheduler.d.ts +15 -0
  11. package/dist/core/scheduler.d.ts.map +1 -0
  12. package/dist/core/store.d.ts +29 -0
  13. package/dist/core/store.d.ts.map +1 -0
  14. package/dist/core/transport.d.ts +57 -0
  15. package/dist/core/transport.d.ts.map +1 -0
  16. package/dist/index.d.ts +38 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/markdown/blocks.d.ts +31 -0
  19. package/dist/markdown/blocks.d.ts.map +1 -0
  20. package/dist/markdown/inline.d.ts +13 -0
  21. package/dist/markdown/inline.d.ts.map +1 -0
  22. package/dist/markdown/render.d.ts +18 -0
  23. package/dist/markdown/render.d.ts.map +1 -0
  24. package/dist/react/agent-chat.d.ts +14 -0
  25. package/dist/react/agent-chat.d.ts.map +1 -0
  26. package/dist/react/composer.d.ts +11 -0
  27. package/dist/react/composer.d.ts.map +1 -0
  28. package/dist/react/icons.d.ts +12 -0
  29. package/dist/react/icons.d.ts.map +1 -0
  30. package/dist/react/markdown-stream.d.ts +14 -0
  31. package/dist/react/markdown-stream.d.ts.map +1 -0
  32. package/dist/react/message-body.d.ts +14 -0
  33. package/dist/react/message-body.d.ts.map +1 -0
  34. package/dist/react/message-list.d.ts +8 -0
  35. package/dist/react/message-list.d.ts.map +1 -0
  36. package/dist/react/tool-call-card.d.ts +13 -0
  37. package/dist/react/tool-call-card.d.ts.map +1 -0
  38. package/dist/react/use-agent-stream.d.ts +11 -0
  39. package/dist/react/use-agent-stream.d.ts.map +1 -0
  40. package/dist/react/use-stick-to-bottom.d.ts +14 -0
  41. package/dist/react/use-stick-to-bottom.d.ts.map +1 -0
  42. package/dist/sse/client.d.ts +60 -0
  43. package/dist/sse/client.d.ts.map +1 -0
  44. package/dist/sse/frame.d.ts +42 -0
  45. package/dist/sse/frame.d.ts.map +1 -0
  46. package/dist/types.d.ts +119 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/docs/design-notes.md +145 -0
  49. package/package.json +84 -4
  50. package/src/lib/adapters/openai.ts +112 -0
  51. package/src/lib/core/reducer.ts +417 -0
  52. package/src/lib/core/scheduler.ts +40 -0
  53. package/src/lib/core/store.ts +214 -0
  54. package/src/lib/core/transport.ts +197 -0
  55. package/src/lib/index.ts +102 -0
  56. package/src/lib/markdown/blocks.ts +201 -0
  57. package/src/lib/markdown/inline.tsx +87 -0
  58. package/src/lib/markdown/render.tsx +149 -0
  59. package/src/lib/react/agent-chat.tsx +121 -0
  60. package/src/lib/react/composer.tsx +105 -0
  61. package/src/lib/react/icons.tsx +83 -0
  62. package/src/lib/react/markdown-stream.tsx +37 -0
  63. package/src/lib/react/message-body.tsx +66 -0
  64. package/src/lib/react/message-list.tsx +109 -0
  65. package/src/lib/react/tool-call-card.tsx +117 -0
  66. package/src/lib/react/use-agent-stream.ts +14 -0
  67. package/src/lib/react/use-stick-to-bottom.ts +60 -0
  68. package/src/lib/sse/client.ts +263 -0
  69. package/src/lib/sse/frame.ts +116 -0
  70. package/src/lib/styles.css +790 -0
  71. package/src/lib/types.ts +130 -0
@@ -0,0 +1,1418 @@
1
+ import { Fragment as e, memo as t, useCallback as n, useEffect as r, useLayoutEffect as i, useMemo as a, useRef as o, useState as s, useSyncExternalStore as c } from "react";
2
+ import { Fragment as l, jsx as u, jsxs as d } from "react/jsx-runtime";
3
+ // src/lib/types.ts
4
+ var f = [
5
+ "turn.start",
6
+ "message.delta",
7
+ "message.done",
8
+ "tool.call",
9
+ "tool.args",
10
+ "tool.result",
11
+ "turn.end",
12
+ "error",
13
+ "ping"
14
+ ], p = /\r?\n\r?\n/;
15
+ function m(e) {
16
+ if (e.length === 0) return null;
17
+ let t = e.split(/\r?\n/), n = null, r = "message", i = null, a = [];
18
+ for (let e of t) {
19
+ if (e === "" || e.startsWith(":")) continue;
20
+ let t = e.indexOf(":"), o = t === -1 ? e : e.slice(0, t), s = t === -1 ? "" : e.slice(t + 1);
21
+ switch (s.startsWith(" ") && (s = s.slice(1)), o) {
22
+ case "id":
23
+ n = s;
24
+ break;
25
+ case "event":
26
+ r = s === "" ? "message" : s;
27
+ break;
28
+ case "data":
29
+ a.push(s);
30
+ break;
31
+ case "retry": {
32
+ let e = Number(s);
33
+ Number.isFinite(e) && e > 0 && (i = e);
34
+ break;
35
+ }
36
+ }
37
+ }
38
+ return a.length === 0 ? null : {
39
+ id: n,
40
+ event: r,
41
+ data: a.join("\n"),
42
+ retry: i
43
+ };
44
+ }
45
+ function h(e) {
46
+ let t = [], n = e;
47
+ for (;;) {
48
+ let e = p.exec(n);
49
+ if (!e) break;
50
+ let r = n.slice(0, e.index);
51
+ n = n.slice(e.index + e[0].length);
52
+ let i = m(r);
53
+ i && t.push(i);
54
+ }
55
+ return {
56
+ frames: t,
57
+ rest: n
58
+ };
59
+ }
60
+ function g(e) {
61
+ let t = "";
62
+ e.id !== void 0 && e.id !== null && (t += `id: ${e.id}\n`), e.event && e.event !== "message" && (t += `event: ${e.event}\n`);
63
+ for (let n of e.data.split("\n")) t += `data: ${n}\n`;
64
+ return `${t}\n`;
65
+ }
66
+ function _(e, t) {
67
+ if (t === null) return !0;
68
+ let n = Number(e), r = Number(t);
69
+ return Number.isFinite(n) && Number.isFinite(r) ? n > r : e !== t;
70
+ }
71
+ // src/lib/sse/client.ts
72
+ var v = 500, y = 2, b = 7e3;
73
+ function ee(e, t) {
74
+ return new Promise((n) => {
75
+ if (t.aborted) return n();
76
+ let r = setTimeout(n, e);
77
+ t.addEventListener("abort", () => {
78
+ clearTimeout(r), n();
79
+ }, { once: !0 });
80
+ });
81
+ }
82
+ async function te(e, t) {
83
+ if (t <= 0) return e.read();
84
+ let n, r = new Promise((e, r) => {
85
+ n = setTimeout(() => r(/* @__PURE__ */ Error("idle timeout")), t);
86
+ });
87
+ try {
88
+ return await Promise.race([e.read(), r]);
89
+ } catch (t) {
90
+ throw e.cancel().catch(() => {}), t;
91
+ } finally {
92
+ n !== void 0 && clearTimeout(n);
93
+ }
94
+ }
95
+ function ne(e) {
96
+ return e === 0 || e === 408 || e === 429 || e >= 500;
97
+ }
98
+ function re(e, t = 500, n = 2, r = b) {
99
+ return Math.min(t * n ** Math.max(0, e - 1), r);
100
+ }
101
+ function x(e) {
102
+ let { url: t, method: n = "POST", headers: r = {}, body: i, backoffBaseMs: a = 500, backoffFactor: o = 2, backoffMaxMs: s = b, maxAttempts: c = 8, idleTimeoutMs: l = 0, isRetriable: u = (e) => ne(e.status), fetch: d = globalThis.fetch, onStatus: f = () => {}, onEvent: p, getCursor: m = () => null } = e, g = new AbortController(), v = "idle", y = 0, x = e.lastEventId ?? null, S = (e, t) => {
103
+ v = e, f(e, t);
104
+ }, C = async (e) => {
105
+ if (!e.body) throw Error("response has no body");
106
+ let t = e.body.getReader(), n = new TextDecoder(), r = "";
107
+ for (;;) {
108
+ let { value: e, done: i } = await te(t, l);
109
+ if (i) break;
110
+ r += n.decode(e, { stream: !0 });
111
+ let { frames: a, rest: o } = h(r);
112
+ r = o;
113
+ for (let e of a) {
114
+ if (e.id !== null) {
115
+ if (!_(e.id, m() ?? x)) continue;
116
+ x = e.id;
117
+ }
118
+ p(e);
119
+ }
120
+ }
121
+ if (r += n.decode(), r.trim() !== "") {
122
+ let { frames: e } = h(`${r}\n\n`);
123
+ for (let t of e) (t.id === null || _(t.id, m() ?? x)) && (t.id !== null && (x = t.id), p(t));
124
+ }
125
+ };
126
+ return (async () => {
127
+ for (; !g.signal.aborted;) {
128
+ S(y === 0 ? "connecting" : "reconnecting", {
129
+ attempt: y,
130
+ delayMs: 0
131
+ });
132
+ try {
133
+ let e = {
134
+ accept: "text/event-stream",
135
+ ...r
136
+ };
137
+ i !== void 0 && n !== "GET" && (e["content-type"] = "application/json"), x !== null && (e["last-event-id"] = x);
138
+ let a = await d(t, {
139
+ method: n,
140
+ headers: e,
141
+ body: i === void 0 || n === "GET" ? void 0 : JSON.stringify(i),
142
+ signal: g.signal,
143
+ cache: "no-store"
144
+ });
145
+ if (g.signal.aborted) return;
146
+ if (!a.ok) {
147
+ let e = `HTTP ${a.status}`;
148
+ if (!u({
149
+ status: a.status,
150
+ attempt: y
151
+ })) {
152
+ S("error", {
153
+ attempt: y,
154
+ delayMs: 0,
155
+ reason: e
156
+ });
157
+ return;
158
+ }
159
+ throw Error(e);
160
+ }
161
+ if (y = 0, S("open", {
162
+ attempt: 0,
163
+ delayMs: 0
164
+ }), await C(a), g.signal.aborted) return;
165
+ throw Error("stream ended before turn.end");
166
+ } catch (e) {
167
+ if (g.signal.aborted) return;
168
+ y += 1;
169
+ let t = re(y, a, o, s), n = e instanceof Error ? e.message : String(e);
170
+ if (!(u({
171
+ status: 0,
172
+ attempt: y
173
+ }) && y <= c)) {
174
+ S("error", {
175
+ attempt: y,
176
+ delayMs: 0,
177
+ reason: n
178
+ });
179
+ return;
180
+ }
181
+ S("reconnecting", {
182
+ attempt: y,
183
+ delayMs: t,
184
+ reason: n
185
+ }), await ee(t, g.signal);
186
+ }
187
+ }
188
+ })(), {
189
+ close() {
190
+ g.signal.aborted || (g.abort(), S("stopped", {
191
+ attempt: y,
192
+ delayMs: 0,
193
+ reason: "aborted-by-user"
194
+ }));
195
+ },
196
+ get status() {
197
+ return v;
198
+ }
199
+ };
200
+ }
201
+ // src/lib/core/reducer.ts
202
+ var S = /* @__PURE__ */ new Set([
203
+ "turn.start",
204
+ "message.delta",
205
+ "message.done",
206
+ "tool.call",
207
+ "tool.args",
208
+ "tool.result",
209
+ "turn.end",
210
+ "error",
211
+ "ping"
212
+ ]);
213
+ function C(e) {
214
+ return S.has(e);
215
+ }
216
+ function ie(e, t) {
217
+ if (!C(e)) return null;
218
+ let n;
219
+ try {
220
+ n = t === "" ? {} : JSON.parse(t);
221
+ } catch {
222
+ return null;
223
+ }
224
+ return typeof n != "object" || !n ? null : {
225
+ type: e,
226
+ ...n
227
+ };
228
+ }
229
+ function w(e) {
230
+ let t = e.trim();
231
+ if (t === "") return null;
232
+ try {
233
+ return {
234
+ value: JSON.parse(t),
235
+ complete: !0
236
+ };
237
+ } catch {}
238
+ let n = ae(t);
239
+ if (n === null) return null;
240
+ try {
241
+ return {
242
+ value: JSON.parse(n),
243
+ complete: !1
244
+ };
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
249
+ function ae(e) {
250
+ let t = [], n = !1, r = !1, i = -1;
251
+ for (let a = 0; a < e.length; a += 1) {
252
+ let o = e[a];
253
+ if (n) r ? r = !1 : o === "\\" ? r = !0 : o === "\"" && (n = !1);
254
+ else if (o === "\"") n = !0;
255
+ else if (o === "{" || o === "[") t.push(o);
256
+ else if (o === "}" || o === "]") {
257
+ if (t.length === 0) return null;
258
+ t.pop(), t.length === 0 && (i = a);
259
+ }
260
+ }
261
+ if (n) return null;
262
+ if (i !== -1) return e.slice(0, i + 1);
263
+ if (t.length === 0) return null;
264
+ let a = e.replace(/,\s*$/, "");
265
+ a.endsWith(":") && (a = `${a} null`);
266
+ let o = t.slice().reverse().map((e) => e === "{" ? "}" : "]").join("");
267
+ return a + o;
268
+ }
269
+ var T = (e = Date.now()) => ({
270
+ turnId: null,
271
+ status: "running",
272
+ parts: [],
273
+ toolCalls: [],
274
+ error: null,
275
+ interrupted: !1,
276
+ startedAt: e,
277
+ endedAt: null
278
+ }), E = () => ({
279
+ messages: [],
280
+ live: null,
281
+ status: "idle",
282
+ reconnect: null
283
+ });
284
+ function oe(e, t) {
285
+ if (t === "") return e;
286
+ let n = e[e.length - 1];
287
+ if (n && n.kind === "text") {
288
+ let r = e.slice(0, -1);
289
+ return r.push({
290
+ kind: "text",
291
+ text: n.text + t
292
+ }), r;
293
+ }
294
+ return [...e, {
295
+ kind: "text",
296
+ text: t
297
+ }];
298
+ }
299
+ function D(e, t) {
300
+ let n = e.findIndex((e) => e.callId === t.callId);
301
+ if (n === -1) return [...e, t];
302
+ let r = e.slice();
303
+ return r[n] = t, r;
304
+ }
305
+ var se = 0;
306
+ function ce(e) {
307
+ return se += 1, `${e}-${Date.now().toString(36)}-${se}`;
308
+ }
309
+ function O(e, t, n, r) {
310
+ return e.parts.some((e) => e.kind === "tool" || e.kind === "text" && e.text.trim() !== "") ? {
311
+ id: e.turnId ?? ce("assistant"),
312
+ role: "assistant",
313
+ parts: e.parts,
314
+ toolCalls: e.toolCalls.map((e) => e.status === "running" ? {
315
+ ...e,
316
+ status: "error",
317
+ preview: e.preview ?? "未返回结果"
318
+ } : e),
319
+ status: t,
320
+ createdAt: e.startedAt || n,
321
+ ...r === void 0 ? {} : { error: r }
322
+ } : null;
323
+ }
324
+ function k(e, t, n = Date.now()) {
325
+ switch (t.type) {
326
+ case "ping": return e;
327
+ case "turn.start": return {
328
+ ...e,
329
+ live: {
330
+ ...T(n),
331
+ turnId: t.turnId,
332
+ startedAt: n
333
+ }
334
+ };
335
+ case "message.delta": {
336
+ let r = e.live ?? T(n);
337
+ return {
338
+ ...e,
339
+ live: {
340
+ ...r,
341
+ parts: oe(r.parts, t.text)
342
+ }
343
+ };
344
+ }
345
+ case "tool.call": {
346
+ let r = e.live ?? T(n), i = {
347
+ callId: t.callId,
348
+ name: t.name,
349
+ args: t.arguments ?? "",
350
+ argsComplete: !1,
351
+ status: "running",
352
+ startedAt: n
353
+ };
354
+ return {
355
+ ...e,
356
+ live: {
357
+ ...r,
358
+ toolCalls: D(r.toolCalls, i),
359
+ parts: le(r.parts, t.callId) ? r.parts : [...r.parts, {
360
+ kind: "tool",
361
+ callId: t.callId
362
+ }]
363
+ }
364
+ };
365
+ }
366
+ case "tool.args": {
367
+ let n = e.live;
368
+ if (!n) return e;
369
+ let r = n.toolCalls.find((e) => e.callId === t.callId);
370
+ if (!r) return e;
371
+ let i = {
372
+ ...r,
373
+ args: r.args + t.arguments,
374
+ argsComplete: t.complete ?? r.argsComplete
375
+ };
376
+ return {
377
+ ...e,
378
+ live: {
379
+ ...n,
380
+ toolCalls: D(n.toolCalls, i)
381
+ }
382
+ };
383
+ }
384
+ case "tool.result": {
385
+ let r = e.live;
386
+ if (!r) return e;
387
+ let i = r.toolCalls.find((e) => e.callId === t.callId);
388
+ if (!i) return e;
389
+ let a = {
390
+ ...i,
391
+ argsComplete: !0,
392
+ status: t.ok ? "ok" : "error",
393
+ preview: t.preview ?? i.preview,
394
+ durationMs: t.durationMs ?? n - i.startedAt
395
+ };
396
+ return {
397
+ ...e,
398
+ live: {
399
+ ...r,
400
+ toolCalls: D(r.toolCalls, a)
401
+ }
402
+ };
403
+ }
404
+ case "message.done": {
405
+ let t = e.live;
406
+ return t ? {
407
+ ...e,
408
+ live: {
409
+ ...t,
410
+ parts: t.parts
411
+ }
412
+ } : e;
413
+ }
414
+ case "error": {
415
+ let r = e.live ?? T(n), i = {
416
+ message: t.message,
417
+ stage: t.stage ?? "unknown",
418
+ retriable: t.retriable ?? !0
419
+ }, a = O(r, "error", n, i);
420
+ return {
421
+ ...e,
422
+ messages: a ? [...e.messages, a] : e.messages,
423
+ live: a ? null : {
424
+ ...r,
425
+ status: "error",
426
+ error: i,
427
+ endedAt: n
428
+ }
429
+ };
430
+ }
431
+ case "turn.end": {
432
+ let r = e.live;
433
+ if (!r) return e;
434
+ let i = O(r, t.reason === "stopped" ? "stopped" : "done", n);
435
+ return {
436
+ ...e,
437
+ messages: i ? [...e.messages, i] : e.messages,
438
+ live: null
439
+ };
440
+ }
441
+ default: return e;
442
+ }
443
+ }
444
+ function le(e, t) {
445
+ return e.some((e) => e.kind === "tool" && e.callId === t);
446
+ }
447
+ function ue(e, t, n = Date.now()) {
448
+ let r = t.trim();
449
+ return r === "" ? e : {
450
+ ...e,
451
+ messages: [...e.messages, {
452
+ id: ce("user"),
453
+ role: "user",
454
+ parts: [{
455
+ kind: "text",
456
+ text: r
457
+ }],
458
+ toolCalls: [],
459
+ status: "done",
460
+ createdAt: n
461
+ }]
462
+ };
463
+ }
464
+ function A(e, t = Date.now()) {
465
+ let n = e.live;
466
+ if (!n) return e;
467
+ let r = O(n, "stopped", t);
468
+ return {
469
+ ...e,
470
+ messages: r ? [...e.messages, r] : e.messages,
471
+ live: null,
472
+ status: "stopped"
473
+ };
474
+ }
475
+ function j(e, t, n) {
476
+ let r = t === "reconnecting", i = r ? n ?? null : null, a = e.live;
477
+ return {
478
+ ...e,
479
+ status: t,
480
+ reconnect: i,
481
+ live: a && a.interrupted !== r ? {
482
+ ...a,
483
+ interrupted: r
484
+ } : a
485
+ };
486
+ }
487
+ function M(e, t = Date.now()) {
488
+ return e.live ? k(e, {
489
+ type: "error",
490
+ message: "连接已断开,本轮未完成",
491
+ stage: "unknown",
492
+ retriable: !0
493
+ }, t) : e;
494
+ }
495
+ // src/lib/core/scheduler.ts
496
+ var N = {
497
+ schedule(e) {
498
+ return e(), null;
499
+ },
500
+ cancel() {}
501
+ }, P = {
502
+ schedule(e) {
503
+ return typeof requestAnimationFrame == "function" ? requestAnimationFrame(() => e()) : setTimeout(e, 16);
504
+ },
505
+ cancel(e) {
506
+ typeof cancelAnimationFrame == "function" && cancelAnimationFrame(e);
507
+ }
508
+ };
509
+ function F() {
510
+ return typeof requestAnimationFrame == "function" ? P : N;
511
+ }
512
+ // src/lib/core/store.ts
513
+ function de(e) {
514
+ let { transport: t, now: n = Date.now, onEvent: r } = e, i = e.scheduler ?? F(), a = E(), o = null, s = null, c = !1, l = /* @__PURE__ */ new Set(), u = () => {
515
+ c = !1, s = null;
516
+ for (let e of [...l]) e();
517
+ }, d = () => {
518
+ c || (c = !0, s = i.schedule(u));
519
+ }, f = () => {
520
+ c && (i.cancel(s), c = !1, s = null);
521
+ }, p = () => {
522
+ o?.abort(), o = null;
523
+ }, m = (e, t) => {
524
+ (e !== "stopped" || a.live !== null) && (a = j(a, e, t), (e === "closed" || e === "error") && a.live && a.live.status === "running" && (a = M(a, n())), d());
525
+ }, h = (e) => {
526
+ let t = ie(e.event, e.data);
527
+ t && (r?.(t, e), a = k(a, t, n()), d(), t.type === "turn.end" && (a = {
528
+ ...a,
529
+ status: "closed"
530
+ }, d(), p()));
531
+ }, g = (e, n) => {
532
+ p();
533
+ let r = new AbortController();
534
+ o = r, t.open({
535
+ text: e,
536
+ history: n,
537
+ signal: r.signal,
538
+ onFrame: h,
539
+ onStatus: m
540
+ });
541
+ };
542
+ return {
543
+ subscribe(e) {
544
+ return l.add(e), () => {
545
+ l.delete(e);
546
+ };
547
+ },
548
+ getSnapshot() {
549
+ return a;
550
+ },
551
+ send(e) {
552
+ let t = a.live;
553
+ if (t && t.status === "running") return;
554
+ let r = e.trim();
555
+ if (r === "") return;
556
+ let i = n(), o = a.messages;
557
+ a = ue({
558
+ ...a,
559
+ live: null
560
+ }, r, i), a = {
561
+ ...a,
562
+ live: T(i),
563
+ status: "connecting",
564
+ reconnect: null
565
+ }, d(), g(r, o);
566
+ },
567
+ stop() {
568
+ a.live && (a = A(a, n()), d()), p();
569
+ },
570
+ retry() {
571
+ let e = a.live;
572
+ if (!(e && e.status === "error" || a.status === "error" || a.messages.at(-1)?.status === "error")) return;
573
+ let t = [...a.messages].reverse().find((e) => e.role === "user");
574
+ if (!t) return;
575
+ let r = t.parts.filter((e) => e.kind === "text").map((e) => e.text).join("\n"), i = a.messages.lastIndexOf(t), o = a.messages.slice(0, i), s = n();
576
+ a = {
577
+ ...a,
578
+ live: T(s),
579
+ status: "connecting",
580
+ reconnect: null
581
+ }, d(), g(r, o);
582
+ },
583
+ reset() {
584
+ p(), f(), a = E(), d();
585
+ }
586
+ };
587
+ }
588
+ // src/lib/core/transport.ts
589
+ function I(e) {
590
+ return e.map((e) => ({
591
+ role: e.role,
592
+ text: e.parts.filter((e) => e.kind === "text").map((e) => e.text).join("\n")
593
+ }));
594
+ }
595
+ function fe() {
596
+ return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `t_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
597
+ }
598
+ function pe(e) {
599
+ let { url: t, headers: n, fetch: r, buildBody: i, idleTimeoutMs: a, maxAttempts: o, backoffBaseMs: s } = e;
600
+ return { open(e) {
601
+ let c = fe(), l = (i ?? me)({
602
+ text: e.text,
603
+ history: e.history
604
+ }), u = typeof l == "object" && l && !Array.isArray(l) ? {
605
+ clientTurnId: c,
606
+ ...l
607
+ } : l, d = x({
608
+ url: t,
609
+ method: "POST",
610
+ headers: n,
611
+ body: u,
612
+ fetch: r,
613
+ ...a === void 0 ? {} : { idleTimeoutMs: a },
614
+ ...o === void 0 ? {} : { maxAttempts: o },
615
+ ...s === void 0 ? {} : { backoffBaseMs: s },
616
+ onEvent: e.onFrame,
617
+ onStatus: e.onStatus
618
+ });
619
+ e.signal.addEventListener("abort", () => d.close(), { once: !0 });
620
+ } };
621
+ }
622
+ function me({ text: e, history: t }) {
623
+ return {
624
+ text: e,
625
+ history: I(t)
626
+ };
627
+ }
628
+ function he(e, t = {}) {
629
+ let { dropAfterChunk: n = -1, reconnectDelayMs: r = 1200 } = t;
630
+ return { open({ signal: t, onFrame: i, onStatus: a }) {
631
+ let o = 0, s = !1, c = (e, n) => {
632
+ t.aborted || l.push(setTimeout(e, n));
633
+ }, l = [], u = () => {
634
+ for (let e of l) clearTimeout(e);
635
+ l.length = 0;
636
+ };
637
+ t.addEventListener("abort", u, { once: !0 });
638
+ let d = (e) => {
639
+ let { frames: t } = h(e);
640
+ for (let e of t) i(e);
641
+ }, f = () => {
642
+ if (t.aborted) return;
643
+ let i = e[o];
644
+ i ? (o += 1, !s && n >= 0 && o - 1 === n ? (s = !0, a("reconnecting", {
645
+ attempt: 1,
646
+ delayMs: r,
647
+ reason: "simulated-disconnect"
648
+ }), c(() => {
649
+ a("open", {
650
+ attempt: 1,
651
+ delayMs: 0
652
+ }), f();
653
+ }, r)) : (d(i.chunk), c(f, i.delayMs))) : (a("closed", {
654
+ attempt: 0,
655
+ delayMs: 0,
656
+ reason: "script-finished"
657
+ }), u());
658
+ };
659
+ a("connecting", {
660
+ attempt: 0,
661
+ delayMs: 0
662
+ }), c(() => {
663
+ a("open", {
664
+ attempt: 0,
665
+ delayMs: 0
666
+ }), f();
667
+ }, 120);
668
+ } };
669
+ }
670
+ // src/lib/adapters/openai.ts
671
+ function ge() {
672
+ let e = null, t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Set();
673
+ return {
674
+ translate: (r) => {
675
+ let i = r.choices?.[0];
676
+ if (!i) return [];
677
+ let a = [], o = i.delta ?? {};
678
+ typeof o.content == "string" && o.content !== "" && a.push({
679
+ type: "message.delta",
680
+ text: o.content
681
+ });
682
+ for (let e of o.tool_calls ?? []) {
683
+ let r = e.index ?? 0;
684
+ if (!t.has(r)) {
685
+ let n = e.id ?? `call_${r}`, i = e.function?.name ?? "unknown_tool";
686
+ t.set(r, {
687
+ callId: n,
688
+ name: i
689
+ }), a.push({
690
+ type: "tool.call",
691
+ callId: n,
692
+ name: i,
693
+ arguments: ""
694
+ });
695
+ }
696
+ let i = t.get(r), o = e.function?.arguments;
697
+ typeof o == "string" && o !== "" && (n.add(r), a.push({
698
+ type: "tool.args",
699
+ callId: i.callId,
700
+ arguments: o
701
+ }));
702
+ }
703
+ if (i.finish_reason && (e = i.finish_reason, e === "tool_calls")) for (let [e, r] of t) n.has(e) || a.push({
704
+ type: "tool.args",
705
+ callId: r.callId,
706
+ arguments: ""
707
+ }), a.push({
708
+ type: "tool.args",
709
+ callId: r.callId,
710
+ arguments: "",
711
+ complete: !0
712
+ });
713
+ return a;
714
+ },
715
+ get finishReason() {
716
+ return e;
717
+ },
718
+ get toolCalls() {
719
+ return t;
720
+ },
721
+ reset() {
722
+ e = null, t.clear(), n.clear();
723
+ }
724
+ };
725
+ }
726
+ // src/lib/markdown/blocks.ts
727
+ var _e = /^(#{1,6})\s+(.*)$/, ve = /^(```|~~~)\s*([\w+#.-]*)\s*$/, L = /^\s*(?:[-*+]|\d+[.)])\s+/, R = /^\s*>\s?/, ye = /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/;
728
+ function z(e, t, n) {
729
+ if (!t || t.lines.length === 0) return;
730
+ let r = t.lines.join("\n");
731
+ e.push({
732
+ key: `${t.kind}-${e.length}`,
733
+ kind: t.kind,
734
+ text: r,
735
+ closed: n,
736
+ ...t.level === void 0 ? {} : { level: t.level },
737
+ ...t.lang === void 0 ? {} : { lang: t.lang },
738
+ ...t.ordered === void 0 ? {} : { ordered: t.ordered }
739
+ }), t.lines = [];
740
+ }
741
+ function B(e) {
742
+ let t = e.split("\n"), n = [], r = null, i = 0;
743
+ for (; i < t.length;) {
744
+ let e = t[i] ?? "", a = ve.exec(e.trim());
745
+ if (a) {
746
+ z(n, r, !0), r = null;
747
+ let e = a[1] ?? "```", o = a[2] ?? "", s = [], c = !1;
748
+ for (i += 1; i < t.length; i += 1) {
749
+ let n = t[i] ?? "";
750
+ if (n.trim().startsWith(e)) {
751
+ c = !0, i += 1;
752
+ break;
753
+ }
754
+ s.push(n);
755
+ }
756
+ n.push({
757
+ key: `code-${n.length}`,
758
+ kind: "code",
759
+ text: s.join("\n"),
760
+ closed: c,
761
+ lang: o
762
+ });
763
+ continue;
764
+ }
765
+ if (e.trim() === "") {
766
+ z(n, r, !0), r = null, i += 1;
767
+ continue;
768
+ }
769
+ let o = _e.exec(e);
770
+ if (o) z(n, r, !0), r = null, n.push({
771
+ key: `heading-${n.length}`,
772
+ kind: "heading",
773
+ text: o[2] ?? "",
774
+ closed: !0,
775
+ level: (o[1] ?? "#").length
776
+ }), i += 1;
777
+ else if (ye.test(e)) z(n, r, !0), r = null, n.push({
778
+ key: `hr-${n.length}`,
779
+ kind: "hr",
780
+ text: "",
781
+ closed: !0
782
+ }), i += 1;
783
+ else if (R.test(e)) r && r.kind !== "quote" && (z(n, r, !0), r = null), r ??= {
784
+ kind: "quote",
785
+ lines: []
786
+ }, r.lines.push(e.replace(R, "")), i += 1;
787
+ else if (L.test(e)) {
788
+ let t = /^\s*\d+[.)]\s+/.test(e);
789
+ r && r.kind !== "list" && (z(n, r, !0), r = null), r && r.ordered !== t && (z(n, r, !0), r = null), r ??= {
790
+ kind: "list",
791
+ lines: [],
792
+ ordered: t
793
+ }, r.lines.push(e), i += 1;
794
+ } else r && r.kind !== "paragraph" && (z(n, r, !0), r = null), r ??= {
795
+ kind: "paragraph",
796
+ lines: []
797
+ }, r.lines.push(e), i += 1;
798
+ }
799
+ return z(n, r, !1), n;
800
+ }
801
+ function V(e) {
802
+ return e.replace(L, "");
803
+ }
804
+ function be(e) {
805
+ return e ? {
806
+ ts: "ts",
807
+ tsx: "tsx",
808
+ typescript: "ts",
809
+ js: "js",
810
+ javascript: "js",
811
+ json: "json",
812
+ bash: "bash",
813
+ sh: "sh",
814
+ python: "py",
815
+ py: "py",
816
+ css: "css",
817
+ html: "html"
818
+ }[e.toLowerCase()] ?? e : "text";
819
+ }
820
+ // src/lib/markdown/inline.tsx
821
+ var H = /(`[^`\n]+`)|(\*\*[^*\n]+\*\*)|(\*[^*\n]+\*)|(\[[^\]\n]+\]\([^)\s]+\))|(https?:\/\/[^\s<>"']+)/g;
822
+ function U(e) {
823
+ let t = e.trim();
824
+ return t === "" ? !1 : t.startsWith("#") || t.startsWith("/") ? !0 : /^(https?:|mailto:)/i.test(t);
825
+ }
826
+ function xe(t, n, r) {
827
+ return U(n) ? /* @__PURE__ */ u("a", {
828
+ href: n,
829
+ target: "_blank",
830
+ rel: "noreferrer noopener",
831
+ children: t
832
+ }, r) : /* @__PURE__ */ u(e, { children: t }, r);
833
+ }
834
+ function W(e) {
835
+ if (e === "") return [];
836
+ let t = [], n = 0, r;
837
+ for (H.lastIndex = 0; (r = H.exec(e)) !== null;) {
838
+ r.index > n && t.push(e.slice(n, r.index));
839
+ let i = r[0], a = `i-${t.length}`;
840
+ if (i.startsWith("`")) t.push(/* @__PURE__ */ u("code", {
841
+ className: "asui-inline-code",
842
+ children: i.slice(1, -1)
843
+ }, a));
844
+ else if (i.startsWith("**")) t.push(/* @__PURE__ */ u("strong", { children: i.slice(2, -2) }, a));
845
+ else if (i.startsWith("*")) t.push(/* @__PURE__ */ u("em", { children: i.slice(1, -1) }, a));
846
+ else if (i.startsWith("[")) {
847
+ let e = /^\[([^\]]+)\]\(([^)]+)\)$/.exec(i);
848
+ e ? t.push(xe(e[1] ?? "", e[2] ?? "", a)) : t.push(i);
849
+ } else t.push(xe(i, i, a));
850
+ n = r.index + i.length;
851
+ }
852
+ return n < e.length && t.push(e.slice(n)), t;
853
+ }
854
+ function G(e) {
855
+ let t = e.split("\n"), n = [];
856
+ return t.forEach((e, t) => {
857
+ t > 0 && n.push(/* @__PURE__ */ u("br", {}, `br-${t}`)), n.push(...W(e));
858
+ }), n;
859
+ }
860
+ // src/lib/markdown/render.tsx
861
+ var Se = 500, K = /* @__PURE__ */ new Map();
862
+ function Ce(e) {
863
+ return [
864
+ e.kind,
865
+ e.level ?? "",
866
+ e.lang ?? "",
867
+ e.ordered ? "1" : "0",
868
+ e.text
869
+ ].join("\0");
870
+ }
871
+ function we(e, t) {
872
+ let n = Ce(e);
873
+ if (e.closed) {
874
+ let e = K.get(n);
875
+ if (e !== void 0) return e;
876
+ }
877
+ let r = Ee(e, t);
878
+ if (e.closed) {
879
+ if (K.size >= Se) {
880
+ let e = K.keys().next();
881
+ e.done || K.delete(e.value);
882
+ }
883
+ K.set(n, r);
884
+ }
885
+ return r;
886
+ }
887
+ function Te() {
888
+ K.clear();
889
+ }
890
+ function Ee(e, t) {
891
+ switch (e.kind) {
892
+ case "heading": {
893
+ let t = Math.min(Math.max(e.level ?? 1, 1), 6), n = `h${t}`;
894
+ return /* @__PURE__ */ u(n, {
895
+ className: `asui-h asui-h${t}`,
896
+ children: W(e.text)
897
+ });
898
+ }
899
+ case "code": return /* @__PURE__ */ u(De, {
900
+ code: e.text,
901
+ lang: e.lang,
902
+ streaming: t
903
+ });
904
+ case "list": {
905
+ let t = e.text.split("\n").filter((e) => e.trim() !== "").map((e) => V(e)).map((e, t) => /* @__PURE__ */ u("li", { children: W(e) }, `li-${t}`));
906
+ return e.ordered ? /* @__PURE__ */ u("ol", {
907
+ className: "asui-list",
908
+ children: t
909
+ }) : /* @__PURE__ */ u("ul", {
910
+ className: "asui-list",
911
+ children: t
912
+ });
913
+ }
914
+ case "quote": return /* @__PURE__ */ u("blockquote", {
915
+ className: "asui-quote",
916
+ children: G(e.text)
917
+ });
918
+ case "hr": return /* @__PURE__ */ u("hr", { className: "asui-hr" });
919
+ default: return /* @__PURE__ */ u("p", {
920
+ className: "asui-p",
921
+ children: G(e.text)
922
+ });
923
+ }
924
+ }
925
+ function De({ code: e, lang: t, streaming: n }) {
926
+ let [r, i] = s(!1);
927
+ return /* @__PURE__ */ d("div", {
928
+ className: "asui-code",
929
+ children: [/* @__PURE__ */ d("div", {
930
+ className: "asui-code-head",
931
+ children: [/* @__PURE__ */ u("span", {
932
+ className: "asui-code-lang",
933
+ children: be(t)
934
+ }), !n && /* @__PURE__ */ u("button", {
935
+ type: "button",
936
+ className: "asui-code-copy",
937
+ onClick: () => {
938
+ let t = typeof navigator > "u" ? void 0 : navigator.clipboard;
939
+ t && t.writeText(e).then(() => {
940
+ i(!0), setTimeout(() => i(!1), 1400);
941
+ }, () => {});
942
+ },
943
+ children: r ? "已复制" : "复制"
944
+ })]
945
+ }), /* @__PURE__ */ u("pre", { children: /* @__PURE__ */ u("code", { children: e }) })]
946
+ });
947
+ }
948
+ var Oe = t(function({ block: e, streaming: t }) {
949
+ return /* @__PURE__ */ u(l, { children: we(e, t) });
950
+ }, (e, t) => e.streaming === t.streaming && e.block.kind === t.block.kind && e.block.closed === t.block.closed && e.block.level === t.block.level && e.block.lang === t.block.lang && e.block.ordered === t.block.ordered && e.block.text === t.block.text);
951
+ // src/lib/react/use-agent-stream.ts
952
+ function ke(e) {
953
+ return c(e.subscribe, e.getSnapshot, e.getSnapshot);
954
+ }
955
+ // src/lib/react/markdown-stream.tsx
956
+ var Ae = t(function({ text: e, streaming: t = !1, className: n }) {
957
+ let r = a(() => B(e), [e]);
958
+ return /* @__PURE__ */ d("div", {
959
+ className: n ? `asui-md ${n}` : "asui-md",
960
+ children: [r.map((e) => /* @__PURE__ */ u(Oe, {
961
+ block: e,
962
+ streaming: t && !e.closed
963
+ }, e.key)), t && /* @__PURE__ */ u("span", {
964
+ className: "asui-caret",
965
+ "aria-hidden": "true"
966
+ })]
967
+ });
968
+ }), q = {
969
+ width: 16,
970
+ height: 16,
971
+ viewBox: "0 0 24 24",
972
+ fill: "none",
973
+ stroke: "currentColor",
974
+ strokeWidth: 1.8,
975
+ strokeLinecap: "round",
976
+ strokeLinejoin: "round",
977
+ "aria-hidden": !0
978
+ };
979
+ function je(e) {
980
+ return /* @__PURE__ */ u("svg", {
981
+ ...q,
982
+ ...e,
983
+ children: /* @__PURE__ */ u("path", { d: "M4 11.5 20 4l-7.5 16-1.8-6.2L4 11.5Z" })
984
+ });
985
+ }
986
+ function Me(e) {
987
+ return /* @__PURE__ */ u("svg", {
988
+ ...q,
989
+ ...e,
990
+ children: /* @__PURE__ */ u("rect", {
991
+ x: "6",
992
+ y: "6",
993
+ width: "12",
994
+ height: "12",
995
+ rx: "2",
996
+ fill: "currentColor",
997
+ stroke: "none"
998
+ })
999
+ });
1000
+ }
1001
+ function J(e) {
1002
+ return /* @__PURE__ */ d("svg", {
1003
+ ...q,
1004
+ ...e,
1005
+ children: [/* @__PURE__ */ u("path", { d: "M20 12a8 8 0 1 1-2.4-5.7" }), /* @__PURE__ */ u("path", { d: "M20 4v4h-4" })]
1006
+ });
1007
+ }
1008
+ function Ne(e) {
1009
+ return /* @__PURE__ */ u("svg", {
1010
+ ...q,
1011
+ ...e,
1012
+ children: /* @__PURE__ */ u("path", { d: "M14.7 6.3a4 4 0 0 0 5 5l-8.4 8.4a2.4 2.4 0 0 1-3.4-3.4l8.4-8.4a4 4 0 0 0-1.6-1.6Z" })
1013
+ });
1014
+ }
1015
+ function Pe(e) {
1016
+ return /* @__PURE__ */ u("svg", {
1017
+ ...q,
1018
+ ...e,
1019
+ children: /* @__PURE__ */ u("path", { d: "m5 13 4 4L19 7" })
1020
+ });
1021
+ }
1022
+ function Y(e) {
1023
+ return /* @__PURE__ */ d("svg", {
1024
+ ...q,
1025
+ ...e,
1026
+ children: [
1027
+ /* @__PURE__ */ u("path", { d: "M12 8v5" }),
1028
+ /* @__PURE__ */ u("path", { d: "M12 16.5v.5" }),
1029
+ /* @__PURE__ */ u("path", { d: "M10.3 4.3 2.9 17.4A2 2 0 0 0 4.6 20h14.8a2 2 0 0 0 1.7-2.6L13.7 4.3a2 2 0 0 0-3.4 0Z" })
1030
+ ]
1031
+ });
1032
+ }
1033
+ function Fe(e) {
1034
+ return /* @__PURE__ */ d("svg", {
1035
+ ...q,
1036
+ ...e,
1037
+ children: [/* @__PURE__ */ u("path", { d: "M12 5v14" }), /* @__PURE__ */ u("path", { d: "m6 13 6 6 6-6" })]
1038
+ });
1039
+ }
1040
+ function X(e) {
1041
+ return /* @__PURE__ */ u("svg", {
1042
+ ...q,
1043
+ ...e,
1044
+ children: /* @__PURE__ */ u("path", { d: "M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M18 6l-2.5 2.5M8.5 15.5 6 18" })
1045
+ });
1046
+ }
1047
+ // src/lib/react/tool-call-card.tsx
1048
+ var Z = 160;
1049
+ function Ie(e) {
1050
+ if (typeof e == "string") return e.length > Z ? `${e.slice(0, Z)}…` : e;
1051
+ if (typeof e == "number" || typeof e == "boolean" || e === null) return String(e);
1052
+ try {
1053
+ let t = JSON.stringify(e);
1054
+ return t.length > Z ? `${t.slice(0, Z)}…` : t;
1055
+ } catch {
1056
+ return "[unserializable]";
1057
+ }
1058
+ }
1059
+ function Le(e) {
1060
+ return e.status === "running" ? "调用中" : e.status === "ok" ? "完成" : "失败";
1061
+ }
1062
+ function Re(e) {
1063
+ return e.durationMs === void 0 ? null : e.durationMs < 1e3 ? `${Math.max(1, Math.round(e.durationMs))}ms` : `${(e.durationMs / 1e3).toFixed(1)}s`;
1064
+ }
1065
+ function ze({ tool: e }) {
1066
+ let [t, n] = s(e.status === "error"), r = e.args.trim() === "" ? null : w(e.args), i = r && typeof r.value == "object" && r.value !== null ? Object.entries(r.value) : null, a = Re(e);
1067
+ return /* @__PURE__ */ d("section", {
1068
+ className: `asui-tool asui-tool--${e.status}`,
1069
+ "data-testid": "tool-call-card",
1070
+ "data-status": e.status,
1071
+ children: [/* @__PURE__ */ d("button", {
1072
+ type: "button",
1073
+ className: "asui-tool-head",
1074
+ onClick: () => n((e) => !e),
1075
+ "aria-expanded": t,
1076
+ children: [
1077
+ /* @__PURE__ */ u("span", {
1078
+ className: "asui-tool-icon",
1079
+ children: e.status === "ok" ? /* @__PURE__ */ u(Pe, {}) : e.status === "error" ? /* @__PURE__ */ u(Y, {}) : /* @__PURE__ */ u(Ne, {})
1080
+ }),
1081
+ /* @__PURE__ */ u("span", {
1082
+ className: "asui-tool-name",
1083
+ children: e.name
1084
+ }),
1085
+ /* @__PURE__ */ u("span", {
1086
+ className: "asui-tool-status",
1087
+ children: Le(e)
1088
+ }),
1089
+ a && /* @__PURE__ */ u("span", {
1090
+ className: "asui-tool-duration",
1091
+ children: a
1092
+ }),
1093
+ /* @__PURE__ */ u("span", {
1094
+ className: `asui-tool-chevron${t ? " is-open" : ""}`,
1095
+ "aria-hidden": "true",
1096
+ children: "›"
1097
+ })
1098
+ ]
1099
+ }), t && /* @__PURE__ */ d("div", {
1100
+ className: "asui-tool-body",
1101
+ children: [
1102
+ i && i.length > 0 ? /* @__PURE__ */ u("dl", {
1103
+ className: "asui-tool-args",
1104
+ children: i.map(([e, t]) => /* @__PURE__ */ d("div", {
1105
+ className: "asui-tool-arg",
1106
+ children: [/* @__PURE__ */ u("dt", { children: e }), /* @__PURE__ */ u("dd", { children: Ie(t) })]
1107
+ }, e))
1108
+ }) : /* @__PURE__ */ u("pre", {
1109
+ className: "asui-tool-raw",
1110
+ children: e.args || "(无参数)"
1111
+ }),
1112
+ !e.argsComplete && e.status === "running" && /* @__PURE__ */ d("p", {
1113
+ className: "asui-tool-hint",
1114
+ children: ["参数生成中…", r && !r.complete ? "(当前为不完整 JSON,已按可解析部分展示)" : ""]
1115
+ }),
1116
+ e.preview && /* @__PURE__ */ u("pre", {
1117
+ className: "asui-tool-preview",
1118
+ "data-testid": "tool-preview",
1119
+ children: e.preview
1120
+ })
1121
+ ]
1122
+ })]
1123
+ });
1124
+ }
1125
+ // src/lib/react/message-body.tsx
1126
+ function Q({ parts: e, toolCalls: t, streaming: n, role: r }) {
1127
+ let i = new Map(t.map((e) => [e.callId, e]));
1128
+ return /* @__PURE__ */ d(l, { children: [e.map((t, r) => t.kind === "text" ? /* @__PURE__ */ u(Ae, {
1129
+ text: t.text,
1130
+ streaming: n && r === e.length - 1
1131
+ }, `text-${r}`) : /* @__PURE__ */ u(ze, { tool: i.get(t.callId) ?? Be(t.callId) }, `tool-${t.callId}`)), r === "assistant" && n && e.length === 0 && /* @__PURE__ */ d("div", {
1132
+ className: "asui-typing",
1133
+ "data-testid": "typing-indicator",
1134
+ "aria-label": "正在生成",
1135
+ children: [
1136
+ /* @__PURE__ */ u("span", {}),
1137
+ /* @__PURE__ */ u("span", {}),
1138
+ /* @__PURE__ */ u("span", {})
1139
+ ]
1140
+ })] });
1141
+ }
1142
+ function Be(e) {
1143
+ return {
1144
+ callId: e,
1145
+ name: "unknown_tool",
1146
+ args: "",
1147
+ argsComplete: !0,
1148
+ status: "error",
1149
+ preview: "工具调用状态缺失",
1150
+ startedAt: 0
1151
+ };
1152
+ }
1153
+ function $({ message: e, stage: t }) {
1154
+ return /* @__PURE__ */ d("div", {
1155
+ className: "asui-error",
1156
+ role: "alert",
1157
+ children: [/* @__PURE__ */ u(Y, {}), /* @__PURE__ */ d("div", { children: [/* @__PURE__ */ u("strong", { children: "本轮失败" }), /* @__PURE__ */ d("p", { children: [e, t === "unknown" ? "" : `(阶段:${t})`] })] })]
1158
+ });
1159
+ }
1160
+ // src/lib/react/use-stick-to-bottom.ts
1161
+ var Ve = 48;
1162
+ function He(e) {
1163
+ let t = o(null), a = o(!0), [c, l] = s(!0);
1164
+ return i(() => {
1165
+ let e = t.current;
1166
+ e && a.current && (e.scrollTop = e.scrollHeight);
1167
+ }, [e]), r(() => {
1168
+ let e = t.current;
1169
+ if (!e) return;
1170
+ let n = () => {
1171
+ let t = e.scrollHeight - e.scrollTop - e.clientHeight < Ve;
1172
+ a.current = t, l(t);
1173
+ };
1174
+ e.addEventListener("scroll", n, { passive: !0 });
1175
+ let r = typeof ResizeObserver == "function" ? new ResizeObserver(() => {
1176
+ a.current && (e.scrollTop = e.scrollHeight);
1177
+ }) : null;
1178
+ return r?.observe(e), () => {
1179
+ e.removeEventListener("scroll", n), r?.disconnect();
1180
+ };
1181
+ }, []), {
1182
+ ref: t,
1183
+ pinned: c,
1184
+ scrollToBottom: n(() => {
1185
+ let e = t.current;
1186
+ e && (e.scrollTop = e.scrollHeight, a.current = !0, l(!0));
1187
+ }, [])
1188
+ };
1189
+ }
1190
+ // src/lib/react/message-list.tsx
1191
+ function Ue({ snapshot: e, onRetry: t, emptyState: n }) {
1192
+ let { messages: r, live: i } = e, { ref: o, pinned: s, scrollToBottom: c } = He(a(() => {
1193
+ let e = i?.parts.reduce((e, t) => t.kind === "text" ? e + t.text.length : e, 0) ?? 0;
1194
+ return `${r.length}:${e}:${i?.status ?? "none"}`;
1195
+ }, [r.length, i]));
1196
+ return r.length === 0 && !i ? /* @__PURE__ */ u("div", {
1197
+ className: "asui-empty",
1198
+ children: n
1199
+ }) : /* @__PURE__ */ d("div", {
1200
+ className: "asui-list",
1201
+ ref: o,
1202
+ role: "log",
1203
+ "aria-live": "polite",
1204
+ children: [/* @__PURE__ */ d("div", {
1205
+ className: "asui-list-inner",
1206
+ children: [r.map((e) => /* @__PURE__ */ d("article", {
1207
+ className: `asui-msg asui-msg--${e.role}`,
1208
+ "data-testid": `message-${e.role}`,
1209
+ children: [e.role === "assistant" && /* @__PURE__ */ d(l, { children: [/* @__PURE__ */ u(Q, {
1210
+ parts: e.parts,
1211
+ toolCalls: e.toolCalls,
1212
+ streaming: !1,
1213
+ role: "assistant"
1214
+ }), e.error && /* @__PURE__ */ d("div", {
1215
+ className: "asui-error-wrap",
1216
+ children: [/* @__PURE__ */ u($, {
1217
+ message: e.error.message,
1218
+ stage: e.error.stage
1219
+ }), t && /* @__PURE__ */ d("button", {
1220
+ type: "button",
1221
+ className: "asui-inline-retry",
1222
+ onClick: t,
1223
+ children: [/* @__PURE__ */ u(J, {}), " 重试本轮"]
1224
+ })]
1225
+ })] }), e.role === "user" && /* @__PURE__ */ u("p", {
1226
+ className: "asui-user-text",
1227
+ children: e.parts.filter((e) => e.kind === "text").map((e) => e.text).join("\n")
1228
+ })]
1229
+ }, e.id)), i && /* @__PURE__ */ d("article", {
1230
+ className: "asui-msg asui-msg--assistant",
1231
+ "data-testid": "message-live",
1232
+ children: [
1233
+ /* @__PURE__ */ u(Q, {
1234
+ parts: i.parts,
1235
+ toolCalls: i.toolCalls,
1236
+ streaming: i.status === "running" && !i.interrupted,
1237
+ role: "assistant"
1238
+ }),
1239
+ i.interrupted && i.status === "running" && /* @__PURE__ */ u("p", {
1240
+ className: "asui-interrupted",
1241
+ "data-testid": "interrupted-hint",
1242
+ children: "连接中断,正在续传…"
1243
+ }),
1244
+ i.error && /* @__PURE__ */ d("div", {
1245
+ className: "asui-error-wrap",
1246
+ children: [/* @__PURE__ */ u($, {
1247
+ message: i.error.message,
1248
+ stage: i.error.stage
1249
+ }), t && /* @__PURE__ */ d("button", {
1250
+ type: "button",
1251
+ className: "asui-inline-retry",
1252
+ onClick: t,
1253
+ children: [/* @__PURE__ */ u(J, {}), " 重试本轮"]
1254
+ })]
1255
+ })
1256
+ ]
1257
+ })]
1258
+ }), !s && /* @__PURE__ */ u("button", {
1259
+ type: "button",
1260
+ className: "asui-jump-bottom",
1261
+ onClick: c,
1262
+ "aria-label": "回到底部",
1263
+ children: /* @__PURE__ */ u(Fe, {})
1264
+ })]
1265
+ });
1266
+ }
1267
+ // src/lib/react/composer.tsx
1268
+ var We = 200;
1269
+ function Ge({ running: e, canRetry: t, placeholder: n = "发消息…", disabled: r = !1, onSend: a, onStop: c, onRetry: l }) {
1270
+ let [f, p] = s(""), m = o(null);
1271
+ i(() => {
1272
+ let e = m.current;
1273
+ e && (e.style.height = "auto", e.style.height = `${Math.min(e.scrollHeight, We)}px`);
1274
+ }, [f]);
1275
+ let h = () => {
1276
+ let t = f.trim();
1277
+ t === "" || e || r || (p(""), a(t));
1278
+ };
1279
+ return /* @__PURE__ */ d("div", {
1280
+ className: "asui-composer",
1281
+ children: [/* @__PURE__ */ d("div", {
1282
+ className: "asui-composer-box",
1283
+ children: [
1284
+ /* @__PURE__ */ u(X, { className: "asui-composer-spark" }),
1285
+ /* @__PURE__ */ u("textarea", {
1286
+ ref: m,
1287
+ className: "asui-composer-input",
1288
+ value: f,
1289
+ rows: 1,
1290
+ placeholder: n,
1291
+ disabled: r,
1292
+ onChange: (e) => p(e.target.value),
1293
+ onKeyDown: (e) => {
1294
+ e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing && (e.preventDefault(), h());
1295
+ },
1296
+ "aria-label": "输入消息"
1297
+ }),
1298
+ e ? /* @__PURE__ */ u("button", {
1299
+ type: "button",
1300
+ className: "asui-btn asui-btn--stop",
1301
+ onClick: c,
1302
+ title: "停止生成",
1303
+ "aria-label": "停止生成",
1304
+ children: /* @__PURE__ */ u(Me, {})
1305
+ }) : t ? /* @__PURE__ */ u("button", {
1306
+ type: "button",
1307
+ className: "asui-btn asui-btn--retry",
1308
+ onClick: l,
1309
+ title: "重试",
1310
+ "aria-label": "重试",
1311
+ children: /* @__PURE__ */ u(J, {})
1312
+ }) : /* @__PURE__ */ u("button", {
1313
+ type: "button",
1314
+ className: "asui-btn asui-btn--send",
1315
+ onClick: h,
1316
+ disabled: f.trim() === "" || r,
1317
+ title: "发送",
1318
+ "aria-label": "发送",
1319
+ children: /* @__PURE__ */ u(je, {})
1320
+ })
1321
+ ]
1322
+ }), /* @__PURE__ */ d("p", {
1323
+ className: "asui-composer-hint",
1324
+ children: [
1325
+ /* @__PURE__ */ u("kbd", { children: "Enter" }),
1326
+ " 发送 · ",
1327
+ /* @__PURE__ */ u("kbd", { children: "Shift" }),
1328
+ " + ",
1329
+ /* @__PURE__ */ u("kbd", { children: "Enter" }),
1330
+ " 换行"
1331
+ ]
1332
+ })]
1333
+ });
1334
+ }
1335
+ // src/lib/react/agent-chat.tsx
1336
+ var Ke = {
1337
+ idle: "就绪",
1338
+ connecting: "连接中",
1339
+ open: "生成中",
1340
+ reconnecting: "重连中",
1341
+ closed: "就绪",
1342
+ stopped: "已停止",
1343
+ error: "连接异常"
1344
+ };
1345
+ function qe({ store: e, title: t = "Agent 对话", subtitle: n, placeholder: r, suggestions: i = [], footer: a, emptyState: o, className: s }) {
1346
+ let c = ke(e), l = c.live?.status === "running", f = c.live?.status === "error" || c.status === "error" || c.messages.at(-1)?.status === "error", p = c.status === "error" ? "error" : c.status === "reconnecting" ? "warn" : l ? "busy" : "ok", m = c.status === "reconnecting" && c.reconnect ? ` · 第 ${c.reconnect.attempt} 次` : "";
1347
+ return /* @__PURE__ */ d("div", {
1348
+ className: s ? `asui-chat ${s}` : "asui-chat",
1349
+ children: [
1350
+ /* @__PURE__ */ d("header", {
1351
+ className: "asui-header",
1352
+ children: [/* @__PURE__ */ d("div", {
1353
+ className: "asui-brand",
1354
+ children: [/* @__PURE__ */ u("span", {
1355
+ className: "asui-brand-mark",
1356
+ children: /* @__PURE__ */ u(X, {
1357
+ width: 14,
1358
+ height: 14
1359
+ })
1360
+ }), /* @__PURE__ */ d("div", { children: [/* @__PURE__ */ u("h1", {
1361
+ className: "asui-title",
1362
+ children: t
1363
+ }), n && /* @__PURE__ */ u("p", {
1364
+ className: "asui-subtitle",
1365
+ children: n
1366
+ })] })]
1367
+ }), /* @__PURE__ */ d("span", {
1368
+ className: `asui-badge asui-badge--${p}`,
1369
+ "data-testid": "status-badge",
1370
+ children: [
1371
+ /* @__PURE__ */ u("i", {}),
1372
+ Ke[c.status],
1373
+ m
1374
+ ]
1375
+ })]
1376
+ }),
1377
+ /* @__PURE__ */ u(Ue, {
1378
+ snapshot: c,
1379
+ onRetry: e.retry,
1380
+ emptyState: o ?? /* @__PURE__ */ d("div", {
1381
+ className: "asui-empty-inner",
1382
+ children: [
1383
+ /* @__PURE__ */ u(X, {
1384
+ width: 22,
1385
+ height: 22
1386
+ }),
1387
+ /* @__PURE__ */ u("h2", { children: "问点需要查证的问题" }),
1388
+ /* @__PURE__ */ u("p", { children: "工具调用会以卡片形式展开,失败可以重试,断线会自动续传。" }),
1389
+ i.length > 0 && /* @__PURE__ */ u("div", {
1390
+ className: "asui-suggestions",
1391
+ children: i.map((t) => /* @__PURE__ */ u("button", {
1392
+ type: "button",
1393
+ className: "asui-suggestion",
1394
+ onClick: () => e.send(t),
1395
+ children: t
1396
+ }, t))
1397
+ })
1398
+ ]
1399
+ })
1400
+ }),
1401
+ /* @__PURE__ */ u(Ge, {
1402
+ running: l === !0,
1403
+ canRetry: f === !0,
1404
+ placeholder: r ?? "发消息…",
1405
+ onSend: e.send,
1406
+ onStop: e.stop,
1407
+ onRetry: e.retry
1408
+ }),
1409
+ a && /* @__PURE__ */ u("div", {
1410
+ className: "asui-footer",
1411
+ children: a
1412
+ })
1413
+ ]
1414
+ });
1415
+ }
1416
+ export { f as AGENT_EVENT_TYPES, qe as AgentChat, Ge as Composer, v as DEFAULT_BACKOFF_BASE_MS, y as DEFAULT_BACKOFF_FACTOR, b as DEFAULT_BACKOFF_MAX_MS, $ as ErrorNote, Oe as MarkdownBlockView, Ae as MarkdownStream, Q as MessageBody, Ue as MessageList, ze as ToolCallCard, ue as appendUserMessage, j as applySseStatus, Te as clearBlockCache, re as computeBackoff, de as createAgentStream, pe as createHttpTransport, ge as createOpenAIStreamTranslator, he as createScriptedTransport, x as createSseClient, ie as decodeAgentEvent, F as defaultScheduler, g as formatSseFrame, N as immediateScheduler, T as initialLiveTurn, E as initialSnapshot, C as isAgentEventType, _ as isNewerEventId, U as isSafeHref, V as listItemText, W as parseInline, G as parseInlineLines, h as parseSseChunk, m as parseSseFrame, P as rafScheduler, k as reduceAgentEvent, we as renderBlock, w as repairPartialJson, M as settleOrphanLiveTurn, ne as shouldRetryStatus, B as splitBlocks, A as stopLiveTurn, I as toWireHistory, ke as useAgentStream, He as useStickToBottom };
1417
+
1418
+ //# sourceMappingURL=agent-stream-ui.js.map