assistant-stream 0.0.0 → 0.0.3

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/dist/index.js ADDED
@@ -0,0 +1,1012 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ AssistantStream: () => AssistantStream,
34
+ DataStreamDecoder: () => DataStreamDecoder,
35
+ DataStreamEncoder: () => DataStreamEncoder,
36
+ PlainTextDecoder: () => PlainTextDecoder,
37
+ PlainTextEncoder: () => PlainTextEncoder,
38
+ createAssistantRun: () => createAssistantRun,
39
+ createRun: () => createAssistantRun,
40
+ toAssistantMessageStream: () => toAssistantMessageStream
41
+ });
42
+ module.exports = __toCommonJS(src_exports);
43
+
44
+ // src/core/AssistantStream.ts
45
+ var AssistantStream = class _AssistantStream {
46
+ constructor(readable) {
47
+ this.readable = readable;
48
+ this.readable = readable;
49
+ }
50
+ toResponse(transformer) {
51
+ return new Response(this.toByteStream(transformer));
52
+ }
53
+ static fromResponse(response, transformer) {
54
+ return _AssistantStream.fromByteStream(response.body, transformer);
55
+ }
56
+ toByteStream(transformer) {
57
+ return this.readable.pipeThrough(transformer);
58
+ }
59
+ static fromByteStream(readable, transformer) {
60
+ return new _AssistantStream(readable.pipeThrough(transformer));
61
+ }
62
+ tee() {
63
+ const [readable1, readable2] = this.readable.tee();
64
+ return [new _AssistantStream(readable1), new _AssistantStream(readable2)];
65
+ }
66
+ };
67
+
68
+ // src/core/utils/generateId.tsx
69
+ var import_non_secure = require("nanoid/non-secure");
70
+ var generateId = (0, import_non_secure.customAlphabet)(
71
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
72
+ 7
73
+ );
74
+
75
+ // src/core/modules/text.ts
76
+ var TextStreamControllerImpl = class {
77
+ _controller;
78
+ constructor(controller) {
79
+ this._controller = controller;
80
+ }
81
+ append(textDelta) {
82
+ this._controller.enqueue({
83
+ type: "text-delta",
84
+ textDelta
85
+ });
86
+ return this;
87
+ }
88
+ close() {
89
+ this._controller.close();
90
+ }
91
+ };
92
+ var createTextStream = (readable) => {
93
+ return new AssistantStream(
94
+ new ReadableStream({
95
+ start(c) {
96
+ return readable.start?.(new TextStreamControllerImpl(c));
97
+ },
98
+ pull(c) {
99
+ return readable.pull?.(new TextStreamControllerImpl(c));
100
+ },
101
+ cancel(c) {
102
+ return readable.cancel?.(c);
103
+ }
104
+ })
105
+ );
106
+ };
107
+
108
+ // src/core/modules/tool-call.ts
109
+ var ToolCallStreamControllerImpl = class {
110
+ constructor(_controller, _options) {
111
+ this._controller = _controller;
112
+ this._options = _options;
113
+ this._controller.enqueue({
114
+ type: "tool-call-begin",
115
+ toolCallId: this._options.toolCallId,
116
+ toolName: this._options.toolName
117
+ });
118
+ const stream = createTextStream({
119
+ start: (c) => {
120
+ this._argsTextController = c;
121
+ }
122
+ });
123
+ stream.readable.pipeTo(
124
+ new WritableStream({
125
+ write: (chunk) => {
126
+ if (chunk.type !== "text-delta")
127
+ throw new Error("Unexpected chunk type");
128
+ this._controller.enqueue({
129
+ type: "tool-call-delta",
130
+ toolCallId: this._options.toolCallId,
131
+ argsTextDelta: chunk.textDelta
132
+ });
133
+ }
134
+ })
135
+ );
136
+ }
137
+ get toolCallId() {
138
+ return this._options.toolCallId;
139
+ }
140
+ get toolName() {
141
+ return this._options.toolName;
142
+ }
143
+ get argsText() {
144
+ return this._argsTextController;
145
+ }
146
+ _argsTextController;
147
+ setResult(result) {
148
+ this._controller.enqueue({
149
+ type: "tool-result",
150
+ toolCallId: this._options.toolCallId,
151
+ result
152
+ });
153
+ }
154
+ close() {
155
+ this._controller.close();
156
+ }
157
+ };
158
+ var createToolCallStream = (readable) => {
159
+ const options = {
160
+ toolCallId: readable.toolCallId,
161
+ toolName: readable.toolName
162
+ };
163
+ return new AssistantStream(
164
+ new ReadableStream({
165
+ start(c) {
166
+ return readable.start?.(new ToolCallStreamControllerImpl(c, options));
167
+ },
168
+ pull(c) {
169
+ return readable.pull?.(new ToolCallStreamControllerImpl(c, options));
170
+ },
171
+ cancel(c) {
172
+ return readable.cancel?.(c);
173
+ }
174
+ })
175
+ );
176
+ };
177
+
178
+ // src/core/modules/runs.ts
179
+ var promiseWithResolvers = () => {
180
+ let resolve;
181
+ let reject;
182
+ const promise = new Promise((res, rej) => {
183
+ resolve = res;
184
+ reject = rej;
185
+ });
186
+ return { promise, resolve, reject };
187
+ };
188
+ var createMergeStream = () => {
189
+ const list = [];
190
+ let sealed = false;
191
+ let controller;
192
+ let currentPull;
193
+ const handlePull = (item) => {
194
+ if (!item.promise) {
195
+ item.promise = item.reader.read().then(({ done, value }) => {
196
+ item.promise = void 0;
197
+ if (done) {
198
+ list.splice(list.indexOf(item), 1);
199
+ if (sealed && list.length === 0) {
200
+ controller.close();
201
+ }
202
+ } else {
203
+ controller.enqueue(value);
204
+ }
205
+ currentPull?.resolve();
206
+ currentPull = void 0;
207
+ }).catch((e) => {
208
+ list.forEach((item2) => {
209
+ item2.reader.cancel();
210
+ });
211
+ list.length = 0;
212
+ controller.error(e);
213
+ currentPull?.reject(e);
214
+ currentPull = void 0;
215
+ });
216
+ }
217
+ };
218
+ const readable = new ReadableStream({
219
+ start(c) {
220
+ controller = c;
221
+ },
222
+ async pull() {
223
+ list.map((item) => {
224
+ handlePull(item);
225
+ return item.promise;
226
+ });
227
+ currentPull = promiseWithResolvers();
228
+ return currentPull.promise;
229
+ },
230
+ cancel() {
231
+ list.forEach((item) => {
232
+ item.reader.cancel();
233
+ });
234
+ list.length = 0;
235
+ }
236
+ });
237
+ return {
238
+ stream: readable,
239
+ seal() {
240
+ sealed = true;
241
+ if (list.length === 0) controller.close();
242
+ },
243
+ addStream(stream) {
244
+ if (sealed)
245
+ throw new Error(
246
+ "Cannot add streams after the run callback has settled."
247
+ );
248
+ const item = { reader: stream.readable.getReader() };
249
+ list.push(item);
250
+ if (list.length === 1) {
251
+ handlePull(item);
252
+ }
253
+ }
254
+ };
255
+ };
256
+ var RunControllerImpl = class {
257
+ _merge = createMergeStream();
258
+ _textPartController;
259
+ getReadable() {
260
+ return this._merge.stream;
261
+ }
262
+ close() {
263
+ this._merge.seal();
264
+ this._textPartController?.close();
265
+ }
266
+ appendStep(stream) {
267
+ this._merge.addStream(stream);
268
+ }
269
+ appendText(textDelta) {
270
+ if (!this._textPartController) {
271
+ this._textPartController = this.addTextPart();
272
+ }
273
+ this._textPartController.append(textDelta);
274
+ }
275
+ addTextPart() {
276
+ let controller;
277
+ const textStream = createTextStream({
278
+ start(c) {
279
+ controller = c;
280
+ }
281
+ });
282
+ this.appendStep(textStream);
283
+ return controller;
284
+ }
285
+ addToolCallPart(options) {
286
+ const opt = typeof options === "string" ? { toolName: options, toolCallId: generateId() } : options;
287
+ let controller;
288
+ const toolCallStream = createToolCallStream({
289
+ toolCallId: opt.toolCallId,
290
+ toolName: opt.toolName,
291
+ start(c) {
292
+ controller = c;
293
+ }
294
+ });
295
+ this.appendStep(toolCallStream);
296
+ return controller;
297
+ }
298
+ };
299
+ function createAssistantRun(callback) {
300
+ const controller = new RunControllerImpl();
301
+ const promiseOrVoid = callback(controller);
302
+ if (promiseOrVoid instanceof Promise) {
303
+ promiseOrVoid.finally(() => controller.close());
304
+ } else {
305
+ controller.close();
306
+ }
307
+ return new AssistantStream(controller.getReadable());
308
+ }
309
+
310
+ // src/core/utils/PipeableTransformStream.ts
311
+ var PipeableTransformStream = class extends TransformStream {
312
+ constructor(transform) {
313
+ super();
314
+ const readable = transform(super.readable);
315
+ Object.defineProperty(this, "readable", {
316
+ value: readable,
317
+ writable: false
318
+ });
319
+ }
320
+ };
321
+
322
+ // src/core/serialization/DataStream.ts
323
+ var DataStreamEncoder = class {
324
+ _transformStream;
325
+ get writable() {
326
+ return this._transformStream.writable;
327
+ }
328
+ get readable() {
329
+ return this._transformStream.readable;
330
+ }
331
+ constructor() {
332
+ this._transformStream = new PipeableTransformStream((readable) => {
333
+ const transform = new TransformStream({
334
+ transform(chunk, controller) {
335
+ const type = chunk.type;
336
+ switch (type) {
337
+ case "text-delta":
338
+ controller.enqueue("0:" + JSON.stringify(chunk.textDelta) + "\n");
339
+ break;
340
+ case "tool-call-begin":
341
+ controller.enqueue(
342
+ "b:" + JSON.stringify({
343
+ toolCallId: chunk.toolCallId,
344
+ toolName: chunk.toolName
345
+ }) + "\n"
346
+ );
347
+ break;
348
+ case "tool-call-delta":
349
+ controller.enqueue(
350
+ "c:" + JSON.stringify({
351
+ toolCallId: chunk.toolCallId,
352
+ argsTextDelta: chunk.argsTextDelta
353
+ }) + "\n"
354
+ );
355
+ break;
356
+ case "tool-result":
357
+ controller.enqueue(
358
+ "a:" + JSON.stringify({
359
+ toolCallId: chunk.toolCallId,
360
+ result: chunk.result
361
+ }) + "\n"
362
+ );
363
+ break;
364
+ default:
365
+ const exhaustiveCheck = type;
366
+ throw new Error(`unsupported chunk type: ${exhaustiveCheck}`);
367
+ }
368
+ }
369
+ });
370
+ return readable.pipeThrough(transform).pipeThrough(new TextEncoderStream());
371
+ });
372
+ }
373
+ };
374
+ var decodeStreamPart = (part) => {
375
+ const index = part.indexOf(":");
376
+ if (index === -1) throw new Error("Invalid stream part");
377
+ return {
378
+ type: part.slice(0, index),
379
+ value: JSON.parse(part.slice(index + 1))
380
+ };
381
+ };
382
+ var DataStreamDecoder = class {
383
+ _transformStream;
384
+ get writable() {
385
+ return this._transformStream.writable;
386
+ }
387
+ get readable() {
388
+ return this._transformStream.readable;
389
+ }
390
+ constructor() {
391
+ this._transformStream = new PipeableTransformStream((readable) => {
392
+ const transform = new TransformStream({
393
+ transform(chunk, controller) {
394
+ const { type, value } = decodeStreamPart(chunk);
395
+ switch (type) {
396
+ case "0":
397
+ controller.enqueue({
398
+ type: "text-delta",
399
+ textDelta: value
400
+ });
401
+ break;
402
+ case "b": {
403
+ const { toolCallId, toolName } = value;
404
+ controller.enqueue({
405
+ type: "tool-call-begin",
406
+ toolCallId,
407
+ toolName
408
+ });
409
+ break;
410
+ }
411
+ case "c": {
412
+ const { toolCallId, argsTextDelta } = value;
413
+ controller.enqueue({
414
+ type: "tool-call-delta",
415
+ toolCallId,
416
+ argsTextDelta
417
+ });
418
+ break;
419
+ }
420
+ case "a": {
421
+ const { toolCallId, result } = value;
422
+ controller.enqueue({
423
+ type: "tool-result",
424
+ toolCallId,
425
+ result
426
+ });
427
+ break;
428
+ }
429
+ default:
430
+ const exhaustiveCheck = type;
431
+ throw new Error(`unsupported chunk type: ${exhaustiveCheck}`);
432
+ }
433
+ }
434
+ });
435
+ return readable.pipeThrough(new TextDecoderStream()).pipeThrough(new ChunkByLineStream()).pipeThrough(transform);
436
+ });
437
+ }
438
+ };
439
+ var ChunkByLineStream = class extends TransformStream {
440
+ buffer = "";
441
+ constructor() {
442
+ super({
443
+ transform: (chunk, controller) => {
444
+ this.buffer += chunk;
445
+ const lines = this.buffer.split("\n");
446
+ for (let i = 0; i < lines.length - 1; i++) {
447
+ controller.enqueue(lines[i]);
448
+ }
449
+ this.buffer = lines[lines.length - 1];
450
+ },
451
+ flush: (controller) => {
452
+ if (this.buffer) {
453
+ controller.enqueue(this.buffer);
454
+ }
455
+ }
456
+ });
457
+ }
458
+ };
459
+
460
+ // src/core/serialization/PlainText.ts
461
+ var PlainTextEncoder = class {
462
+ _transformStream;
463
+ get writable() {
464
+ return this._transformStream.writable;
465
+ }
466
+ get readable() {
467
+ return this._transformStream.readable;
468
+ }
469
+ constructor() {
470
+ this._transformStream = new PipeableTransformStream((readable) => {
471
+ const transform = new TransformStream({
472
+ transform(chunk, controller) {
473
+ const type = chunk.type;
474
+ switch (type) {
475
+ case "text-delta":
476
+ controller.enqueue(chunk.textDelta);
477
+ break;
478
+ case "tool-call-begin":
479
+ case "tool-call-delta":
480
+ case "tool-result":
481
+ throw new Error(
482
+ `tool-call-begin and tool-call-delta are not supported in plain text serialization`
483
+ );
484
+ default:
485
+ const exhaustiveCheck = type;
486
+ throw new Error(`unsupported chunk type: ${exhaustiveCheck}`);
487
+ }
488
+ }
489
+ });
490
+ return readable.pipeThrough(transform).pipeThrough(new TextEncoderStream());
491
+ });
492
+ }
493
+ };
494
+ var PlainTextDecoder = class {
495
+ _transformStream;
496
+ get writable() {
497
+ return this._transformStream.writable;
498
+ }
499
+ get readable() {
500
+ return this._transformStream.readable;
501
+ }
502
+ constructor() {
503
+ this._transformStream = new PipeableTransformStream((readable) => {
504
+ const transform = new TransformStream({
505
+ transform(chunk, controller) {
506
+ controller.enqueue({
507
+ type: "text-delta",
508
+ textDelta: chunk
509
+ });
510
+ }
511
+ });
512
+ return readable.pipeThrough(new TextDecoderStream()).pipeThrough(transform);
513
+ });
514
+ }
515
+ };
516
+
517
+ // src/core/accumulators/partial-json/parse-partial-json.ts
518
+ var import_secure_json_parse = __toESM(require("secure-json-parse"));
519
+
520
+ // src/core/accumulators/partial-json/fix-json.ts
521
+ function fixJson(input) {
522
+ const stack = ["ROOT"];
523
+ let lastValidIndex = -1;
524
+ let literalStart = null;
525
+ function processValueStart(char, i, swapState) {
526
+ {
527
+ switch (char) {
528
+ case '"': {
529
+ lastValidIndex = i;
530
+ stack.pop();
531
+ stack.push(swapState);
532
+ stack.push("INSIDE_STRING");
533
+ break;
534
+ }
535
+ case "f":
536
+ case "t":
537
+ case "n": {
538
+ lastValidIndex = i;
539
+ literalStart = i;
540
+ stack.pop();
541
+ stack.push(swapState);
542
+ stack.push("INSIDE_LITERAL");
543
+ break;
544
+ }
545
+ case "-": {
546
+ stack.pop();
547
+ stack.push(swapState);
548
+ stack.push("INSIDE_NUMBER");
549
+ break;
550
+ }
551
+ case "0":
552
+ case "1":
553
+ case "2":
554
+ case "3":
555
+ case "4":
556
+ case "5":
557
+ case "6":
558
+ case "7":
559
+ case "8":
560
+ case "9": {
561
+ lastValidIndex = i;
562
+ stack.pop();
563
+ stack.push(swapState);
564
+ stack.push("INSIDE_NUMBER");
565
+ break;
566
+ }
567
+ case "{": {
568
+ lastValidIndex = i;
569
+ stack.pop();
570
+ stack.push(swapState);
571
+ stack.push("INSIDE_OBJECT_START");
572
+ break;
573
+ }
574
+ case "[": {
575
+ lastValidIndex = i;
576
+ stack.pop();
577
+ stack.push(swapState);
578
+ stack.push("INSIDE_ARRAY_START");
579
+ break;
580
+ }
581
+ }
582
+ }
583
+ }
584
+ function processAfterObjectValue(char, i) {
585
+ switch (char) {
586
+ case ",": {
587
+ stack.pop();
588
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
589
+ break;
590
+ }
591
+ case "}": {
592
+ lastValidIndex = i;
593
+ stack.pop();
594
+ break;
595
+ }
596
+ }
597
+ }
598
+ function processAfterArrayValue(char, i) {
599
+ switch (char) {
600
+ case ",": {
601
+ stack.pop();
602
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
603
+ break;
604
+ }
605
+ case "]": {
606
+ lastValidIndex = i;
607
+ stack.pop();
608
+ break;
609
+ }
610
+ }
611
+ }
612
+ for (let i = 0; i < input.length; i++) {
613
+ const char = input[i];
614
+ const currentState = stack[stack.length - 1];
615
+ switch (currentState) {
616
+ case "ROOT":
617
+ processValueStart(char, i, "FINISH");
618
+ break;
619
+ case "INSIDE_OBJECT_START": {
620
+ switch (char) {
621
+ case '"': {
622
+ stack.pop();
623
+ stack.push("INSIDE_OBJECT_KEY");
624
+ break;
625
+ }
626
+ case "}": {
627
+ lastValidIndex = i;
628
+ stack.pop();
629
+ break;
630
+ }
631
+ }
632
+ break;
633
+ }
634
+ case "INSIDE_OBJECT_AFTER_COMMA": {
635
+ switch (char) {
636
+ case '"': {
637
+ stack.pop();
638
+ stack.push("INSIDE_OBJECT_KEY");
639
+ break;
640
+ }
641
+ }
642
+ break;
643
+ }
644
+ case "INSIDE_OBJECT_KEY": {
645
+ switch (char) {
646
+ case '"': {
647
+ stack.pop();
648
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
649
+ break;
650
+ }
651
+ }
652
+ break;
653
+ }
654
+ case "INSIDE_OBJECT_AFTER_KEY": {
655
+ switch (char) {
656
+ case ":": {
657
+ stack.pop();
658
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
659
+ break;
660
+ }
661
+ }
662
+ break;
663
+ }
664
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
665
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
666
+ break;
667
+ }
668
+ case "INSIDE_OBJECT_AFTER_VALUE": {
669
+ processAfterObjectValue(char, i);
670
+ break;
671
+ }
672
+ case "INSIDE_STRING": {
673
+ switch (char) {
674
+ case '"': {
675
+ stack.pop();
676
+ lastValidIndex = i;
677
+ break;
678
+ }
679
+ case "\\": {
680
+ stack.push("INSIDE_STRING_ESCAPE");
681
+ break;
682
+ }
683
+ default: {
684
+ lastValidIndex = i;
685
+ }
686
+ }
687
+ break;
688
+ }
689
+ case "INSIDE_ARRAY_START": {
690
+ switch (char) {
691
+ case "]": {
692
+ lastValidIndex = i;
693
+ stack.pop();
694
+ break;
695
+ }
696
+ default: {
697
+ lastValidIndex = i;
698
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
699
+ break;
700
+ }
701
+ }
702
+ break;
703
+ }
704
+ case "INSIDE_ARRAY_AFTER_VALUE": {
705
+ switch (char) {
706
+ case ",": {
707
+ stack.pop();
708
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
709
+ break;
710
+ }
711
+ case "]": {
712
+ lastValidIndex = i;
713
+ stack.pop();
714
+ break;
715
+ }
716
+ default: {
717
+ lastValidIndex = i;
718
+ break;
719
+ }
720
+ }
721
+ break;
722
+ }
723
+ case "INSIDE_ARRAY_AFTER_COMMA": {
724
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
725
+ break;
726
+ }
727
+ case "INSIDE_STRING_ESCAPE": {
728
+ stack.pop();
729
+ lastValidIndex = i;
730
+ break;
731
+ }
732
+ case "INSIDE_NUMBER": {
733
+ switch (char) {
734
+ case "0":
735
+ case "1":
736
+ case "2":
737
+ case "3":
738
+ case "4":
739
+ case "5":
740
+ case "6":
741
+ case "7":
742
+ case "8":
743
+ case "9": {
744
+ lastValidIndex = i;
745
+ break;
746
+ }
747
+ case "e":
748
+ case "E":
749
+ case "-":
750
+ case ".": {
751
+ break;
752
+ }
753
+ case ",": {
754
+ stack.pop();
755
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
756
+ processAfterArrayValue(char, i);
757
+ }
758
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
759
+ processAfterObjectValue(char, i);
760
+ }
761
+ break;
762
+ }
763
+ case "}": {
764
+ stack.pop();
765
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
766
+ processAfterObjectValue(char, i);
767
+ }
768
+ break;
769
+ }
770
+ case "]": {
771
+ stack.pop();
772
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
773
+ processAfterArrayValue(char, i);
774
+ }
775
+ break;
776
+ }
777
+ default: {
778
+ stack.pop();
779
+ break;
780
+ }
781
+ }
782
+ break;
783
+ }
784
+ case "INSIDE_LITERAL": {
785
+ const partialLiteral = input.substring(literalStart, i + 1);
786
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
787
+ stack.pop();
788
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
789
+ processAfterObjectValue(char, i);
790
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
791
+ processAfterArrayValue(char, i);
792
+ }
793
+ } else {
794
+ lastValidIndex = i;
795
+ }
796
+ break;
797
+ }
798
+ }
799
+ }
800
+ let result = input.slice(0, lastValidIndex + 1);
801
+ for (let i = stack.length - 1; i >= 0; i--) {
802
+ const state = stack[i];
803
+ switch (state) {
804
+ case "INSIDE_STRING": {
805
+ result += '"';
806
+ break;
807
+ }
808
+ case "INSIDE_OBJECT_KEY":
809
+ case "INSIDE_OBJECT_AFTER_KEY":
810
+ case "INSIDE_OBJECT_AFTER_COMMA":
811
+ case "INSIDE_OBJECT_START":
812
+ case "INSIDE_OBJECT_BEFORE_VALUE":
813
+ case "INSIDE_OBJECT_AFTER_VALUE": {
814
+ result += "}";
815
+ break;
816
+ }
817
+ case "INSIDE_ARRAY_START":
818
+ case "INSIDE_ARRAY_AFTER_COMMA":
819
+ case "INSIDE_ARRAY_AFTER_VALUE": {
820
+ result += "]";
821
+ break;
822
+ }
823
+ case "INSIDE_LITERAL": {
824
+ const partialLiteral = input.substring(literalStart, input.length);
825
+ if ("true".startsWith(partialLiteral)) {
826
+ result += "true".slice(partialLiteral.length);
827
+ } else if ("false".startsWith(partialLiteral)) {
828
+ result += "false".slice(partialLiteral.length);
829
+ } else if ("null".startsWith(partialLiteral)) {
830
+ result += "null".slice(partialLiteral.length);
831
+ }
832
+ }
833
+ }
834
+ }
835
+ return result;
836
+ }
837
+
838
+ // src/core/accumulators/partial-json/parse-partial-json.ts
839
+ var parsePartialJson = (json) => {
840
+ try {
841
+ return import_secure_json_parse.default.parse(json);
842
+ } catch {
843
+ try {
844
+ return import_secure_json_parse.default.parse(fixJson(json));
845
+ } catch {
846
+ return void 0;
847
+ }
848
+ }
849
+ };
850
+
851
+ // src/core/accumulators/assistant-message.ts
852
+ function createAsyncIterableStream(source, transform) {
853
+ const transformedStream = source.pipeThrough(transform);
854
+ transformedStream[Symbol.asyncIterator] = () => {
855
+ const reader = transformedStream.getReader();
856
+ return {
857
+ async next() {
858
+ const { done, value } = await reader.read();
859
+ return done ? { done: true, value: void 0 } : { done: false, value };
860
+ }
861
+ };
862
+ };
863
+ return transformedStream;
864
+ }
865
+ var toAssistantMessageStream = (stream) => {
866
+ let message = {
867
+ role: "assistant",
868
+ content: [],
869
+ status: { type: "running" },
870
+ metadata: {
871
+ steps: [],
872
+ custom: {}
873
+ }
874
+ };
875
+ const transformer = new TransformStream({
876
+ transform(chunk, controller) {
877
+ const { type } = chunk;
878
+ switch (type) {
879
+ case "text-delta": {
880
+ message = appendOrUpdateText(message, chunk.textDelta);
881
+ controller.enqueue(message);
882
+ break;
883
+ }
884
+ case "tool-call-begin": {
885
+ const { toolCallId, toolName } = chunk;
886
+ message = appendToolCall(message, toolCallId, toolName);
887
+ controller.enqueue(message);
888
+ break;
889
+ }
890
+ case "tool-call-delta": {
891
+ const { toolCallId, argsTextDelta } = chunk;
892
+ message = appendToolArgsTextDelta(message, toolCallId, argsTextDelta);
893
+ controller.enqueue(message);
894
+ break;
895
+ }
896
+ case "tool-result": {
897
+ const { toolCallId, result } = chunk;
898
+ message = setToolResult(message, toolCallId, result);
899
+ controller.enqueue(message);
900
+ break;
901
+ }
902
+ }
903
+ },
904
+ flush(controller) {
905
+ message = appendOrUpdateFinish(message);
906
+ controller.enqueue(message);
907
+ }
908
+ });
909
+ return createAsyncIterableStream(stream.readable, transformer);
910
+ };
911
+ var appendOrUpdateText = (message, textDelta) => {
912
+ let contentParts = message.content ?? [];
913
+ let contentPart = message.content?.at(-1);
914
+ if (contentPart?.type !== "text") {
915
+ contentPart = {
916
+ type: "text",
917
+ text: textDelta,
918
+ status: { type: "running" }
919
+ };
920
+ } else {
921
+ contentParts = contentParts.slice(0, -1);
922
+ contentPart = {
923
+ type: "text",
924
+ text: contentPart.text + textDelta,
925
+ status: { type: "running" }
926
+ };
927
+ }
928
+ return {
929
+ ...message,
930
+ content: contentParts.concat([contentPart])
931
+ };
932
+ };
933
+ var appendToolCall = (message, toolCallId, toolName) => {
934
+ return {
935
+ ...message,
936
+ content: [
937
+ ...message.content,
938
+ {
939
+ type: "tool-call",
940
+ toolCallId,
941
+ toolName,
942
+ argsText: "",
943
+ args: {},
944
+ status: { type: "running", isArgsComplete: false }
945
+ }
946
+ ]
947
+ };
948
+ };
949
+ var appendToolArgsTextDelta = (message, toolCallId, argsTextDelta) => {
950
+ const contentPartIdx = message.content.findIndex(
951
+ (part) => part.type === "tool-call" && part.toolCallId === toolCallId
952
+ );
953
+ if (contentPartIdx === -1)
954
+ throw new Error(
955
+ `Received tool call delta for unknown tool call "${toolCallId}".`
956
+ );
957
+ const contentPart = message.content[contentPartIdx];
958
+ const newArgsText = contentPart.argsText + argsTextDelta;
959
+ return {
960
+ ...message,
961
+ content: [
962
+ ...message.content.slice(0, contentPartIdx),
963
+ {
964
+ ...contentPart,
965
+ argsText: newArgsText,
966
+ args: parsePartialJson(newArgsText)
967
+ },
968
+ ...message.content.slice(contentPartIdx + 1)
969
+ ]
970
+ };
971
+ };
972
+ var setToolResult = (message, toolCallId, result) => {
973
+ let found = false;
974
+ const newContentParts = message.content?.map((part) => {
975
+ if (part.type !== "tool-call" || part.toolCallId !== toolCallId)
976
+ return part;
977
+ found = true;
978
+ return {
979
+ ...part,
980
+ result
981
+ };
982
+ });
983
+ if (!found)
984
+ throw new Error(
985
+ `Received tool result for unknown tool call "${toolCallId}". This is likely an internal bug in assistant-ui.`
986
+ );
987
+ return {
988
+ ...message,
989
+ content: newContentParts
990
+ };
991
+ };
992
+ var appendOrUpdateFinish = (message) => {
993
+ return {
994
+ ...message,
995
+ status: {
996
+ type: "complete",
997
+ reason: "unknown"
998
+ }
999
+ };
1000
+ };
1001
+ // Annotate the CommonJS export names for ESM import in node:
1002
+ 0 && (module.exports = {
1003
+ AssistantStream,
1004
+ DataStreamDecoder,
1005
+ DataStreamEncoder,
1006
+ PlainTextDecoder,
1007
+ PlainTextEncoder,
1008
+ createAssistantRun,
1009
+ createRun,
1010
+ toAssistantMessageStream
1011
+ });
1012
+ //# sourceMappingURL=index.js.map