@mastra/client-js 1.0.0-beta.10 → 1.0.0-beta.13

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.cjs CHANGED
@@ -1,13 +1,1068 @@
1
1
  'use strict';
2
2
 
3
- var uiUtils = require('@ai-sdk/ui-utils');
4
3
  var uuid = require('@lukeed/uuid');
5
4
  var error = require('@mastra/core/error');
6
5
  var requestContext = require('@mastra/core/request-context');
7
6
  var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
8
7
  var zodToJson = require('@mastra/schema-compat/zod-to-json');
9
8
 
10
- // src/resources/agent.ts
9
+ var __create = Object.create;
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __getProtoOf = Object.getPrototypeOf;
14
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __commonJS = (cb, mod) => function __require() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
32
+ mod
33
+ ));
34
+
35
+ // ../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js
36
+ var require_secure_json_parse = __commonJS({
37
+ "../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports, module) {
38
+ var hasBuffer = typeof Buffer !== "undefined";
39
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
40
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
41
+ function _parse(text, reviver, options) {
42
+ if (options == null) {
43
+ if (reviver !== null && typeof reviver === "object") {
44
+ options = reviver;
45
+ reviver = void 0;
46
+ }
47
+ }
48
+ if (hasBuffer && Buffer.isBuffer(text)) {
49
+ text = text.toString();
50
+ }
51
+ if (text && text.charCodeAt(0) === 65279) {
52
+ text = text.slice(1);
53
+ }
54
+ const obj = JSON.parse(text, reviver);
55
+ if (obj === null || typeof obj !== "object") {
56
+ return obj;
57
+ }
58
+ const protoAction = options && options.protoAction || "error";
59
+ const constructorAction = options && options.constructorAction || "error";
60
+ if (protoAction === "ignore" && constructorAction === "ignore") {
61
+ return obj;
62
+ }
63
+ if (protoAction !== "ignore" && constructorAction !== "ignore") {
64
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
65
+ return obj;
66
+ }
67
+ } else if (protoAction !== "ignore" && constructorAction === "ignore") {
68
+ if (suspectProtoRx.test(text) === false) {
69
+ return obj;
70
+ }
71
+ } else {
72
+ if (suspectConstructorRx.test(text) === false) {
73
+ return obj;
74
+ }
75
+ }
76
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
77
+ }
78
+ function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
79
+ let next = [obj];
80
+ while (next.length) {
81
+ const nodes = next;
82
+ next = [];
83
+ for (const node of nodes) {
84
+ if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
85
+ if (safe === true) {
86
+ return null;
87
+ } else if (protoAction === "error") {
88
+ throw new SyntaxError("Object contains forbidden prototype property");
89
+ }
90
+ delete node.__proto__;
91
+ }
92
+ if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
93
+ if (safe === true) {
94
+ return null;
95
+ } else if (constructorAction === "error") {
96
+ throw new SyntaxError("Object contains forbidden prototype property");
97
+ }
98
+ delete node.constructor;
99
+ }
100
+ for (const key in node) {
101
+ const value = node[key];
102
+ if (value && typeof value === "object") {
103
+ next.push(value);
104
+ }
105
+ }
106
+ }
107
+ }
108
+ return obj;
109
+ }
110
+ function parse(text, reviver, options) {
111
+ const stackTraceLimit = Error.stackTraceLimit;
112
+ Error.stackTraceLimit = 0;
113
+ try {
114
+ return _parse(text, reviver, options);
115
+ } finally {
116
+ Error.stackTraceLimit = stackTraceLimit;
117
+ }
118
+ }
119
+ function safeParse(text, reviver) {
120
+ const stackTraceLimit = Error.stackTraceLimit;
121
+ Error.stackTraceLimit = 0;
122
+ try {
123
+ return _parse(text, reviver, { safe: true });
124
+ } catch (_e) {
125
+ return null;
126
+ } finally {
127
+ Error.stackTraceLimit = stackTraceLimit;
128
+ }
129
+ }
130
+ module.exports = parse;
131
+ module.exports.default = parse;
132
+ module.exports.parse = parse;
133
+ module.exports.safeParse = safeParse;
134
+ module.exports.scan = filter;
135
+ }
136
+ });
137
+
138
+ // ../../node_modules/.pnpm/@ai-sdk+provider@1.1.3/node_modules/@ai-sdk/provider/dist/index.mjs
139
+ var marker = "vercel.ai.error";
140
+ var symbol = Symbol.for(marker);
141
+ var _a;
142
+ var _AISDKError = class _AISDKError2 extends Error {
143
+ /**
144
+ * Creates an AI SDK Error.
145
+ *
146
+ * @param {Object} params - The parameters for creating the error.
147
+ * @param {string} params.name - The name of the error.
148
+ * @param {string} params.message - The error message.
149
+ * @param {unknown} [params.cause] - The underlying cause of the error.
150
+ */
151
+ constructor({
152
+ name: name14,
153
+ message,
154
+ cause
155
+ }) {
156
+ super(message);
157
+ this[_a] = true;
158
+ this.name = name14;
159
+ this.cause = cause;
160
+ }
161
+ /**
162
+ * Checks if the given error is an AI SDK Error.
163
+ * @param {unknown} error - The error to check.
164
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
165
+ */
166
+ static isInstance(error) {
167
+ return _AISDKError2.hasMarker(error, marker);
168
+ }
169
+ static hasMarker(error, marker15) {
170
+ const markerSymbol = Symbol.for(marker15);
171
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
172
+ }
173
+ };
174
+ _a = symbol;
175
+ var AISDKError = _AISDKError;
176
+ function getErrorMessage(error) {
177
+ if (error == null) {
178
+ return "unknown error";
179
+ }
180
+ if (typeof error === "string") {
181
+ return error;
182
+ }
183
+ if (error instanceof Error) {
184
+ return error.message;
185
+ }
186
+ return JSON.stringify(error);
187
+ }
188
+ var name3 = "AI_InvalidArgumentError";
189
+ var marker4 = `vercel.ai.error.${name3}`;
190
+ var symbol4 = Symbol.for(marker4);
191
+ var _a4;
192
+ var InvalidArgumentError = class extends AISDKError {
193
+ constructor({
194
+ message,
195
+ cause,
196
+ argument
197
+ }) {
198
+ super({ name: name3, message, cause });
199
+ this[_a4] = true;
200
+ this.argument = argument;
201
+ }
202
+ static isInstance(error) {
203
+ return AISDKError.hasMarker(error, marker4);
204
+ }
205
+ };
206
+ _a4 = symbol4;
207
+ var name6 = "AI_JSONParseError";
208
+ var marker7 = `vercel.ai.error.${name6}`;
209
+ var symbol7 = Symbol.for(marker7);
210
+ var _a7;
211
+ var JSONParseError = class extends AISDKError {
212
+ constructor({ text, cause }) {
213
+ super({
214
+ name: name6,
215
+ message: `JSON parsing failed: Text: ${text}.
216
+ Error message: ${getErrorMessage(cause)}`,
217
+ cause
218
+ });
219
+ this[_a7] = true;
220
+ this.text = text;
221
+ }
222
+ static isInstance(error) {
223
+ return AISDKError.hasMarker(error, marker7);
224
+ }
225
+ };
226
+ _a7 = symbol7;
227
+ var name12 = "AI_TypeValidationError";
228
+ var marker13 = `vercel.ai.error.${name12}`;
229
+ var symbol13 = Symbol.for(marker13);
230
+ var _a13;
231
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
232
+ constructor({ value, cause }) {
233
+ super({
234
+ name: name12,
235
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
236
+ Error message: ${getErrorMessage(cause)}`,
237
+ cause
238
+ });
239
+ this[_a13] = true;
240
+ this.value = value;
241
+ }
242
+ static isInstance(error) {
243
+ return AISDKError.hasMarker(error, marker13);
244
+ }
245
+ /**
246
+ * Wraps an error into a TypeValidationError.
247
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
248
+ * Otherwise, it creates a new TypeValidationError.
249
+ *
250
+ * @param {Object} params - The parameters for wrapping the error.
251
+ * @param {unknown} params.value - The value that failed validation.
252
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
253
+ * @returns {TypeValidationError} A TypeValidationError instance.
254
+ */
255
+ static wrap({
256
+ value,
257
+ cause
258
+ }) {
259
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
260
+ }
261
+ };
262
+ _a13 = symbol13;
263
+ var TypeValidationError = _TypeValidationError;
264
+
265
+ // ../../node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.js
266
+ var customAlphabet = (alphabet, defaultSize = 21) => {
267
+ return (size = defaultSize) => {
268
+ let id = "";
269
+ let i = size | 0;
270
+ while (i--) {
271
+ id += alphabet[Math.random() * alphabet.length | 0];
272
+ }
273
+ return id;
274
+ };
275
+ };
276
+
277
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@2.2.8_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
278
+ var import_secure_json_parse = __toESM(require_secure_json_parse());
279
+ var createIdGenerator = ({
280
+ prefix,
281
+ size: defaultSize = 16,
282
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
283
+ separator = "-"
284
+ } = {}) => {
285
+ const generator = customAlphabet(alphabet, defaultSize);
286
+ if (prefix == null) {
287
+ return generator;
288
+ }
289
+ if (alphabet.includes(separator)) {
290
+ throw new InvalidArgumentError({
291
+ argument: "separator",
292
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
293
+ });
294
+ }
295
+ return (size) => `${prefix}${separator}${generator(size)}`;
296
+ };
297
+ createIdGenerator();
298
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
299
+ function validator(validate) {
300
+ return { [validatorSymbol]: true, validate };
301
+ }
302
+ function isValidator(value) {
303
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
304
+ }
305
+ function asValidator(value) {
306
+ return isValidator(value) ? value : zodValidator(value);
307
+ }
308
+ function zodValidator(zodSchema) {
309
+ return validator((value) => {
310
+ const result = zodSchema.safeParse(value);
311
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
312
+ });
313
+ }
314
+ function safeValidateTypes({
315
+ value,
316
+ schema
317
+ }) {
318
+ const validator2 = asValidator(schema);
319
+ try {
320
+ if (validator2.validate == null) {
321
+ return { success: true, value };
322
+ }
323
+ const result = validator2.validate(value);
324
+ if (result.success) {
325
+ return result;
326
+ }
327
+ return {
328
+ success: false,
329
+ error: TypeValidationError.wrap({ value, cause: result.error })
330
+ };
331
+ } catch (error) {
332
+ return {
333
+ success: false,
334
+ error: TypeValidationError.wrap({ value, cause: error })
335
+ };
336
+ }
337
+ }
338
+ function safeParseJSON({
339
+ text,
340
+ schema
341
+ }) {
342
+ try {
343
+ const value = import_secure_json_parse.default.parse(text);
344
+ if (schema == null) {
345
+ return { success: true, value, rawValue: value };
346
+ }
347
+ const validationResult = safeValidateTypes({ value, schema });
348
+ return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
349
+ } catch (error) {
350
+ return {
351
+ success: false,
352
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
353
+ };
354
+ }
355
+ }
356
+
357
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
358
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
359
+ function fixJson(input) {
360
+ const stack = ["ROOT"];
361
+ let lastValidIndex = -1;
362
+ let literalStart = null;
363
+ function processValueStart(char, i, swapState) {
364
+ {
365
+ switch (char) {
366
+ case '"': {
367
+ lastValidIndex = i;
368
+ stack.pop();
369
+ stack.push(swapState);
370
+ stack.push("INSIDE_STRING");
371
+ break;
372
+ }
373
+ case "f":
374
+ case "t":
375
+ case "n": {
376
+ lastValidIndex = i;
377
+ literalStart = i;
378
+ stack.pop();
379
+ stack.push(swapState);
380
+ stack.push("INSIDE_LITERAL");
381
+ break;
382
+ }
383
+ case "-": {
384
+ stack.pop();
385
+ stack.push(swapState);
386
+ stack.push("INSIDE_NUMBER");
387
+ break;
388
+ }
389
+ case "0":
390
+ case "1":
391
+ case "2":
392
+ case "3":
393
+ case "4":
394
+ case "5":
395
+ case "6":
396
+ case "7":
397
+ case "8":
398
+ case "9": {
399
+ lastValidIndex = i;
400
+ stack.pop();
401
+ stack.push(swapState);
402
+ stack.push("INSIDE_NUMBER");
403
+ break;
404
+ }
405
+ case "{": {
406
+ lastValidIndex = i;
407
+ stack.pop();
408
+ stack.push(swapState);
409
+ stack.push("INSIDE_OBJECT_START");
410
+ break;
411
+ }
412
+ case "[": {
413
+ lastValidIndex = i;
414
+ stack.pop();
415
+ stack.push(swapState);
416
+ stack.push("INSIDE_ARRAY_START");
417
+ break;
418
+ }
419
+ }
420
+ }
421
+ }
422
+ function processAfterObjectValue(char, i) {
423
+ switch (char) {
424
+ case ",": {
425
+ stack.pop();
426
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
427
+ break;
428
+ }
429
+ case "}": {
430
+ lastValidIndex = i;
431
+ stack.pop();
432
+ break;
433
+ }
434
+ }
435
+ }
436
+ function processAfterArrayValue(char, i) {
437
+ switch (char) {
438
+ case ",": {
439
+ stack.pop();
440
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
441
+ break;
442
+ }
443
+ case "]": {
444
+ lastValidIndex = i;
445
+ stack.pop();
446
+ break;
447
+ }
448
+ }
449
+ }
450
+ for (let i = 0; i < input.length; i++) {
451
+ const char = input[i];
452
+ const currentState = stack[stack.length - 1];
453
+ switch (currentState) {
454
+ case "ROOT":
455
+ processValueStart(char, i, "FINISH");
456
+ break;
457
+ case "INSIDE_OBJECT_START": {
458
+ switch (char) {
459
+ case '"': {
460
+ stack.pop();
461
+ stack.push("INSIDE_OBJECT_KEY");
462
+ break;
463
+ }
464
+ case "}": {
465
+ lastValidIndex = i;
466
+ stack.pop();
467
+ break;
468
+ }
469
+ }
470
+ break;
471
+ }
472
+ case "INSIDE_OBJECT_AFTER_COMMA": {
473
+ switch (char) {
474
+ case '"': {
475
+ stack.pop();
476
+ stack.push("INSIDE_OBJECT_KEY");
477
+ break;
478
+ }
479
+ }
480
+ break;
481
+ }
482
+ case "INSIDE_OBJECT_KEY": {
483
+ switch (char) {
484
+ case '"': {
485
+ stack.pop();
486
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
487
+ break;
488
+ }
489
+ }
490
+ break;
491
+ }
492
+ case "INSIDE_OBJECT_AFTER_KEY": {
493
+ switch (char) {
494
+ case ":": {
495
+ stack.pop();
496
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
497
+ break;
498
+ }
499
+ }
500
+ break;
501
+ }
502
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
503
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
504
+ break;
505
+ }
506
+ case "INSIDE_OBJECT_AFTER_VALUE": {
507
+ processAfterObjectValue(char, i);
508
+ break;
509
+ }
510
+ case "INSIDE_STRING": {
511
+ switch (char) {
512
+ case '"': {
513
+ stack.pop();
514
+ lastValidIndex = i;
515
+ break;
516
+ }
517
+ case "\\": {
518
+ stack.push("INSIDE_STRING_ESCAPE");
519
+ break;
520
+ }
521
+ default: {
522
+ lastValidIndex = i;
523
+ }
524
+ }
525
+ break;
526
+ }
527
+ case "INSIDE_ARRAY_START": {
528
+ switch (char) {
529
+ case "]": {
530
+ lastValidIndex = i;
531
+ stack.pop();
532
+ break;
533
+ }
534
+ default: {
535
+ lastValidIndex = i;
536
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
537
+ break;
538
+ }
539
+ }
540
+ break;
541
+ }
542
+ case "INSIDE_ARRAY_AFTER_VALUE": {
543
+ switch (char) {
544
+ case ",": {
545
+ stack.pop();
546
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
547
+ break;
548
+ }
549
+ case "]": {
550
+ lastValidIndex = i;
551
+ stack.pop();
552
+ break;
553
+ }
554
+ default: {
555
+ lastValidIndex = i;
556
+ break;
557
+ }
558
+ }
559
+ break;
560
+ }
561
+ case "INSIDE_ARRAY_AFTER_COMMA": {
562
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
563
+ break;
564
+ }
565
+ case "INSIDE_STRING_ESCAPE": {
566
+ stack.pop();
567
+ lastValidIndex = i;
568
+ break;
569
+ }
570
+ case "INSIDE_NUMBER": {
571
+ switch (char) {
572
+ case "0":
573
+ case "1":
574
+ case "2":
575
+ case "3":
576
+ case "4":
577
+ case "5":
578
+ case "6":
579
+ case "7":
580
+ case "8":
581
+ case "9": {
582
+ lastValidIndex = i;
583
+ break;
584
+ }
585
+ case "e":
586
+ case "E":
587
+ case "-":
588
+ case ".": {
589
+ break;
590
+ }
591
+ case ",": {
592
+ stack.pop();
593
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
594
+ processAfterArrayValue(char, i);
595
+ }
596
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
597
+ processAfterObjectValue(char, i);
598
+ }
599
+ break;
600
+ }
601
+ case "}": {
602
+ stack.pop();
603
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
604
+ processAfterObjectValue(char, i);
605
+ }
606
+ break;
607
+ }
608
+ case "]": {
609
+ stack.pop();
610
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
611
+ processAfterArrayValue(char, i);
612
+ }
613
+ break;
614
+ }
615
+ default: {
616
+ stack.pop();
617
+ break;
618
+ }
619
+ }
620
+ break;
621
+ }
622
+ case "INSIDE_LITERAL": {
623
+ const partialLiteral = input.substring(literalStart, i + 1);
624
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
625
+ stack.pop();
626
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
627
+ processAfterObjectValue(char, i);
628
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
629
+ processAfterArrayValue(char, i);
630
+ }
631
+ } else {
632
+ lastValidIndex = i;
633
+ }
634
+ break;
635
+ }
636
+ }
637
+ }
638
+ let result = input.slice(0, lastValidIndex + 1);
639
+ for (let i = stack.length - 1; i >= 0; i--) {
640
+ const state = stack[i];
641
+ switch (state) {
642
+ case "INSIDE_STRING": {
643
+ result += '"';
644
+ break;
645
+ }
646
+ case "INSIDE_OBJECT_KEY":
647
+ case "INSIDE_OBJECT_AFTER_KEY":
648
+ case "INSIDE_OBJECT_AFTER_COMMA":
649
+ case "INSIDE_OBJECT_START":
650
+ case "INSIDE_OBJECT_BEFORE_VALUE":
651
+ case "INSIDE_OBJECT_AFTER_VALUE": {
652
+ result += "}";
653
+ break;
654
+ }
655
+ case "INSIDE_ARRAY_START":
656
+ case "INSIDE_ARRAY_AFTER_COMMA":
657
+ case "INSIDE_ARRAY_AFTER_VALUE": {
658
+ result += "]";
659
+ break;
660
+ }
661
+ case "INSIDE_LITERAL": {
662
+ const partialLiteral = input.substring(literalStart, input.length);
663
+ if ("true".startsWith(partialLiteral)) {
664
+ result += "true".slice(partialLiteral.length);
665
+ } else if ("false".startsWith(partialLiteral)) {
666
+ result += "false".slice(partialLiteral.length);
667
+ } else if ("null".startsWith(partialLiteral)) {
668
+ result += "null".slice(partialLiteral.length);
669
+ }
670
+ }
671
+ }
672
+ }
673
+ return result;
674
+ }
675
+ function parsePartialJson(jsonText) {
676
+ if (jsonText === void 0) {
677
+ return { value: void 0, state: "undefined-input" };
678
+ }
679
+ let result = safeParseJSON({ text: jsonText });
680
+ if (result.success) {
681
+ return { value: result.value, state: "successful-parse" };
682
+ }
683
+ result = safeParseJSON({ text: fixJson(jsonText) });
684
+ if (result.success) {
685
+ return { value: result.value, state: "repaired-parse" };
686
+ }
687
+ return { value: void 0, state: "failed-parse" };
688
+ }
689
+ var textStreamPart2 = {
690
+ code: "0",
691
+ name: "text",
692
+ parse: (value) => {
693
+ if (typeof value !== "string") {
694
+ throw new Error('"text" parts expect a string value.');
695
+ }
696
+ return { type: "text", value };
697
+ }
698
+ };
699
+ var dataStreamPart = {
700
+ code: "2",
701
+ name: "data",
702
+ parse: (value) => {
703
+ if (!Array.isArray(value)) {
704
+ throw new Error('"data" parts expect an array value.');
705
+ }
706
+ return { type: "data", value };
707
+ }
708
+ };
709
+ var errorStreamPart2 = {
710
+ code: "3",
711
+ name: "error",
712
+ parse: (value) => {
713
+ if (typeof value !== "string") {
714
+ throw new Error('"error" parts expect a string value.');
715
+ }
716
+ return { type: "error", value };
717
+ }
718
+ };
719
+ var messageAnnotationsStreamPart = {
720
+ code: "8",
721
+ name: "message_annotations",
722
+ parse: (value) => {
723
+ if (!Array.isArray(value)) {
724
+ throw new Error('"message_annotations" parts expect an array value.');
725
+ }
726
+ return { type: "message_annotations", value };
727
+ }
728
+ };
729
+ var toolCallStreamPart = {
730
+ code: "9",
731
+ name: "tool_call",
732
+ parse: (value) => {
733
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
734
+ throw new Error(
735
+ '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
736
+ );
737
+ }
738
+ return {
739
+ type: "tool_call",
740
+ value
741
+ };
742
+ }
743
+ };
744
+ var toolResultStreamPart = {
745
+ code: "a",
746
+ name: "tool_result",
747
+ parse: (value) => {
748
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) {
749
+ throw new Error(
750
+ '"tool_result" parts expect an object with a "toolCallId" and a "result" property.'
751
+ );
752
+ }
753
+ return {
754
+ type: "tool_result",
755
+ value
756
+ };
757
+ }
758
+ };
759
+ var toolCallStreamingStartStreamPart = {
760
+ code: "b",
761
+ name: "tool_call_streaming_start",
762
+ parse: (value) => {
763
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") {
764
+ throw new Error(
765
+ '"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.'
766
+ );
767
+ }
768
+ return {
769
+ type: "tool_call_streaming_start",
770
+ value
771
+ };
772
+ }
773
+ };
774
+ var toolCallDeltaStreamPart = {
775
+ code: "c",
776
+ name: "tool_call_delta",
777
+ parse: (value) => {
778
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") {
779
+ throw new Error(
780
+ '"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.'
781
+ );
782
+ }
783
+ return {
784
+ type: "tool_call_delta",
785
+ value
786
+ };
787
+ }
788
+ };
789
+ var finishMessageStreamPart = {
790
+ code: "d",
791
+ name: "finish_message",
792
+ parse: (value) => {
793
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
794
+ throw new Error(
795
+ '"finish_message" parts expect an object with a "finishReason" property.'
796
+ );
797
+ }
798
+ const result = {
799
+ finishReason: value.finishReason
800
+ };
801
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
802
+ result.usage = {
803
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
804
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
805
+ };
806
+ }
807
+ return {
808
+ type: "finish_message",
809
+ value: result
810
+ };
811
+ }
812
+ };
813
+ var finishStepStreamPart = {
814
+ code: "e",
815
+ name: "finish_step",
816
+ parse: (value) => {
817
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
818
+ throw new Error(
819
+ '"finish_step" parts expect an object with a "finishReason" property.'
820
+ );
821
+ }
822
+ const result = {
823
+ finishReason: value.finishReason,
824
+ isContinued: false
825
+ };
826
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
827
+ result.usage = {
828
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
829
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
830
+ };
831
+ }
832
+ if ("isContinued" in value && typeof value.isContinued === "boolean") {
833
+ result.isContinued = value.isContinued;
834
+ }
835
+ return {
836
+ type: "finish_step",
837
+ value: result
838
+ };
839
+ }
840
+ };
841
+ var startStepStreamPart = {
842
+ code: "f",
843
+ name: "start_step",
844
+ parse: (value) => {
845
+ if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") {
846
+ throw new Error(
847
+ '"start_step" parts expect an object with an "id" property.'
848
+ );
849
+ }
850
+ return {
851
+ type: "start_step",
852
+ value: {
853
+ messageId: value.messageId
854
+ }
855
+ };
856
+ }
857
+ };
858
+ var reasoningStreamPart = {
859
+ code: "g",
860
+ name: "reasoning",
861
+ parse: (value) => {
862
+ if (typeof value !== "string") {
863
+ throw new Error('"reasoning" parts expect a string value.');
864
+ }
865
+ return { type: "reasoning", value };
866
+ }
867
+ };
868
+ var sourcePart = {
869
+ code: "h",
870
+ name: "source",
871
+ parse: (value) => {
872
+ if (value == null || typeof value !== "object") {
873
+ throw new Error('"source" parts expect a Source object.');
874
+ }
875
+ return {
876
+ type: "source",
877
+ value
878
+ };
879
+ }
880
+ };
881
+ var redactedReasoningStreamPart = {
882
+ code: "i",
883
+ name: "redacted_reasoning",
884
+ parse: (value) => {
885
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string") {
886
+ throw new Error(
887
+ '"redacted_reasoning" parts expect an object with a "data" property.'
888
+ );
889
+ }
890
+ return { type: "redacted_reasoning", value: { data: value.data } };
891
+ }
892
+ };
893
+ var reasoningSignatureStreamPart = {
894
+ code: "j",
895
+ name: "reasoning_signature",
896
+ parse: (value) => {
897
+ if (value == null || typeof value !== "object" || !("signature" in value) || typeof value.signature !== "string") {
898
+ throw new Error(
899
+ '"reasoning_signature" parts expect an object with a "signature" property.'
900
+ );
901
+ }
902
+ return {
903
+ type: "reasoning_signature",
904
+ value: { signature: value.signature }
905
+ };
906
+ }
907
+ };
908
+ var fileStreamPart = {
909
+ code: "k",
910
+ name: "file",
911
+ parse: (value) => {
912
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string" || !("mimeType" in value) || typeof value.mimeType !== "string") {
913
+ throw new Error(
914
+ '"file" parts expect an object with a "data" and "mimeType" property.'
915
+ );
916
+ }
917
+ return { type: "file", value };
918
+ }
919
+ };
920
+ var dataStreamParts = [
921
+ textStreamPart2,
922
+ dataStreamPart,
923
+ errorStreamPart2,
924
+ messageAnnotationsStreamPart,
925
+ toolCallStreamPart,
926
+ toolResultStreamPart,
927
+ toolCallStreamingStartStreamPart,
928
+ toolCallDeltaStreamPart,
929
+ finishMessageStreamPart,
930
+ finishStepStreamPart,
931
+ startStepStreamPart,
932
+ reasoningStreamPart,
933
+ sourcePart,
934
+ redactedReasoningStreamPart,
935
+ reasoningSignatureStreamPart,
936
+ fileStreamPart
937
+ ];
938
+ var dataStreamPartsByCode = Object.fromEntries(
939
+ dataStreamParts.map((part) => [part.code, part])
940
+ );
941
+ Object.fromEntries(
942
+ dataStreamParts.map((part) => [part.name, part.code])
943
+ );
944
+ var validCodes2 = dataStreamParts.map((part) => part.code);
945
+ var parseDataStreamPart = (line) => {
946
+ const firstSeparatorIndex = line.indexOf(":");
947
+ if (firstSeparatorIndex === -1) {
948
+ throw new Error("Failed to parse stream string. No separator found.");
949
+ }
950
+ const prefix = line.slice(0, firstSeparatorIndex);
951
+ if (!validCodes2.includes(prefix)) {
952
+ throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
953
+ }
954
+ const code = prefix;
955
+ const textValue = line.slice(firstSeparatorIndex + 1);
956
+ const jsonValue = JSON.parse(textValue);
957
+ return dataStreamPartsByCode[code].parse(jsonValue);
958
+ };
959
+ var NEWLINE = "\n".charCodeAt(0);
960
+ function concatChunks(chunks, totalLength) {
961
+ const concatenatedChunks = new Uint8Array(totalLength);
962
+ let offset = 0;
963
+ for (const chunk of chunks) {
964
+ concatenatedChunks.set(chunk, offset);
965
+ offset += chunk.length;
966
+ }
967
+ chunks.length = 0;
968
+ return concatenatedChunks;
969
+ }
970
+ async function processDataStream({
971
+ stream,
972
+ onTextPart,
973
+ onReasoningPart,
974
+ onReasoningSignaturePart,
975
+ onRedactedReasoningPart,
976
+ onSourcePart,
977
+ onFilePart,
978
+ onDataPart,
979
+ onErrorPart,
980
+ onToolCallStreamingStartPart,
981
+ onToolCallDeltaPart,
982
+ onToolCallPart,
983
+ onToolResultPart,
984
+ onMessageAnnotationsPart,
985
+ onFinishMessagePart,
986
+ onFinishStepPart,
987
+ onStartStepPart
988
+ }) {
989
+ const reader = stream.getReader();
990
+ const decoder = new TextDecoder();
991
+ const chunks = [];
992
+ let totalLength = 0;
993
+ while (true) {
994
+ const { value } = await reader.read();
995
+ if (value) {
996
+ chunks.push(value);
997
+ totalLength += value.length;
998
+ if (value[value.length - 1] !== NEWLINE) {
999
+ continue;
1000
+ }
1001
+ }
1002
+ if (chunks.length === 0) {
1003
+ break;
1004
+ }
1005
+ const concatenatedChunks = concatChunks(chunks, totalLength);
1006
+ totalLength = 0;
1007
+ const streamParts = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseDataStreamPart);
1008
+ for (const { type, value: value2 } of streamParts) {
1009
+ switch (type) {
1010
+ case "text":
1011
+ await (onTextPart == null ? void 0 : onTextPart(value2));
1012
+ break;
1013
+ case "reasoning":
1014
+ await (onReasoningPart == null ? void 0 : onReasoningPart(value2));
1015
+ break;
1016
+ case "reasoning_signature":
1017
+ await (onReasoningSignaturePart == null ? void 0 : onReasoningSignaturePart(value2));
1018
+ break;
1019
+ case "redacted_reasoning":
1020
+ await (onRedactedReasoningPart == null ? void 0 : onRedactedReasoningPart(value2));
1021
+ break;
1022
+ case "file":
1023
+ await (onFilePart == null ? void 0 : onFilePart(value2));
1024
+ break;
1025
+ case "source":
1026
+ await (onSourcePart == null ? void 0 : onSourcePart(value2));
1027
+ break;
1028
+ case "data":
1029
+ await (onDataPart == null ? void 0 : onDataPart(value2));
1030
+ break;
1031
+ case "error":
1032
+ await (onErrorPart == null ? void 0 : onErrorPart(value2));
1033
+ break;
1034
+ case "message_annotations":
1035
+ await (onMessageAnnotationsPart == null ? void 0 : onMessageAnnotationsPart(value2));
1036
+ break;
1037
+ case "tool_call_streaming_start":
1038
+ await (onToolCallStreamingStartPart == null ? void 0 : onToolCallStreamingStartPart(value2));
1039
+ break;
1040
+ case "tool_call_delta":
1041
+ await (onToolCallDeltaPart == null ? void 0 : onToolCallDeltaPart(value2));
1042
+ break;
1043
+ case "tool_call":
1044
+ await (onToolCallPart == null ? void 0 : onToolCallPart(value2));
1045
+ break;
1046
+ case "tool_result":
1047
+ await (onToolResultPart == null ? void 0 : onToolResultPart(value2));
1048
+ break;
1049
+ case "finish_message":
1050
+ await (onFinishMessagePart == null ? void 0 : onFinishMessagePart(value2));
1051
+ break;
1052
+ case "finish_step":
1053
+ await (onFinishStepPart == null ? void 0 : onFinishStepPart(value2));
1054
+ break;
1055
+ case "start_step":
1056
+ await (onStartStepPart == null ? void 0 : onStartStepPart(value2));
1057
+ break;
1058
+ default: {
1059
+ const exhaustiveCheck = type;
1060
+ throw new Error(`Unknown stream part type: ${exhaustiveCheck}`);
1061
+ }
1062
+ }
1063
+ }
1064
+ }
1065
+ }
11
1066
  function parseClientRequestContext(requestContext$1) {
12
1067
  if (requestContext$1) {
13
1068
  if (requestContext$1 instanceof requestContext.RequestContext) {
@@ -34,7 +1089,7 @@ function requestContextQueryString(requestContext, delimiter = "?") {
34
1089
  function isZodType(value) {
35
1090
  return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
36
1091
  }
37
- function zodToJsonSchema(zodSchema) {
1092
+ function zodToJsonSchema2(zodSchema) {
38
1093
  if (!isZodType(zodSchema)) {
39
1094
  return zodSchema;
40
1095
  }
@@ -53,7 +1108,7 @@ function processClientTools(clientTools) {
53
1108
  key,
54
1109
  {
55
1110
  ...value,
56
- parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
1111
+ parameters: value.parameters ? zodToJsonSchema2(value.parameters) : void 0
57
1112
  }
58
1113
  ];
59
1114
  } else {
@@ -61,8 +1116,8 @@ function processClientTools(clientTools) {
61
1116
  key,
62
1117
  {
63
1118
  ...value,
64
- inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
65
- outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
1119
+ inputSchema: value.inputSchema ? zodToJsonSchema2(value.inputSchema) : void 0,
1120
+ outputSchema: value.outputSchema ? zodToJsonSchema2(value.outputSchema) : void 0
66
1121
  }
67
1122
  ];
68
1123
  }
@@ -332,8 +1387,8 @@ var Agent = class extends BaseResource {
332
1387
  async generateLegacy(params) {
333
1388
  const processedParams = {
334
1389
  ...params,
335
- output: params.output ? zodToJsonSchema(params.output) : void 0,
336
- experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
1390
+ output: params.output ? zodToJsonSchema2(params.output) : void 0,
1391
+ experimental_output: params.experimental_output ? zodToJsonSchema2(params.experimental_output) : void 0,
337
1392
  requestContext: parseClientRequestContext(params.requestContext),
338
1393
  clientTools: processClientTools(params.clientTools)
339
1394
  };
@@ -404,7 +1459,7 @@ var Agent = class extends BaseResource {
404
1459
  clientTools: processClientTools(params.clientTools),
405
1460
  structuredOutput: params.structuredOutput ? {
406
1461
  ...params.structuredOutput,
407
- schema: zodToJsonSchema(params.structuredOutput.schema)
1462
+ schema: zodToJsonSchema2(params.structuredOutput.schema)
408
1463
  } : void 0
409
1464
  };
410
1465
  const { resourceId, threadId, requestContext } = processedParams;
@@ -494,7 +1549,7 @@ var Agent = class extends BaseResource {
494
1549
  replaceLastMessage
495
1550
  });
496
1551
  }
497
- await uiUtils.processDataStream({
1552
+ await processDataStream({
498
1553
  stream,
499
1554
  onTextPart(value) {
500
1555
  if (currentTextPart == null) {
@@ -591,7 +1646,7 @@ var Agent = class extends BaseResource {
591
1646
  onToolCallDeltaPart(value) {
592
1647
  const partialToolCall = partialToolCalls[value.toolCallId];
593
1648
  partialToolCall.text += value.argsTextDelta;
594
- const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
1649
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
595
1650
  const invocation = {
596
1651
  state: "partial-call",
597
1652
  step: partialToolCall.step,
@@ -697,8 +1752,8 @@ var Agent = class extends BaseResource {
697
1752
  async streamLegacy(params) {
698
1753
  const processedParams = {
699
1754
  ...params,
700
- output: params.output ? zodToJsonSchema(params.output) : void 0,
701
- experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
1755
+ output: params.output ? zodToJsonSchema2(params.output) : void 0,
1756
+ experimental_output: params.experimental_output ? zodToJsonSchema2(params.experimental_output) : void 0,
702
1757
  requestContext: parseClientRequestContext(params.requestContext),
703
1758
  clientTools: processClientTools(params.clientTools)
704
1759
  };
@@ -710,7 +1765,7 @@ var Agent = class extends BaseResource {
710
1765
  headers: response.headers
711
1766
  });
712
1767
  streamResponse.processDataStream = async (options = {}) => {
713
- await uiUtils.processDataStream({
1768
+ await processDataStream({
714
1769
  stream: streamResponse.body,
715
1770
  ...options
716
1771
  });
@@ -793,7 +1848,7 @@ var Agent = class extends BaseResource {
793
1848
  case "tripwire": {
794
1849
  message.parts.push({
795
1850
  type: "text",
796
- text: chunk.payload.tripwireReason
1851
+ text: chunk.payload.reason
797
1852
  });
798
1853
  execUpdate();
799
1854
  break;
@@ -916,7 +1971,7 @@ var Agent = class extends BaseResource {
916
1971
  case "tool-call-delta": {
917
1972
  const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
918
1973
  partialToolCall.text += chunk.payload.argsTextDelta;
919
- const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
1974
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
920
1975
  const invocation = {
921
1976
  state: "partial-call",
922
1977
  step: partialToolCall.step,
@@ -1148,7 +2203,7 @@ var Agent = class extends BaseResource {
1148
2203
  clientTools: processClientTools(params.clientTools),
1149
2204
  structuredOutput: params.structuredOutput ? {
1150
2205
  ...params.structuredOutput,
1151
- schema: zodToJsonSchema(params.structuredOutput.schema)
2206
+ schema: zodToJsonSchema2(params.structuredOutput.schema)
1152
2207
  } : void 0
1153
2208
  };
1154
2209
  let readableController;
@@ -1586,186 +2641,68 @@ var Tool = class extends BaseResource {
1586
2641
  });
1587
2642
  }
1588
2643
  };
1589
-
1590
- // src/resources/workflow.ts
2644
+ function deserializeWorkflowError(result) {
2645
+ if (result.status === "failed" && result.error) {
2646
+ result.error = error.getErrorFromUnknown(result.error, {
2647
+ fallbackMessage: "Unknown workflow error",
2648
+ supportSerialization: false
2649
+ });
2650
+ }
2651
+ return result;
2652
+ }
1591
2653
  var RECORD_SEPARATOR = "";
1592
- var Workflow = class extends BaseResource {
1593
- constructor(options, workflowId) {
2654
+ var Run = class extends BaseResource {
2655
+ constructor(options, workflowId, runId) {
1594
2656
  super(options);
1595
2657
  this.workflowId = workflowId;
2658
+ this.runId = runId;
1596
2659
  }
1597
2660
  /**
1598
- * Retrieves details about the workflow
1599
- * @param requestContext - Optional request context to pass as query parameter
1600
- * @returns Promise containing workflow details including steps and graphs
1601
- */
1602
- details(requestContext) {
1603
- return this.request(`/api/workflows/${this.workflowId}${requestContextQueryString(requestContext)}`);
1604
- }
1605
- /**
1606
- * Retrieves all runs for a workflow
1607
- * @param params - Parameters for filtering runs
1608
- * @param requestContext - Optional request context to pass as query parameter
1609
- * @returns Promise containing workflow runs array
2661
+ * Creates a transform stream that parses RECORD_SEPARATOR-delimited JSON chunks
1610
2662
  */
1611
- runs(params, requestContext) {
1612
- const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
1613
- const searchParams = new URLSearchParams();
1614
- if (params?.fromDate) {
1615
- searchParams.set("fromDate", params.fromDate.toISOString());
1616
- }
1617
- if (params?.toDate) {
1618
- searchParams.set("toDate", params.toDate.toISOString());
1619
- }
1620
- if (params?.page !== void 0) {
1621
- searchParams.set("page", String(params.page));
1622
- }
1623
- if (params?.perPage !== void 0) {
1624
- searchParams.set("perPage", String(params.perPage));
1625
- }
1626
- if (params?.limit !== null && params?.limit !== void 0) {
1627
- if (params.limit === false) {
1628
- searchParams.set("limit", "false");
1629
- } else if (typeof params.limit === "number" && params.limit > 0 && Number.isInteger(params.limit)) {
1630
- searchParams.set("limit", String(params.limit));
2663
+ createChunkTransformStream() {
2664
+ let failedChunk = void 0;
2665
+ return new TransformStream({
2666
+ start() {
2667
+ },
2668
+ async transform(chunk, controller) {
2669
+ try {
2670
+ const decoded = new TextDecoder().decode(chunk);
2671
+ const chunks = decoded.split(RECORD_SEPARATOR);
2672
+ for (const chunk2 of chunks) {
2673
+ if (chunk2) {
2674
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2675
+ try {
2676
+ const parsedChunk = JSON.parse(newChunk);
2677
+ controller.enqueue(parsedChunk);
2678
+ failedChunk = void 0;
2679
+ } catch {
2680
+ failedChunk = newChunk;
2681
+ }
2682
+ }
2683
+ }
2684
+ } catch {
2685
+ }
1631
2686
  }
1632
- }
1633
- if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1634
- searchParams.set("offset", String(params.offset));
1635
- }
1636
- if (params?.resourceId) {
1637
- searchParams.set("resourceId", params.resourceId);
1638
- }
1639
- if (requestContextParam) {
1640
- searchParams.set("requestContext", requestContextParam);
1641
- }
1642
- if (searchParams.size) {
1643
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1644
- } else {
1645
- return this.request(`/api/workflows/${this.workflowId}/runs`);
1646
- }
1647
- }
1648
- /**
1649
- * Retrieves a specific workflow run by its ID
1650
- * @param runId - The ID of the workflow run to retrieve
1651
- * @param requestContext - Optional request context to pass as query parameter
1652
- * @returns Promise containing the workflow run details
1653
- */
1654
- runById(runId, requestContext) {
1655
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${requestContextQueryString(requestContext)}`);
1656
- }
1657
- /**
1658
- * Deletes a specific workflow run by its ID
1659
- * @param runId - The ID of the workflow run to delete
1660
- * @returns Promise containing a success message
1661
- */
1662
- deleteRunById(runId) {
1663
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`, {
1664
- method: "DELETE"
1665
2687
  });
1666
2688
  }
1667
- /**
1668
- * Retrieves the execution result for a specific workflow run by its ID
1669
- * @param runId - The ID of the workflow run to retrieve the execution result for
1670
- * @param requestContext - Optional request context to pass as query parameter
1671
- * @returns Promise containing the workflow run execution result
1672
- */
1673
- runExecutionResult(runId, requestContext) {
1674
- return this.request(
1675
- `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${requestContextQueryString(requestContext)}`
1676
- );
1677
- }
1678
2689
  /**
1679
2690
  * Cancels a specific workflow run by its ID
1680
- * @param runId - The ID of the workflow run to cancel
1681
2691
  * @returns Promise containing a success message
1682
2692
  */
1683
- cancelRun(runId) {
1684
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
2693
+ cancelRun() {
2694
+ return this.request(`/api/workflows/${this.workflowId}/runs/${this.runId}/cancel`, {
1685
2695
  method: "POST"
1686
2696
  });
1687
2697
  }
1688
- /**
1689
- * Creates a new workflow run
1690
- * @param params - Optional object containing the optional runId
1691
- * @returns Promise containing the runId of the created run with methods to control execution
1692
- */
1693
- async createRun(params) {
1694
- const searchParams = new URLSearchParams();
1695
- if (!!params?.runId) {
1696
- searchParams.set("runId", params.runId);
1697
- }
1698
- const res = await this.request(
1699
- `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1700
- {
1701
- method: "POST"
1702
- }
1703
- );
1704
- const runId = res.runId;
1705
- return {
1706
- runId,
1707
- start: async (p) => {
1708
- return this.start({
1709
- runId,
1710
- inputData: p.inputData,
1711
- initialState: p.initialState,
1712
- requestContext: p.requestContext,
1713
- tracingOptions: p.tracingOptions
1714
- });
1715
- },
1716
- startAsync: async (p) => {
1717
- return this.startAsync({
1718
- runId,
1719
- inputData: p.inputData,
1720
- initialState: p.initialState,
1721
- requestContext: p.requestContext,
1722
- tracingOptions: p.tracingOptions
1723
- });
1724
- },
1725
- stream: async (p) => {
1726
- return this.stream({
1727
- runId,
1728
- inputData: p.inputData,
1729
- initialState: p.initialState,
1730
- requestContext: p.requestContext
1731
- });
1732
- },
1733
- resume: async (p) => {
1734
- return this.resume({
1735
- runId,
1736
- step: p.step,
1737
- resumeData: p.resumeData,
1738
- requestContext: p.requestContext,
1739
- tracingOptions: p.tracingOptions
1740
- });
1741
- },
1742
- resumeAsync: async (p) => {
1743
- return this.resumeAsync({
1744
- runId,
1745
- step: p.step,
1746
- resumeData: p.resumeData,
1747
- requestContext: p.requestContext,
1748
- tracingOptions: p.tracingOptions
1749
- });
1750
- },
1751
- resumeStreamVNext: async (p) => {
1752
- return this.resumeStreamVNext({
1753
- runId,
1754
- step: p.step,
1755
- resumeData: p.resumeData,
1756
- requestContext: p.requestContext
1757
- });
1758
- }
1759
- };
1760
- }
1761
2698
  /**
1762
2699
  * Starts a workflow run synchronously without waiting for the workflow to complete
1763
- * @param params - Object containing the runId, inputData, initialState and requestContext
2700
+ * @param params - Object containing the inputData, initialState and requestContext
1764
2701
  * @returns Promise containing success message
1765
2702
  */
1766
2703
  start(params) {
1767
2704
  const requestContext = parseClientRequestContext(params.requestContext);
1768
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
2705
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${this.runId}`, {
1769
2706
  method: "POST",
1770
2707
  body: {
1771
2708
  inputData: params?.inputData,
@@ -1777,18 +2714,17 @@ var Workflow = class extends BaseResource {
1777
2714
  }
1778
2715
  /**
1779
2716
  * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1780
- * @param params - Object containing the runId, step, resumeData and requestContext
2717
+ * @param params - Object containing the step, resumeData and requestContext
1781
2718
  * @returns Promise containing success message
1782
2719
  */
1783
2720
  resume({
1784
2721
  step,
1785
- runId,
1786
2722
  resumeData,
1787
2723
  tracingOptions,
1788
2724
  ...rest
1789
2725
  }) {
1790
2726
  const requestContext = parseClientRequestContext(rest.requestContext);
1791
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
2727
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${this.runId}`, {
1792
2728
  method: "POST",
1793
2729
  body: {
1794
2730
  step,
@@ -1800,14 +2736,12 @@ var Workflow = class extends BaseResource {
1800
2736
  }
1801
2737
  /**
1802
2738
  * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1803
- * @param params - Object containing the optional runId, inputData, initialState and requestContext
2739
+ * @param params - Object containing the inputData, initialState and requestContext
1804
2740
  * @returns Promise containing the workflow execution results
1805
2741
  */
1806
2742
  startAsync(params) {
1807
2743
  const searchParams = new URLSearchParams();
1808
- if (!!params?.runId) {
1809
- searchParams.set("runId", params.runId);
1810
- }
2744
+ searchParams.set("runId", this.runId);
1811
2745
  const requestContext = parseClientRequestContext(params.requestContext);
1812
2746
  return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1813
2747
  method: "POST",
@@ -1815,20 +2749,19 @@ var Workflow = class extends BaseResource {
1815
2749
  inputData: params.inputData,
1816
2750
  initialState: params.initialState,
1817
2751
  requestContext,
1818
- tracingOptions: params.tracingOptions
2752
+ tracingOptions: params.tracingOptions,
2753
+ resourceId: params.resourceId
1819
2754
  }
1820
- });
2755
+ }).then(deserializeWorkflowError);
1821
2756
  }
1822
2757
  /**
1823
2758
  * Starts a workflow run and returns a stream
1824
- * @param params - Object containing the optional runId, inputData, initialState and requestContext
2759
+ * @param params - Object containing the inputData, initialState and requestContext
1825
2760
  * @returns Promise containing the workflow execution results
1826
2761
  */
1827
2762
  async stream(params) {
1828
2763
  const searchParams = new URLSearchParams();
1829
- if (!!params?.runId) {
1830
- searchParams.set("runId", params.runId);
1831
- }
2764
+ searchParams.set("runId", this.runId);
1832
2765
  const requestContext = parseClientRequestContext(params.requestContext);
1833
2766
  const response = await this.request(
1834
2767
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
@@ -1838,7 +2771,8 @@ var Workflow = class extends BaseResource {
1838
2771
  inputData: params.inputData,
1839
2772
  initialState: params.initialState,
1840
2773
  requestContext,
1841
- tracingOptions: params.tracingOptions
2774
+ tracingOptions: params.tracingOptions,
2775
+ resourceId: params.resourceId
1842
2776
  },
1843
2777
  stream: true
1844
2778
  }
@@ -1849,40 +2783,15 @@ var Workflow = class extends BaseResource {
1849
2783
  if (!response.body) {
1850
2784
  throw new Error("Response body is null");
1851
2785
  }
1852
- let failedChunk = void 0;
1853
- const transformStream = new TransformStream({
1854
- start() {
1855
- },
1856
- async transform(chunk, controller) {
1857
- try {
1858
- const decoded = new TextDecoder().decode(chunk);
1859
- const chunks = decoded.split(RECORD_SEPARATOR);
1860
- for (const chunk2 of chunks) {
1861
- if (chunk2) {
1862
- const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1863
- try {
1864
- const parsedChunk = JSON.parse(newChunk);
1865
- controller.enqueue(parsedChunk);
1866
- failedChunk = void 0;
1867
- } catch {
1868
- failedChunk = newChunk;
1869
- }
1870
- }
1871
- }
1872
- } catch {
1873
- }
1874
- }
1875
- });
1876
- return response.body.pipeThrough(transformStream);
2786
+ return response.body.pipeThrough(this.createChunkTransformStream());
1877
2787
  }
1878
2788
  /**
1879
2789
  * Observes workflow stream for a workflow run
1880
- * @param params - Object containing the runId
1881
2790
  * @returns Promise containing the workflow execution results
1882
2791
  */
1883
- async observeStream(params) {
2792
+ async observeStream() {
1884
2793
  const searchParams = new URLSearchParams();
1885
- searchParams.set("runId", params.runId);
2794
+ searchParams.set("runId", this.runId);
1886
2795
  const response = await this.request(
1887
2796
  `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1888
2797
  {
@@ -1896,97 +2805,47 @@ var Workflow = class extends BaseResource {
1896
2805
  if (!response.body) {
1897
2806
  throw new Error("Response body is null");
1898
2807
  }
1899
- let failedChunk = void 0;
1900
- const transformStream = new TransformStream({
1901
- start() {
1902
- },
1903
- async transform(chunk, controller) {
1904
- try {
1905
- const decoded = new TextDecoder().decode(chunk);
1906
- const chunks = decoded.split(RECORD_SEPARATOR);
1907
- for (const chunk2 of chunks) {
1908
- if (chunk2) {
1909
- const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1910
- try {
1911
- const parsedChunk = JSON.parse(newChunk);
1912
- controller.enqueue(parsedChunk);
1913
- failedChunk = void 0;
1914
- } catch {
1915
- failedChunk = newChunk;
1916
- }
1917
- }
1918
- }
1919
- } catch {
1920
- }
1921
- }
1922
- });
1923
- return response.body.pipeThrough(transformStream);
2808
+ return response.body.pipeThrough(this.createChunkTransformStream());
1924
2809
  }
1925
2810
  /**
1926
2811
  * Starts a workflow run and returns a stream
1927
- * @param params - Object containing the optional runId, inputData, initialState and requestContext
2812
+ * @param params - Object containing the inputData, initialState and requestContext
1928
2813
  * @returns Promise containing the workflow execution results
1929
2814
  */
1930
2815
  async streamVNext(params) {
1931
- const searchParams = new URLSearchParams();
1932
- if (!!params?.runId) {
1933
- searchParams.set("runId", params.runId);
1934
- }
1935
- const requestContext = parseClientRequestContext(params.requestContext);
1936
- const response = await this.request(
1937
- `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1938
- {
1939
- method: "POST",
1940
- body: {
1941
- inputData: params.inputData,
1942
- initialState: params.initialState,
1943
- requestContext,
1944
- closeOnSuspend: params.closeOnSuspend,
1945
- tracingOptions: params.tracingOptions
1946
- },
1947
- stream: true
1948
- }
1949
- );
1950
- if (!response.ok) {
1951
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1952
- }
1953
- if (!response.body) {
1954
- throw new Error("Response body is null");
1955
- }
1956
- let failedChunk = void 0;
1957
- const transformStream = new TransformStream({
1958
- start() {
1959
- },
1960
- async transform(chunk, controller) {
1961
- try {
1962
- const decoded = new TextDecoder().decode(chunk);
1963
- const chunks = decoded.split(RECORD_SEPARATOR);
1964
- for (const chunk2 of chunks) {
1965
- if (chunk2) {
1966
- const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1967
- try {
1968
- const parsedChunk = JSON.parse(newChunk);
1969
- controller.enqueue(parsedChunk);
1970
- failedChunk = void 0;
1971
- } catch {
1972
- failedChunk = newChunk;
1973
- }
1974
- }
1975
- }
1976
- } catch {
1977
- }
2816
+ const searchParams = new URLSearchParams();
2817
+ searchParams.set("runId", this.runId);
2818
+ const requestContext = parseClientRequestContext(params.requestContext);
2819
+ const response = await this.request(
2820
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
2821
+ {
2822
+ method: "POST",
2823
+ body: {
2824
+ inputData: params.inputData,
2825
+ initialState: params.initialState,
2826
+ requestContext,
2827
+ closeOnSuspend: params.closeOnSuspend,
2828
+ tracingOptions: params.tracingOptions,
2829
+ resourceId: params.resourceId
2830
+ },
2831
+ stream: true
1978
2832
  }
1979
- });
1980
- return response.body.pipeThrough(transformStream);
2833
+ );
2834
+ if (!response.ok) {
2835
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2836
+ }
2837
+ if (!response.body) {
2838
+ throw new Error("Response body is null");
2839
+ }
2840
+ return response.body.pipeThrough(this.createChunkTransformStream());
1981
2841
  }
1982
2842
  /**
1983
2843
  * Observes workflow vNext stream for a workflow run
1984
- * @param params - Object containing the runId
1985
2844
  * @returns Promise containing the workflow execution results
1986
2845
  */
1987
- async observeStreamVNext(params) {
2846
+ async observeStreamVNext() {
1988
2847
  const searchParams = new URLSearchParams();
1989
- searchParams.set("runId", params.runId);
2848
+ searchParams.set("runId", this.runId);
1990
2849
  const response = await this.request(
1991
2850
  `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
1992
2851
  {
@@ -2000,40 +2859,16 @@ var Workflow = class extends BaseResource {
2000
2859
  if (!response.body) {
2001
2860
  throw new Error("Response body is null");
2002
2861
  }
2003
- let failedChunk = void 0;
2004
- const transformStream = new TransformStream({
2005
- start() {
2006
- },
2007
- async transform(chunk, controller) {
2008
- try {
2009
- const decoded = new TextDecoder().decode(chunk);
2010
- const chunks = decoded.split(RECORD_SEPARATOR);
2011
- for (const chunk2 of chunks) {
2012
- if (chunk2) {
2013
- const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2014
- try {
2015
- const parsedChunk = JSON.parse(newChunk);
2016
- controller.enqueue(parsedChunk);
2017
- failedChunk = void 0;
2018
- } catch {
2019
- failedChunk = newChunk;
2020
- }
2021
- }
2022
- }
2023
- } catch {
2024
- }
2025
- }
2026
- });
2027
- return response.body.pipeThrough(transformStream);
2862
+ return response.body.pipeThrough(this.createChunkTransformStream());
2028
2863
  }
2029
2864
  /**
2030
2865
  * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2031
- * @param params - Object containing the runId, step, resumeData and requestContext
2866
+ * @param params - Object containing the step, resumeData and requestContext
2032
2867
  * @returns Promise containing the workflow resume results
2033
2868
  */
2034
2869
  resumeAsync(params) {
2035
2870
  const requestContext = parseClientRequestContext(params.requestContext);
2036
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2871
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${this.runId}`, {
2037
2872
  method: "POST",
2038
2873
  body: {
2039
2874
  step: params.step,
@@ -2041,16 +2876,16 @@ var Workflow = class extends BaseResource {
2041
2876
  requestContext,
2042
2877
  tracingOptions: params.tracingOptions
2043
2878
  }
2044
- });
2879
+ }).then(deserializeWorkflowError);
2045
2880
  }
2046
2881
  /**
2047
2882
  * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2048
- * @param params - Object containing the runId, step, resumeData and requestContext
2883
+ * @param params - Object containing the step, resumeData and requestContext
2049
2884
  * @returns Promise containing the workflow resume results
2050
2885
  */
2051
2886
  async resumeStreamVNext(params) {
2052
2887
  const searchParams = new URLSearchParams();
2053
- searchParams.set("runId", params.runId);
2888
+ searchParams.set("runId", this.runId);
2054
2889
  const requestContext = parseClientRequestContext(params.requestContext);
2055
2890
  const response = await this.request(
2056
2891
  `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
@@ -2071,63 +2906,16 @@ var Workflow = class extends BaseResource {
2071
2906
  if (!response.body) {
2072
2907
  throw new Error("Response body is null");
2073
2908
  }
2074
- let failedChunk = void 0;
2075
- const transformStream = new TransformStream({
2076
- start() {
2077
- },
2078
- async transform(chunk, controller) {
2079
- try {
2080
- const decoded = new TextDecoder().decode(chunk);
2081
- const chunks = decoded.split(RECORD_SEPARATOR);
2082
- for (const chunk2 of chunks) {
2083
- if (chunk2) {
2084
- const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2085
- try {
2086
- const parsedChunk = JSON.parse(newChunk);
2087
- controller.enqueue(parsedChunk);
2088
- failedChunk = void 0;
2089
- } catch {
2090
- failedChunk = newChunk;
2091
- }
2092
- }
2093
- }
2094
- } catch {
2095
- }
2096
- }
2097
- });
2098
- return response.body.pipeThrough(transformStream);
2099
- }
2100
- /**
2101
- * Creates a new ReadableStream from an iterable or async iterable of objects,
2102
- * serializing each as JSON and separating them with the record separator (\x1E).
2103
- *
2104
- * @param records - An iterable or async iterable of objects to stream
2105
- * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2106
- */
2107
- static createRecordStream(records) {
2108
- const encoder = new TextEncoder();
2109
- return new ReadableStream({
2110
- async start(controller) {
2111
- try {
2112
- for await (const record of records) {
2113
- const json = JSON.stringify(record) + RECORD_SEPARATOR;
2114
- controller.enqueue(encoder.encode(json));
2115
- }
2116
- controller.close();
2117
- } catch (err) {
2118
- controller.error(err);
2119
- }
2120
- }
2121
- });
2909
+ return response.body.pipeThrough(this.createChunkTransformStream());
2122
2910
  }
2123
2911
  /**
2124
2912
  * Restarts an active workflow run synchronously without waiting for the workflow to complete
2125
- * @param params - Object containing the runId and requestContext
2913
+ * @param params - Object containing the requestContext
2126
2914
  * @returns Promise containing success message
2127
2915
  */
2128
2916
  restart(params) {
2129
2917
  const requestContext = parseClientRequestContext(params.requestContext);
2130
- return this.request(`/api/workflows/${this.workflowId}/restart?runId=${params.runId}`, {
2918
+ return this.request(`/api/workflows/${this.workflowId}/restart?runId=${this.runId}`, {
2131
2919
  method: "POST",
2132
2920
  body: {
2133
2921
  requestContext,
@@ -2137,49 +2925,27 @@ var Workflow = class extends BaseResource {
2137
2925
  }
2138
2926
  /**
2139
2927
  * Restarts an active workflow run asynchronously
2140
- * @param params - Object containing the runId and requestContext
2928
+ * @param params - optional object containing the requestContext
2141
2929
  * @returns Promise containing the workflow restart results
2142
2930
  */
2143
2931
  restartAsync(params) {
2144
- const requestContext = parseClientRequestContext(params.requestContext);
2145
- return this.request(`/api/workflows/${this.workflowId}/restart-async?runId=${params.runId}`, {
2932
+ const requestContext = parseClientRequestContext(params?.requestContext);
2933
+ return this.request(`/api/workflows/${this.workflowId}/restart-async?runId=${this.runId}`, {
2146
2934
  method: "POST",
2147
2935
  body: {
2148
2936
  requestContext,
2149
- tracingOptions: params.tracingOptions
2937
+ tracingOptions: params?.tracingOptions
2150
2938
  }
2151
- });
2152
- }
2153
- /**
2154
- * Restart all active workflow runs synchronously without waiting for the workflow to complete
2155
- * @returns Promise containing success message
2156
- */
2157
- restartAllActiveWorkflowRuns() {
2158
- return this.request(`/api/workflows/${this.workflowId}/restart-all-active-workflow-runs`, {
2159
- method: "POST"
2160
- });
2161
- }
2162
- /**
2163
- * Restart all active workflow runs asynchronously
2164
- * @returns Promise containing success message
2165
- */
2166
- restartAllActiveWorkflowRunsAsync() {
2167
- return this.request(`/api/workflows/${this.workflowId}/restart-all-active-workflow-runs-async`, {
2168
- method: "POST"
2169
- });
2939
+ }).then(deserializeWorkflowError);
2170
2940
  }
2171
2941
  /**
2172
2942
  * Time travels a workflow run synchronously without waiting for the workflow to complete
2173
- * @param params - Object containing the runId, step, inputData, resumeData, initialState, context, nestedStepsContext, requestContext and tracingOptions
2943
+ * @param params - Object containing the step, inputData, resumeData, initialState, context, nestedStepsContext, requestContext and tracingOptions
2174
2944
  * @returns Promise containing success message
2175
2945
  */
2176
- timeTravel({
2177
- runId,
2178
- requestContext: paramsRequestContext,
2179
- ...params
2180
- }) {
2946
+ timeTravel({ requestContext: paramsRequestContext, ...params }) {
2181
2947
  const requestContext = parseClientRequestContext(paramsRequestContext);
2182
- return this.request(`/api/workflows/${this.workflowId}/time-travel?runId=${runId}`, {
2948
+ return this.request(`/api/workflows/${this.workflowId}/time-travel?runId=${this.runId}`, {
2183
2949
  method: "POST",
2184
2950
  body: {
2185
2951
  ...params,
@@ -2189,32 +2955,28 @@ var Workflow = class extends BaseResource {
2189
2955
  }
2190
2956
  /**
2191
2957
  * Time travels a workflow run asynchronously
2192
- * @param params - Object containing the runId, step, inputData, resumeData, initialState, context, nestedStepsContext, requestContext and tracingOptions
2958
+ * @param params - Object containing the step, inputData, resumeData, initialState, context, nestedStepsContext, requestContext and tracingOptions
2193
2959
  * @returns Promise containing the workflow time travel results
2194
2960
  */
2195
- timeTravelAsync({
2196
- runId,
2197
- requestContext: paramsRequestContext,
2198
- ...params
2199
- }) {
2961
+ timeTravelAsync({ requestContext: paramsRequestContext, ...params }) {
2200
2962
  const requestContext = parseClientRequestContext(paramsRequestContext);
2201
- return this.request(`/api/workflows/${this.workflowId}/time-travel-async?runId=${runId}`, {
2963
+ return this.request(`/api/workflows/${this.workflowId}/time-travel-async?runId=${this.runId}`, {
2202
2964
  method: "POST",
2203
2965
  body: {
2204
2966
  ...params,
2205
2967
  requestContext
2206
2968
  }
2207
- });
2969
+ }).then(deserializeWorkflowError);
2208
2970
  }
2209
2971
  /**
2210
2972
  * Time travels a workflow run and returns a stream
2211
- * @param params - Object containing the runId, step, inputData, resumeData, initialState, context, nestedStepsContext, requestContext and tracingOptions
2973
+ * @param params - Object containing the step, inputData, resumeData, initialState, context, nestedStepsContext, requestContext and tracingOptions
2212
2974
  * @returns Promise containing the workflow execution results
2213
2975
  */
2214
- async timeTravelStream({ runId, requestContext: paramsRequestContext, ...params }) {
2976
+ async timeTravelStream({ requestContext: paramsRequestContext, ...params }) {
2215
2977
  const requestContext = parseClientRequestContext(paramsRequestContext);
2216
2978
  const response = await this.request(
2217
- `/api/workflows/${this.workflowId}/time-travel-stream?runId=${runId}`,
2979
+ `/api/workflows/${this.workflowId}/time-travel-stream?runId=${this.runId}`,
2218
2980
  {
2219
2981
  method: "POST",
2220
2982
  body: {
@@ -2230,31 +2992,146 @@ var Workflow = class extends BaseResource {
2230
2992
  if (!response.body) {
2231
2993
  throw new Error("Response body is null");
2232
2994
  }
2233
- let failedChunk = void 0;
2234
- const transformStream = new TransformStream({
2235
- start() {
2236
- },
2237
- async transform(chunk, controller) {
2995
+ return response.body.pipeThrough(this.createChunkTransformStream());
2996
+ }
2997
+ };
2998
+
2999
+ // src/resources/workflow.ts
3000
+ var RECORD_SEPARATOR2 = "";
3001
+ var Workflow = class extends BaseResource {
3002
+ constructor(options, workflowId) {
3003
+ super(options);
3004
+ this.workflowId = workflowId;
3005
+ }
3006
+ /**
3007
+ * Retrieves details about the workflow
3008
+ * @param requestContext - Optional request context to pass as query parameter
3009
+ * @returns Promise containing workflow details including steps and graphs
3010
+ */
3011
+ details(requestContext) {
3012
+ return this.request(`/api/workflows/${this.workflowId}${requestContextQueryString(requestContext)}`);
3013
+ }
3014
+ /**
3015
+ * Retrieves all runs for a workflow
3016
+ * @param params - Parameters for filtering runs
3017
+ * @param requestContext - Optional request context to pass as query parameter
3018
+ * @returns Promise containing workflow runs array
3019
+ */
3020
+ runs(params, requestContext) {
3021
+ const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
3022
+ const searchParams = new URLSearchParams();
3023
+ if (params?.fromDate) {
3024
+ searchParams.set("fromDate", params.fromDate.toISOString());
3025
+ }
3026
+ if (params?.toDate) {
3027
+ searchParams.set("toDate", params.toDate.toISOString());
3028
+ }
3029
+ if (params?.page !== void 0) {
3030
+ searchParams.set("page", String(params.page));
3031
+ }
3032
+ if (params?.perPage !== void 0) {
3033
+ searchParams.set("perPage", String(params.perPage));
3034
+ }
3035
+ if (params?.limit !== null && params?.limit !== void 0) {
3036
+ if (params.limit === false) {
3037
+ searchParams.set("limit", "false");
3038
+ } else if (typeof params.limit === "number" && params.limit > 0 && Number.isInteger(params.limit)) {
3039
+ searchParams.set("limit", String(params.limit));
3040
+ }
3041
+ }
3042
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
3043
+ searchParams.set("offset", String(params.offset));
3044
+ }
3045
+ if (params?.resourceId) {
3046
+ searchParams.set("resourceId", params.resourceId);
3047
+ }
3048
+ if (params?.status) {
3049
+ searchParams.set("status", params.status);
3050
+ }
3051
+ if (requestContextParam) {
3052
+ searchParams.set("requestContext", requestContextParam);
3053
+ }
3054
+ if (searchParams.size) {
3055
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
3056
+ } else {
3057
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
3058
+ }
3059
+ }
3060
+ /**
3061
+ * Retrieves a specific workflow run by its ID
3062
+ * @param runId - The ID of the workflow run to retrieve
3063
+ * @param requestContext - Optional request context to pass as query parameter
3064
+ * @returns Promise containing the workflow run details
3065
+ */
3066
+ runById(runId, requestContext) {
3067
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${requestContextQueryString(requestContext)}`);
3068
+ }
3069
+ /**
3070
+ * Deletes a specific workflow run by its ID
3071
+ * @param runId - The ID of the workflow run to delete
3072
+ * @returns Promise containing a success message
3073
+ */
3074
+ deleteRunById(runId) {
3075
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`, {
3076
+ method: "DELETE"
3077
+ });
3078
+ }
3079
+ /**
3080
+ * Retrieves the execution result for a specific workflow run by its ID
3081
+ * @param runId - The ID of the workflow run to retrieve the execution result for
3082
+ * @param requestContext - Optional request context to pass as query parameter
3083
+ * @returns Promise containing the workflow run execution result
3084
+ */
3085
+ runExecutionResult(runId, requestContext) {
3086
+ return this.request(
3087
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${requestContextQueryString(requestContext)}`
3088
+ );
3089
+ }
3090
+ /**
3091
+ * Creates a new workflow run
3092
+ * @param params - Optional object containing the optional runId
3093
+ * @returns Promise containing the Run instance
3094
+ */
3095
+ async createRun(params) {
3096
+ const searchParams = new URLSearchParams();
3097
+ if (!!params?.runId) {
3098
+ searchParams.set("runId", params.runId);
3099
+ }
3100
+ const res = await this.request(
3101
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
3102
+ {
3103
+ method: "POST",
3104
+ body: {
3105
+ resourceId: params?.resourceId,
3106
+ disableScorers: params?.disableScorers
3107
+ }
3108
+ }
3109
+ );
3110
+ const run = new Run(this.options, this.workflowId, res.runId);
3111
+ return run;
3112
+ }
3113
+ /**
3114
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
3115
+ * serializing each as JSON and separating them with the record separator (\x1E).
3116
+ *
3117
+ * @param records - An iterable or async iterable of objects to stream
3118
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
3119
+ */
3120
+ static createRecordStream(records) {
3121
+ const encoder = new TextEncoder();
3122
+ return new ReadableStream({
3123
+ async start(controller) {
2238
3124
  try {
2239
- const decoded = new TextDecoder().decode(chunk);
2240
- const chunks = decoded.split(RECORD_SEPARATOR);
2241
- for (const chunk2 of chunks) {
2242
- if (chunk2) {
2243
- const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2244
- try {
2245
- const parsedChunk = JSON.parse(newChunk);
2246
- controller.enqueue(parsedChunk);
2247
- failedChunk = void 0;
2248
- } catch {
2249
- failedChunk = newChunk;
2250
- }
2251
- }
3125
+ for await (const record of records) {
3126
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
3127
+ controller.enqueue(encoder.encode(json));
2252
3128
  }
2253
- } catch {
3129
+ controller.close();
3130
+ } catch (err) {
3131
+ controller.error(err);
2254
3132
  }
2255
3133
  }
2256
3134
  });
2257
- return response.body.pipeThrough(transformStream);
2258
3135
  }
2259
3136
  };
2260
3137
 
@@ -2370,7 +3247,7 @@ var MCPTool = class extends BaseResource {
2370
3247
  };
2371
3248
 
2372
3249
  // src/resources/agent-builder.ts
2373
- var RECORD_SEPARATOR2 = "";
3250
+ var RECORD_SEPARATOR3 = "";
2374
3251
  var AgentBuilder = class extends BaseResource {
2375
3252
  constructor(options, actionId) {
2376
3253
  super(options);
@@ -2416,7 +3293,7 @@ var AgentBuilder = class extends BaseResource {
2416
3293
  async transform(chunk, controller) {
2417
3294
  try {
2418
3295
  const decoded = new TextDecoder().decode(chunk);
2419
- const chunks = decoded.split(RECORD_SEPARATOR2);
3296
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2420
3297
  for (const chunk2 of chunks) {
2421
3298
  if (chunk2) {
2422
3299
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2530,7 +3407,7 @@ var AgentBuilder = class extends BaseResource {
2530
3407
  if (done && !value) continue;
2531
3408
  try {
2532
3409
  const decoded = value ? new TextDecoder().decode(value) : "";
2533
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
3410
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2534
3411
  buffer = chunks.pop() || "";
2535
3412
  for (const chunk of chunks) {
2536
3413
  if (chunk) {
@@ -2791,7 +3668,7 @@ var Observability = class extends BaseResource {
2791
3668
  getTraces(params) {
2792
3669
  const { pagination, filters } = params;
2793
3670
  const { page, perPage, dateRange } = pagination || {};
2794
- const { name, spanType, entityId, entityType } = filters || {};
3671
+ const { name: name14, spanType, entityId, entityType } = filters || {};
2795
3672
  const searchParams = new URLSearchParams();
2796
3673
  if (page !== void 0) {
2797
3674
  searchParams.set("page", String(page));
@@ -2799,8 +3676,8 @@ var Observability = class extends BaseResource {
2799
3676
  if (perPage !== void 0) {
2800
3677
  searchParams.set("perPage", String(perPage));
2801
3678
  }
2802
- if (name) {
2803
- searchParams.set("name", name);
3679
+ if (name14) {
3680
+ searchParams.set("name", name14);
2804
3681
  }
2805
3682
  if (spanType !== void 0) {
2806
3683
  searchParams.set("spanType", String(spanType));