@mastra/client-js 0.0.0-message-ordering-20250415215612 → 0.0.0-message-file-url-handling-fix-20250904234524

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +1908 -3
  2. package/LICENSE.md +11 -42
  3. package/README.md +7 -4
  4. package/dist/client.d.ts +280 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/example.d.ts +2 -0
  7. package/dist/example.d.ts.map +1 -0
  8. package/dist/index.cjs +2597 -106
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +4 -585
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +2574 -87
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources/a2a.d.ts +41 -0
  15. package/dist/resources/a2a.d.ts.map +1 -0
  16. package/dist/resources/agent-builder.d.ts +161 -0
  17. package/dist/resources/agent-builder.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +155 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +13 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/legacy-workflow.d.ts +87 -0
  25. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  26. package/dist/resources/mcp-tool.d.ts +27 -0
  27. package/dist/resources/mcp-tool.d.ts.map +1 -0
  28. package/dist/resources/memory-thread.d.ts +53 -0
  29. package/dist/resources/memory-thread.d.ts.map +1 -0
  30. package/dist/resources/network-memory-thread.d.ts +47 -0
  31. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  32. package/dist/resources/network.d.ts +30 -0
  33. package/dist/resources/network.d.ts.map +1 -0
  34. package/dist/resources/observability.d.ts +19 -0
  35. package/dist/resources/observability.d.ts.map +1 -0
  36. package/dist/resources/tool.d.ts +23 -0
  37. package/dist/resources/tool.d.ts.map +1 -0
  38. package/dist/resources/vNextNetwork.d.ts +42 -0
  39. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  40. package/dist/resources/vector.d.ts +48 -0
  41. package/dist/resources/vector.d.ts.map +1 -0
  42. package/dist/resources/workflow.d.ts +154 -0
  43. package/dist/resources/workflow.d.ts.map +1 -0
  44. package/dist/types.d.ts +461 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/utils/index.d.ts +3 -0
  47. package/dist/utils/index.d.ts.map +1 -0
  48. package/dist/utils/process-client-tools.d.ts +3 -0
  49. package/dist/utils/process-client-tools.d.ts.map +1 -0
  50. package/dist/utils/process-mastra-stream.d.ts +7 -0
  51. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  52. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  53. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  54. package/package.json +41 -18
  55. package/dist/index.d.cts +0 -585
  56. package/eslint.config.js +0 -6
  57. package/src/client.ts +0 -223
  58. package/src/example.ts +0 -65
  59. package/src/index.test.ts +0 -710
  60. package/src/index.ts +0 -2
  61. package/src/resources/agent.ts +0 -205
  62. package/src/resources/base.ts +0 -70
  63. package/src/resources/index.ts +0 -7
  64. package/src/resources/memory-thread.ts +0 -60
  65. package/src/resources/network.ts +0 -92
  66. package/src/resources/tool.ts +0 -32
  67. package/src/resources/vector.ts +0 -83
  68. package/src/resources/workflow.ts +0 -215
  69. package/src/types.ts +0 -224
  70. package/tsconfig.json +0 -5
  71. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,10 +1,104 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
- var zodToJsonSchema = require('zod-to-json-schema');
5
3
  var uiUtils = require('@ai-sdk/ui-utils');
4
+ var uuid = require('@lukeed/uuid');
5
+ var runtimeContext = require('@mastra/core/runtime-context');
6
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
7
+ var zod = require('zod');
8
+ var originalZodToJsonSchema = require('zod-to-json-schema');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
6
13
 
7
14
  // src/resources/agent.ts
15
+ function parseClientRuntimeContext(runtimeContext$1) {
16
+ if (runtimeContext$1) {
17
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
18
+ return Object.fromEntries(runtimeContext$1.entries());
19
+ }
20
+ return runtimeContext$1;
21
+ }
22
+ return void 0;
23
+ }
24
+ function isZodType(value) {
25
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
26
+ }
27
+ function zodToJsonSchema(zodSchema) {
28
+ if (!isZodType(zodSchema)) {
29
+ return zodSchema;
30
+ }
31
+ if ("toJSONSchema" in zod.z) {
32
+ const fn = "toJSONSchema";
33
+ return zod.z[fn].call(zod.z, zodSchema);
34
+ }
35
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
36
+ }
37
+
38
+ // src/utils/process-client-tools.ts
39
+ function processClientTools(clientTools) {
40
+ if (!clientTools) {
41
+ return void 0;
42
+ }
43
+ return Object.fromEntries(
44
+ Object.entries(clientTools).map(([key, value]) => {
45
+ if (isVercelTool.isVercelTool(value)) {
46
+ return [
47
+ key,
48
+ {
49
+ ...value,
50
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
51
+ }
52
+ ];
53
+ } else {
54
+ return [
55
+ key,
56
+ {
57
+ ...value,
58
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
59
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
60
+ }
61
+ ];
62
+ }
63
+ })
64
+ );
65
+ }
66
+
67
+ // src/utils/process-mastra-stream.ts
68
+ async function processMastraStream({
69
+ stream,
70
+ onChunk
71
+ }) {
72
+ const reader = stream.getReader();
73
+ const decoder = new TextDecoder();
74
+ let buffer = "";
75
+ try {
76
+ while (true) {
77
+ const { done, value } = await reader.read();
78
+ if (done) break;
79
+ buffer += decoder.decode(value, { stream: true });
80
+ const lines = buffer.split("\n\n");
81
+ buffer = lines.pop() || "";
82
+ for (const line of lines) {
83
+ if (line.startsWith("data: ")) {
84
+ const data = line.slice(6);
85
+ if (data === "[DONE]") {
86
+ console.log("\u{1F3C1} Stream finished");
87
+ return;
88
+ }
89
+ try {
90
+ const json = JSON.parse(data);
91
+ await onChunk(json);
92
+ } catch (error) {
93
+ console.error("\u274C JSON parse error:", error, "Data:", data);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ } finally {
99
+ reader.releaseLock();
100
+ }
101
+ }
8
102
 
9
103
  // src/resources/base.ts
10
104
  var BaseResource = class {
@@ -20,18 +114,21 @@ var BaseResource = class {
20
114
  */
21
115
  async request(path, options = {}) {
22
116
  let lastError = null;
23
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
117
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
24
118
  let delay = backoffMs;
25
119
  for (let attempt = 0; attempt <= retries; attempt++) {
26
120
  try {
27
- const response = await fetch(`${baseUrl}${path}`, {
121
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
28
122
  ...options,
29
123
  headers: {
124
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
30
125
  ...headers,
31
126
  ...options.headers
32
127
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
33
128
  // 'x-mastra-client-type': 'js',
34
129
  },
130
+ signal: this.options.abortSignal,
131
+ credentials: options.credentials ?? credentials,
35
132
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
36
133
  });
37
134
  if (!response.ok) {
@@ -66,6 +163,63 @@ var BaseResource = class {
66
163
  };
67
164
 
68
165
  // src/resources/agent.ts
166
+ async function executeToolCallAndRespond({
167
+ response,
168
+ params,
169
+ runId,
170
+ resourceId,
171
+ threadId,
172
+ runtimeContext,
173
+ respondFn
174
+ }) {
175
+ if (response.finishReason === "tool-calls") {
176
+ const toolCalls = response.toolCalls;
177
+ if (!toolCalls || !Array.isArray(toolCalls)) {
178
+ return response;
179
+ }
180
+ for (const toolCall of toolCalls) {
181
+ const clientTool = params.clientTools?.[toolCall.toolName];
182
+ if (clientTool && clientTool.execute) {
183
+ const result = await clientTool.execute(
184
+ {
185
+ context: toolCall?.args,
186
+ runId,
187
+ resourceId,
188
+ threadId,
189
+ runtimeContext,
190
+ tracingContext: { currentSpan: void 0 }
191
+ },
192
+ {
193
+ messages: response.messages,
194
+ toolCallId: toolCall?.toolCallId
195
+ }
196
+ );
197
+ const updatedMessages = [
198
+ {
199
+ role: "user",
200
+ content: params.messages
201
+ },
202
+ ...response.response.messages,
203
+ {
204
+ role: "tool",
205
+ content: [
206
+ {
207
+ type: "tool-result",
208
+ toolCallId: toolCall.toolCallId,
209
+ toolName: toolCall.toolName,
210
+ result
211
+ }
212
+ ]
213
+ }
214
+ ];
215
+ return respondFn({
216
+ ...params,
217
+ messages: updatedMessages
218
+ });
219
+ }
220
+ }
221
+ }
222
+ }
69
223
  var AgentVoice = class extends BaseResource {
70
224
  constructor(options, agentId) {
71
225
  super(options);
@@ -112,6 +266,13 @@ var AgentVoice = class extends BaseResource {
112
266
  getSpeakers() {
113
267
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
114
268
  }
269
+ /**
270
+ * Get the listener configuration for the agent's voice provider
271
+ * @returns Promise containing a check if the agent has listening capabilities
272
+ */
273
+ getListener() {
274
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
275
+ }
115
276
  };
116
277
  var Agent = class extends BaseResource {
117
278
  constructor(options, agentId) {
@@ -127,21 +288,366 @@ var Agent = class extends BaseResource {
127
288
  details() {
128
289
  return this.request(`/api/agents/${this.agentId}`);
129
290
  }
130
- /**
131
- * Generates a response from the agent
132
- * @param params - Generation parameters including prompt
133
- * @returns Promise containing the generated response
134
- */
135
- generate(params) {
291
+ async generate(params) {
292
+ console.warn(
293
+ "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th. Please use generateLegacy if you don't want to upgrade just yet."
294
+ );
295
+ return this.generateLegacy(params);
296
+ }
297
+ async generateLegacy(params) {
136
298
  const processedParams = {
137
299
  ...params,
138
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
139
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
300
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
301
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
302
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
303
+ clientTools: processClientTools(params.clientTools)
140
304
  };
141
- return this.request(`/api/agents/${this.agentId}/generate`, {
142
- method: "POST",
143
- body: processedParams
305
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
306
+ const response = await this.request(
307
+ `/api/agents/${this.agentId}/generate-legacy`,
308
+ {
309
+ method: "POST",
310
+ body: processedParams
311
+ }
312
+ );
313
+ if (response.finishReason === "tool-calls") {
314
+ const toolCalls = response.toolCalls;
315
+ if (!toolCalls || !Array.isArray(toolCalls)) {
316
+ return response;
317
+ }
318
+ for (const toolCall of toolCalls) {
319
+ const clientTool = params.clientTools?.[toolCall.toolName];
320
+ if (clientTool && clientTool.execute) {
321
+ const result = await clientTool.execute(
322
+ {
323
+ context: toolCall?.args,
324
+ runId,
325
+ resourceId,
326
+ threadId,
327
+ runtimeContext,
328
+ tracingContext: { currentSpan: void 0 }
329
+ },
330
+ {
331
+ messages: response.messages,
332
+ toolCallId: toolCall?.toolCallId
333
+ }
334
+ );
335
+ const updatedMessages = [
336
+ {
337
+ role: "user",
338
+ content: params.messages
339
+ },
340
+ ...response.response.messages,
341
+ {
342
+ role: "tool",
343
+ content: [
344
+ {
345
+ type: "tool-result",
346
+ toolCallId: toolCall.toolCallId,
347
+ toolName: toolCall.toolName,
348
+ result
349
+ }
350
+ ]
351
+ }
352
+ ];
353
+ return this.generate({
354
+ ...params,
355
+ messages: updatedMessages
356
+ });
357
+ }
358
+ }
359
+ }
360
+ return response;
361
+ }
362
+ async generateVNext(params) {
363
+ const processedParams = {
364
+ ...params,
365
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
366
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
367
+ clientTools: processClientTools(params.clientTools)
368
+ };
369
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
370
+ const response = await this.request(
371
+ `/api/agents/${this.agentId}/generate/vnext`,
372
+ {
373
+ method: "POST",
374
+ body: processedParams
375
+ }
376
+ );
377
+ if (response.finishReason === "tool-calls") {
378
+ return executeToolCallAndRespond({
379
+ response,
380
+ params,
381
+ runId,
382
+ resourceId,
383
+ threadId,
384
+ runtimeContext,
385
+ respondFn: this.generateVNext.bind(this)
386
+ });
387
+ }
388
+ return response;
389
+ }
390
+ async processChatResponse({
391
+ stream,
392
+ update,
393
+ onToolCall,
394
+ onFinish,
395
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
396
+ lastMessage
397
+ }) {
398
+ const replaceLastMessage = lastMessage?.role === "assistant";
399
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
400
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
401
+ return Math.max(max, toolInvocation.step ?? 0);
402
+ }, 0) ?? 0) : 0;
403
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
404
+ id: uuid.v4(),
405
+ createdAt: getCurrentDate(),
406
+ role: "assistant",
407
+ content: "",
408
+ parts: []
409
+ };
410
+ let currentTextPart = void 0;
411
+ let currentReasoningPart = void 0;
412
+ let currentReasoningTextDetail = void 0;
413
+ function updateToolInvocationPart(toolCallId, invocation) {
414
+ const part = message.parts.find(
415
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
416
+ );
417
+ if (part != null) {
418
+ part.toolInvocation = invocation;
419
+ } else {
420
+ message.parts.push({
421
+ type: "tool-invocation",
422
+ toolInvocation: invocation
423
+ });
424
+ }
425
+ }
426
+ const data = [];
427
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
428
+ const partialToolCalls = {};
429
+ let usage = {
430
+ completionTokens: NaN,
431
+ promptTokens: NaN,
432
+ totalTokens: NaN
433
+ };
434
+ let finishReason = "unknown";
435
+ function execUpdate() {
436
+ const copiedData = [...data];
437
+ if (messageAnnotations?.length) {
438
+ message.annotations = messageAnnotations;
439
+ }
440
+ const copiedMessage = {
441
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
442
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
443
+ ...structuredClone(message),
444
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
445
+ // hashing approach by default to detect changes, but it only works for shallow
446
+ // changes. This is why we need to add a revision id to ensure that the message
447
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
448
+ // forwarded to rendering):
449
+ revisionId: uuid.v4()
450
+ };
451
+ update({
452
+ message: copiedMessage,
453
+ data: copiedData,
454
+ replaceLastMessage
455
+ });
456
+ }
457
+ await uiUtils.processDataStream({
458
+ stream,
459
+ onTextPart(value) {
460
+ if (currentTextPart == null) {
461
+ currentTextPart = {
462
+ type: "text",
463
+ text: value
464
+ };
465
+ message.parts.push(currentTextPart);
466
+ } else {
467
+ currentTextPart.text += value;
468
+ }
469
+ message.content += value;
470
+ execUpdate();
471
+ },
472
+ onReasoningPart(value) {
473
+ if (currentReasoningTextDetail == null) {
474
+ currentReasoningTextDetail = { type: "text", text: value };
475
+ if (currentReasoningPart != null) {
476
+ currentReasoningPart.details.push(currentReasoningTextDetail);
477
+ }
478
+ } else {
479
+ currentReasoningTextDetail.text += value;
480
+ }
481
+ if (currentReasoningPart == null) {
482
+ currentReasoningPart = {
483
+ type: "reasoning",
484
+ reasoning: value,
485
+ details: [currentReasoningTextDetail]
486
+ };
487
+ message.parts.push(currentReasoningPart);
488
+ } else {
489
+ currentReasoningPart.reasoning += value;
490
+ }
491
+ message.reasoning = (message.reasoning ?? "") + value;
492
+ execUpdate();
493
+ },
494
+ onReasoningSignaturePart(value) {
495
+ if (currentReasoningTextDetail != null) {
496
+ currentReasoningTextDetail.signature = value.signature;
497
+ }
498
+ },
499
+ onRedactedReasoningPart(value) {
500
+ if (currentReasoningPart == null) {
501
+ currentReasoningPart = {
502
+ type: "reasoning",
503
+ reasoning: "",
504
+ details: []
505
+ };
506
+ message.parts.push(currentReasoningPart);
507
+ }
508
+ currentReasoningPart.details.push({
509
+ type: "redacted",
510
+ data: value.data
511
+ });
512
+ currentReasoningTextDetail = void 0;
513
+ execUpdate();
514
+ },
515
+ onFilePart(value) {
516
+ message.parts.push({
517
+ type: "file",
518
+ mimeType: value.mimeType,
519
+ data: value.data
520
+ });
521
+ execUpdate();
522
+ },
523
+ onSourcePart(value) {
524
+ message.parts.push({
525
+ type: "source",
526
+ source: value
527
+ });
528
+ execUpdate();
529
+ },
530
+ onToolCallStreamingStartPart(value) {
531
+ if (message.toolInvocations == null) {
532
+ message.toolInvocations = [];
533
+ }
534
+ partialToolCalls[value.toolCallId] = {
535
+ text: "",
536
+ step,
537
+ toolName: value.toolName,
538
+ index: message.toolInvocations.length
539
+ };
540
+ const invocation = {
541
+ state: "partial-call",
542
+ step,
543
+ toolCallId: value.toolCallId,
544
+ toolName: value.toolName,
545
+ args: void 0
546
+ };
547
+ message.toolInvocations.push(invocation);
548
+ updateToolInvocationPart(value.toolCallId, invocation);
549
+ execUpdate();
550
+ },
551
+ onToolCallDeltaPart(value) {
552
+ const partialToolCall = partialToolCalls[value.toolCallId];
553
+ partialToolCall.text += value.argsTextDelta;
554
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
555
+ const invocation = {
556
+ state: "partial-call",
557
+ step: partialToolCall.step,
558
+ toolCallId: value.toolCallId,
559
+ toolName: partialToolCall.toolName,
560
+ args: partialArgs
561
+ };
562
+ message.toolInvocations[partialToolCall.index] = invocation;
563
+ updateToolInvocationPart(value.toolCallId, invocation);
564
+ execUpdate();
565
+ },
566
+ async onToolCallPart(value) {
567
+ const invocation = {
568
+ state: "call",
569
+ step,
570
+ ...value
571
+ };
572
+ if (partialToolCalls[value.toolCallId] != null) {
573
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
574
+ } else {
575
+ if (message.toolInvocations == null) {
576
+ message.toolInvocations = [];
577
+ }
578
+ message.toolInvocations.push(invocation);
579
+ }
580
+ updateToolInvocationPart(value.toolCallId, invocation);
581
+ execUpdate();
582
+ if (onToolCall) {
583
+ const result = await onToolCall({ toolCall: value });
584
+ if (result != null) {
585
+ const invocation2 = {
586
+ state: "result",
587
+ step,
588
+ ...value,
589
+ result
590
+ };
591
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
592
+ updateToolInvocationPart(value.toolCallId, invocation2);
593
+ execUpdate();
594
+ }
595
+ }
596
+ },
597
+ onToolResultPart(value) {
598
+ const toolInvocations = message.toolInvocations;
599
+ if (toolInvocations == null) {
600
+ throw new Error("tool_result must be preceded by a tool_call");
601
+ }
602
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
603
+ if (toolInvocationIndex === -1) {
604
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
605
+ }
606
+ const invocation = {
607
+ ...toolInvocations[toolInvocationIndex],
608
+ state: "result",
609
+ ...value
610
+ };
611
+ toolInvocations[toolInvocationIndex] = invocation;
612
+ updateToolInvocationPart(value.toolCallId, invocation);
613
+ execUpdate();
614
+ },
615
+ onDataPart(value) {
616
+ data.push(...value);
617
+ execUpdate();
618
+ },
619
+ onMessageAnnotationsPart(value) {
620
+ if (messageAnnotations == null) {
621
+ messageAnnotations = [...value];
622
+ } else {
623
+ messageAnnotations.push(...value);
624
+ }
625
+ execUpdate();
626
+ },
627
+ onFinishStepPart(value) {
628
+ step += 1;
629
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
630
+ currentReasoningPart = void 0;
631
+ currentReasoningTextDetail = void 0;
632
+ },
633
+ onStartStepPart(value) {
634
+ if (!replaceLastMessage) {
635
+ message.id = value.messageId;
636
+ }
637
+ message.parts.push({ type: "step-start" });
638
+ execUpdate();
639
+ },
640
+ onFinishMessagePart(value) {
641
+ finishReason = value.finishReason;
642
+ if (value.usage != null) {
643
+ usage = value.usage;
644
+ }
645
+ },
646
+ onErrorPart(error) {
647
+ throw new Error(error);
648
+ }
144
649
  });
650
+ onFinish?.({ message, finishReason, usage });
145
651
  }
146
652
  /**
147
653
  * Streams a response from the agent
@@ -149,12 +655,294 @@ var Agent = class extends BaseResource {
149
655
  * @returns Promise containing the enhanced Response object with processDataStream method
150
656
  */
151
657
  async stream(params) {
658
+ console.warn(
659
+ "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th. Please use streamLegacy if you don't want to upgrade just yet."
660
+ );
661
+ return this.streamLegacy(params);
662
+ }
663
+ /**
664
+ * Streams a response from the agent
665
+ * @param params - Stream parameters including prompt
666
+ * @returns Promise containing the enhanced Response object with processDataStream method
667
+ */
668
+ async streamLegacy(params) {
152
669
  const processedParams = {
153
670
  ...params,
154
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
155
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
671
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
672
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
673
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
674
+ clientTools: processClientTools(params.clientTools)
675
+ };
676
+ const { readable, writable } = new TransformStream();
677
+ const response = await this.processStreamResponse(processedParams, writable);
678
+ const streamResponse = new Response(readable, {
679
+ status: response.status,
680
+ statusText: response.statusText,
681
+ headers: response.headers
682
+ });
683
+ streamResponse.processDataStream = async (options = {}) => {
684
+ await uiUtils.processDataStream({
685
+ stream: streamResponse.body,
686
+ ...options
687
+ });
688
+ };
689
+ return streamResponse;
690
+ }
691
+ async processChatResponse_vNext({
692
+ stream,
693
+ update,
694
+ onToolCall,
695
+ onFinish,
696
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
697
+ lastMessage
698
+ }) {
699
+ const replaceLastMessage = lastMessage?.role === "assistant";
700
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
701
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
702
+ return Math.max(max, toolInvocation.step ?? 0);
703
+ }, 0) ?? 0) : 0;
704
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
705
+ id: uuid.v4(),
706
+ createdAt: getCurrentDate(),
707
+ role: "assistant",
708
+ content: "",
709
+ parts: []
710
+ };
711
+ let currentTextPart = void 0;
712
+ let currentReasoningPart = void 0;
713
+ let currentReasoningTextDetail = void 0;
714
+ function updateToolInvocationPart(toolCallId, invocation) {
715
+ const part = message.parts.find(
716
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
717
+ );
718
+ if (part != null) {
719
+ part.toolInvocation = invocation;
720
+ } else {
721
+ message.parts.push({
722
+ type: "tool-invocation",
723
+ toolInvocation: invocation
724
+ });
725
+ }
726
+ }
727
+ const data = [];
728
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
729
+ const partialToolCalls = {};
730
+ let usage = {
731
+ completionTokens: NaN,
732
+ promptTokens: NaN,
733
+ totalTokens: NaN
156
734
  };
157
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
735
+ let finishReason = "unknown";
736
+ function execUpdate() {
737
+ const copiedData = [...data];
738
+ if (messageAnnotations?.length) {
739
+ message.annotations = messageAnnotations;
740
+ }
741
+ const copiedMessage = {
742
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
743
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
744
+ ...structuredClone(message),
745
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
746
+ // hashing approach by default to detect changes, but it only works for shallow
747
+ // changes. This is why we need to add a revision id to ensure that the message
748
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
749
+ // forwarded to rendering):
750
+ revisionId: uuid.v4()
751
+ };
752
+ update({
753
+ message: copiedMessage,
754
+ data: copiedData,
755
+ replaceLastMessage
756
+ });
757
+ }
758
+ await processMastraStream({
759
+ stream,
760
+ // TODO: casting as any here because the stream types were all typed as any before in core.
761
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
762
+ onChunk: async (chunk) => {
763
+ switch (chunk.type) {
764
+ case "step-start": {
765
+ if (!replaceLastMessage) {
766
+ message.id = chunk.payload.messageId;
767
+ }
768
+ message.parts.push({ type: "step-start" });
769
+ execUpdate();
770
+ break;
771
+ }
772
+ case "text-delta": {
773
+ if (currentTextPart == null) {
774
+ currentTextPart = {
775
+ type: "text",
776
+ text: chunk.payload.text
777
+ };
778
+ message.parts.push(currentTextPart);
779
+ } else {
780
+ currentTextPart.text += chunk.payload.text;
781
+ }
782
+ message.content += chunk.payload.text;
783
+ execUpdate();
784
+ break;
785
+ }
786
+ case "reasoning-delta": {
787
+ if (currentReasoningTextDetail == null) {
788
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
789
+ if (currentReasoningPart != null) {
790
+ currentReasoningPart.details.push(currentReasoningTextDetail);
791
+ }
792
+ } else {
793
+ currentReasoningTextDetail.text += chunk.payload.text;
794
+ }
795
+ if (currentReasoningPart == null) {
796
+ currentReasoningPart = {
797
+ type: "reasoning",
798
+ reasoning: chunk.payload.text,
799
+ details: [currentReasoningTextDetail]
800
+ };
801
+ message.parts.push(currentReasoningPart);
802
+ } else {
803
+ currentReasoningPart.reasoning += chunk.payload.text;
804
+ }
805
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
806
+ execUpdate();
807
+ break;
808
+ }
809
+ case "file": {
810
+ message.parts.push({
811
+ type: "file",
812
+ mimeType: chunk.payload.mimeType,
813
+ data: chunk.payload.data
814
+ });
815
+ execUpdate();
816
+ break;
817
+ }
818
+ case "source": {
819
+ message.parts.push({
820
+ type: "source",
821
+ source: chunk.payload.source
822
+ });
823
+ execUpdate();
824
+ break;
825
+ }
826
+ case "tool-call": {
827
+ const invocation = {
828
+ state: "call",
829
+ step,
830
+ ...chunk.payload
831
+ };
832
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
833
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
834
+ } else {
835
+ if (message.toolInvocations == null) {
836
+ message.toolInvocations = [];
837
+ }
838
+ message.toolInvocations.push(invocation);
839
+ }
840
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
841
+ execUpdate();
842
+ if (onToolCall) {
843
+ const result = await onToolCall({ toolCall: chunk.payload });
844
+ if (result != null) {
845
+ const invocation2 = {
846
+ state: "result",
847
+ step,
848
+ ...chunk.payload,
849
+ result
850
+ };
851
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
852
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
853
+ execUpdate();
854
+ }
855
+ }
856
+ }
857
+ case "tool-call-input-streaming-start": {
858
+ if (message.toolInvocations == null) {
859
+ message.toolInvocations = [];
860
+ }
861
+ partialToolCalls[chunk.payload.toolCallId] = {
862
+ text: "",
863
+ step,
864
+ toolName: chunk.payload.toolName,
865
+ index: message.toolInvocations.length
866
+ };
867
+ const invocation = {
868
+ state: "partial-call",
869
+ step,
870
+ toolCallId: chunk.payload.toolCallId,
871
+ toolName: chunk.payload.toolName,
872
+ args: void 0
873
+ };
874
+ message.toolInvocations.push(invocation);
875
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
876
+ execUpdate();
877
+ break;
878
+ }
879
+ case "tool-call-delta": {
880
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
881
+ partialToolCall.text += chunk.payload.argsTextDelta;
882
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
883
+ const invocation = {
884
+ state: "partial-call",
885
+ step: partialToolCall.step,
886
+ toolCallId: chunk.payload.toolCallId,
887
+ toolName: partialToolCall.toolName,
888
+ args: partialArgs
889
+ };
890
+ message.toolInvocations[partialToolCall.index] = invocation;
891
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
892
+ execUpdate();
893
+ break;
894
+ }
895
+ case "tool-result": {
896
+ const toolInvocations = message.toolInvocations;
897
+ if (toolInvocations == null) {
898
+ throw new Error("tool_result must be preceded by a tool_call");
899
+ }
900
+ const toolInvocationIndex = toolInvocations.findIndex(
901
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
902
+ );
903
+ if (toolInvocationIndex === -1) {
904
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
905
+ }
906
+ const invocation = {
907
+ ...toolInvocations[toolInvocationIndex],
908
+ state: "result",
909
+ ...chunk.payload
910
+ };
911
+ toolInvocations[toolInvocationIndex] = invocation;
912
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
913
+ execUpdate();
914
+ break;
915
+ }
916
+ case "error": {
917
+ throw new Error(chunk.payload.error);
918
+ }
919
+ case "data": {
920
+ data.push(...chunk.payload.data);
921
+ execUpdate();
922
+ break;
923
+ }
924
+ case "step-finish": {
925
+ step += 1;
926
+ currentTextPart = chunk.payload.isContinued ? currentTextPart : void 0;
927
+ currentReasoningPart = void 0;
928
+ currentReasoningTextDetail = void 0;
929
+ execUpdate();
930
+ break;
931
+ }
932
+ case "finish": {
933
+ finishReason = chunk.payload.finishReason;
934
+ if (chunk.payload.usage != null) {
935
+ usage = chunk.payload.usage;
936
+ }
937
+ break;
938
+ }
939
+ }
940
+ }
941
+ });
942
+ onFinish?.({ message, finishReason, usage });
943
+ }
944
+ async processStreamResponse_vNext(processedParams, writable) {
945
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
158
946
  method: "POST",
159
947
  body: processedParams,
160
948
  stream: true
@@ -162,12 +950,244 @@ var Agent = class extends BaseResource {
162
950
  if (!response.body) {
163
951
  throw new Error("No response body");
164
952
  }
165
- response.processDataStream = async (options = {}) => {
166
- await uiUtils.processDataStream({
167
- stream: response.body,
168
- ...options
953
+ try {
954
+ let toolCalls = [];
955
+ let messages = [];
956
+ const [streamForWritable, streamForProcessing] = response.body.tee();
957
+ streamForWritable.pipeTo(writable, {
958
+ preventClose: true
959
+ }).catch((error) => {
960
+ console.error("Error piping to writable stream:", error);
961
+ });
962
+ this.processChatResponse_vNext({
963
+ stream: streamForProcessing,
964
+ update: ({ message }) => {
965
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
966
+ if (existingIndex !== -1) {
967
+ messages[existingIndex] = message;
968
+ } else {
969
+ messages.push(message);
970
+ }
971
+ },
972
+ onFinish: async ({ finishReason, message }) => {
973
+ if (finishReason === "tool-calls") {
974
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
975
+ if (toolCall) {
976
+ toolCalls.push(toolCall);
977
+ }
978
+ for (const toolCall2 of toolCalls) {
979
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
980
+ if (clientTool && clientTool.execute) {
981
+ const result = await clientTool.execute(
982
+ {
983
+ context: toolCall2?.args,
984
+ runId: processedParams.runId,
985
+ resourceId: processedParams.resourceId,
986
+ threadId: processedParams.threadId,
987
+ runtimeContext: processedParams.runtimeContext,
988
+ // TODO: Pass proper tracing context when client-js supports tracing
989
+ tracingContext: { currentSpan: void 0 }
990
+ },
991
+ {
992
+ messages: response.messages,
993
+ toolCallId: toolCall2?.toolCallId
994
+ }
995
+ );
996
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
997
+ const toolInvocationPart = lastMessage?.parts?.find(
998
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
999
+ );
1000
+ if (toolInvocationPart) {
1001
+ toolInvocationPart.toolInvocation = {
1002
+ ...toolInvocationPart.toolInvocation,
1003
+ state: "result",
1004
+ result
1005
+ };
1006
+ }
1007
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1008
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1009
+ );
1010
+ if (toolInvocation) {
1011
+ toolInvocation.state = "result";
1012
+ toolInvocation.result = result;
1013
+ }
1014
+ const writer = writable.getWriter();
1015
+ try {
1016
+ await writer.write(
1017
+ new TextEncoder().encode(
1018
+ "a:" + JSON.stringify({
1019
+ toolCallId: toolCall2.toolCallId,
1020
+ result
1021
+ }) + "\n"
1022
+ )
1023
+ );
1024
+ } finally {
1025
+ writer.releaseLock();
1026
+ }
1027
+ const originalMessages = processedParams.messages;
1028
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1029
+ this.processStreamResponse_vNext(
1030
+ {
1031
+ ...processedParams,
1032
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1033
+ },
1034
+ writable
1035
+ ).catch((error) => {
1036
+ console.error("Error processing stream response:", error);
1037
+ });
1038
+ }
1039
+ }
1040
+ } else {
1041
+ setTimeout(() => {
1042
+ writable.close();
1043
+ }, 0);
1044
+ }
1045
+ },
1046
+ lastMessage: void 0
1047
+ }).catch((error) => {
1048
+ console.error("Error processing stream response:", error);
1049
+ });
1050
+ } catch (error) {
1051
+ console.error("Error processing stream response:", error);
1052
+ }
1053
+ return response;
1054
+ }
1055
+ async streamVNext(params) {
1056
+ const processedParams = {
1057
+ ...params,
1058
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1059
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1060
+ clientTools: processClientTools(params.clientTools)
1061
+ };
1062
+ const { readable, writable } = new TransformStream();
1063
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1064
+ const streamResponse = new Response(readable, {
1065
+ status: response.status,
1066
+ statusText: response.statusText,
1067
+ headers: response.headers
1068
+ });
1069
+ streamResponse.processDataStream = async ({
1070
+ onChunk
1071
+ }) => {
1072
+ await processMastraStream({
1073
+ stream: streamResponse.body,
1074
+ onChunk
169
1075
  });
170
1076
  };
1077
+ return streamResponse;
1078
+ }
1079
+ /**
1080
+ * Processes the stream response and handles tool calls
1081
+ */
1082
+ async processStreamResponse(processedParams, writable) {
1083
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1084
+ method: "POST",
1085
+ body: processedParams,
1086
+ stream: true
1087
+ });
1088
+ if (!response.body) {
1089
+ throw new Error("No response body");
1090
+ }
1091
+ try {
1092
+ let toolCalls = [];
1093
+ let messages = [];
1094
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1095
+ streamForWritable.pipeTo(writable, {
1096
+ preventClose: true
1097
+ }).catch((error) => {
1098
+ console.error("Error piping to writable stream:", error);
1099
+ });
1100
+ this.processChatResponse({
1101
+ stream: streamForProcessing,
1102
+ update: ({ message }) => {
1103
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1104
+ if (existingIndex !== -1) {
1105
+ messages[existingIndex] = message;
1106
+ } else {
1107
+ messages.push(message);
1108
+ }
1109
+ },
1110
+ onFinish: async ({ finishReason, message }) => {
1111
+ if (finishReason === "tool-calls") {
1112
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1113
+ if (toolCall) {
1114
+ toolCalls.push(toolCall);
1115
+ }
1116
+ for (const toolCall2 of toolCalls) {
1117
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1118
+ if (clientTool && clientTool.execute) {
1119
+ const result = await clientTool.execute(
1120
+ {
1121
+ context: toolCall2?.args,
1122
+ runId: processedParams.runId,
1123
+ resourceId: processedParams.resourceId,
1124
+ threadId: processedParams.threadId,
1125
+ runtimeContext: processedParams.runtimeContext,
1126
+ // TODO: Pass proper tracing context when client-js supports tracing
1127
+ tracingContext: { currentSpan: void 0 }
1128
+ },
1129
+ {
1130
+ messages: response.messages,
1131
+ toolCallId: toolCall2?.toolCallId
1132
+ }
1133
+ );
1134
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1135
+ const toolInvocationPart = lastMessage?.parts?.find(
1136
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1137
+ );
1138
+ if (toolInvocationPart) {
1139
+ toolInvocationPart.toolInvocation = {
1140
+ ...toolInvocationPart.toolInvocation,
1141
+ state: "result",
1142
+ result
1143
+ };
1144
+ }
1145
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1146
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1147
+ );
1148
+ if (toolInvocation) {
1149
+ toolInvocation.state = "result";
1150
+ toolInvocation.result = result;
1151
+ }
1152
+ const writer = writable.getWriter();
1153
+ try {
1154
+ await writer.write(
1155
+ new TextEncoder().encode(
1156
+ "a:" + JSON.stringify({
1157
+ toolCallId: toolCall2.toolCallId,
1158
+ result
1159
+ }) + "\n"
1160
+ )
1161
+ );
1162
+ } finally {
1163
+ writer.releaseLock();
1164
+ }
1165
+ const originalMessages = processedParams.messages;
1166
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1167
+ this.processStreamResponse(
1168
+ {
1169
+ ...processedParams,
1170
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1171
+ },
1172
+ writable
1173
+ ).catch((error) => {
1174
+ console.error("Error processing stream response:", error);
1175
+ });
1176
+ }
1177
+ }
1178
+ } else {
1179
+ setTimeout(() => {
1180
+ writable.close();
1181
+ }, 0);
1182
+ }
1183
+ },
1184
+ lastMessage: void 0
1185
+ }).catch((error) => {
1186
+ console.error("Error processing stream response:", error);
1187
+ });
1188
+ } catch (error) {
1189
+ console.error("Error processing stream response:", error);
1190
+ }
171
1191
  return response;
172
1192
  }
173
1193
  /**
@@ -178,6 +1198,22 @@ var Agent = class extends BaseResource {
178
1198
  getTool(toolId) {
179
1199
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
180
1200
  }
1201
+ /**
1202
+ * Executes a tool for the agent
1203
+ * @param toolId - ID of the tool to execute
1204
+ * @param params - Parameters required for tool execution
1205
+ * @returns Promise containing the tool execution results
1206
+ */
1207
+ executeTool(toolId, params) {
1208
+ const body = {
1209
+ data: params.data,
1210
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1211
+ };
1212
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1213
+ method: "POST",
1214
+ body
1215
+ });
1216
+ }
181
1217
  /**
182
1218
  * Retrieves evaluation results for the agent
183
1219
  * @returns Promise containing agent evaluations
@@ -192,6 +1228,17 @@ var Agent = class extends BaseResource {
192
1228
  liveEvals() {
193
1229
  return this.request(`/api/agents/${this.agentId}/evals/live`);
194
1230
  }
1231
+ /**
1232
+ * Updates the model for the agent
1233
+ * @param params - Parameters for updating the model
1234
+ * @returns Promise containing the updated model
1235
+ */
1236
+ updateModel(params) {
1237
+ return this.request(`/api/agents/${this.agentId}/model`, {
1238
+ method: "POST",
1239
+ body: params
1240
+ });
1241
+ }
195
1242
  };
196
1243
  var Network = class extends BaseResource {
197
1244
  constructor(options, networkId) {
@@ -213,8 +1260,8 @@ var Network = class extends BaseResource {
213
1260
  generate(params) {
214
1261
  const processedParams = {
215
1262
  ...params,
216
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
217
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
1263
+ output: zodToJsonSchema(params.output),
1264
+ experimental_output: zodToJsonSchema(params.experimental_output)
218
1265
  };
219
1266
  return this.request(`/api/networks/${this.networkId}/generate`, {
220
1267
  method: "POST",
@@ -229,8 +1276,8 @@ var Network = class extends BaseResource {
229
1276
  async stream(params) {
230
1277
  const processedParams = {
231
1278
  ...params,
232
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
233
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
1279
+ output: zodToJsonSchema(params.output),
1280
+ experimental_output: zodToJsonSchema(params.experimental_output)
234
1281
  };
235
1282
  const response = await this.request(`/api/networks/${this.networkId}/stream`, {
236
1283
  method: "POST",
@@ -286,10 +1333,45 @@ var MemoryThread = class extends BaseResource {
286
1333
  }
287
1334
  /**
288
1335
  * Retrieves messages associated with the thread
1336
+ * @param params - Optional parameters including limit for number of messages to retrieve
289
1337
  * @returns Promise containing thread messages and UI messages
290
1338
  */
291
- getMessages() {
292
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
1339
+ getMessages(params) {
1340
+ const query = new URLSearchParams({
1341
+ agentId: this.agentId,
1342
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1343
+ });
1344
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
1345
+ }
1346
+ /**
1347
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1348
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1349
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1350
+ */
1351
+ getMessagesPaginated({
1352
+ selectBy,
1353
+ ...rest
1354
+ }) {
1355
+ const query = new URLSearchParams({
1356
+ ...rest,
1357
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1358
+ });
1359
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1360
+ }
1361
+ /**
1362
+ * Deletes one or more messages from the thread
1363
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1364
+ * message object with id property, or array of message objects
1365
+ * @returns Promise containing deletion result
1366
+ */
1367
+ deleteMessages(messageIds) {
1368
+ const query = new URLSearchParams({
1369
+ agentId: this.agentId
1370
+ });
1371
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1372
+ method: "POST",
1373
+ body: { messageIds }
1374
+ });
293
1375
  }
294
1376
  };
295
1377
 
@@ -359,34 +1441,50 @@ var Vector = class extends BaseResource {
359
1441
  }
360
1442
  };
361
1443
 
362
- // src/resources/workflow.ts
1444
+ // src/resources/legacy-workflow.ts
363
1445
  var RECORD_SEPARATOR = "";
364
- var Workflow = class extends BaseResource {
1446
+ var LegacyWorkflow = class extends BaseResource {
365
1447
  constructor(options, workflowId) {
366
1448
  super(options);
367
1449
  this.workflowId = workflowId;
368
1450
  }
369
1451
  /**
370
- * Retrieves details about the workflow
371
- * @returns Promise containing workflow details including steps and graphs
1452
+ * Retrieves details about the legacy workflow
1453
+ * @returns Promise containing legacy workflow details including steps and graphs
372
1454
  */
373
1455
  details() {
374
- return this.request(`/api/workflows/${this.workflowId}`);
1456
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
375
1457
  }
376
1458
  /**
377
- * @deprecated Use `startAsync` instead
378
- * Executes the workflow with the provided parameters
379
- * @param params - Parameters required for workflow execution
380
- * @returns Promise containing the workflow execution results
1459
+ * Retrieves all runs for a legacy workflow
1460
+ * @param params - Parameters for filtering runs
1461
+ * @returns Promise containing legacy workflow runs array
381
1462
  */
382
- execute(params) {
383
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
384
- method: "POST",
385
- body: params
386
- });
1463
+ runs(params) {
1464
+ const searchParams = new URLSearchParams();
1465
+ if (params?.fromDate) {
1466
+ searchParams.set("fromDate", params.fromDate.toISOString());
1467
+ }
1468
+ if (params?.toDate) {
1469
+ searchParams.set("toDate", params.toDate.toISOString());
1470
+ }
1471
+ if (params?.limit) {
1472
+ searchParams.set("limit", String(params.limit));
1473
+ }
1474
+ if (params?.offset) {
1475
+ searchParams.set("offset", String(params.offset));
1476
+ }
1477
+ if (params?.resourceId) {
1478
+ searchParams.set("resourceId", params.resourceId);
1479
+ }
1480
+ if (searchParams.size) {
1481
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1482
+ } else {
1483
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1484
+ }
387
1485
  }
388
1486
  /**
389
- * Creates a new workflow run
1487
+ * Creates a new legacy workflow run
390
1488
  * @returns Promise containing the generated run ID
391
1489
  */
392
1490
  createRun(params) {
@@ -394,34 +1492,34 @@ var Workflow = class extends BaseResource {
394
1492
  if (!!params?.runId) {
395
1493
  searchParams.set("runId", params.runId);
396
1494
  }
397
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
1495
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
398
1496
  method: "POST"
399
1497
  });
400
1498
  }
401
1499
  /**
402
- * Starts a workflow run synchronously without waiting for the workflow to complete
1500
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
403
1501
  * @param params - Object containing the runId and triggerData
404
1502
  * @returns Promise containing success message
405
1503
  */
406
1504
  start(params) {
407
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1505
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
408
1506
  method: "POST",
409
1507
  body: params?.triggerData
410
1508
  });
411
1509
  }
412
1510
  /**
413
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1511
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
414
1512
  * @param stepId - ID of the step to resume
415
- * @param runId - ID of the workflow run
416
- * @param context - Context to resume the workflow with
417
- * @returns Promise containing the workflow resume results
1513
+ * @param runId - ID of the legacy workflow run
1514
+ * @param context - Context to resume the legacy workflow with
1515
+ * @returns Promise containing the legacy workflow resume results
418
1516
  */
419
1517
  resume({
420
1518
  stepId,
421
1519
  runId,
422
1520
  context
423
1521
  }) {
424
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1522
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
425
1523
  method: "POST",
426
1524
  body: {
427
1525
  stepId,
@@ -430,41 +1528,1074 @@ var Workflow = class extends BaseResource {
430
1528
  });
431
1529
  }
432
1530
  /**
433
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
434
- * @param params - Object containing the optional runId and triggerData
435
- * @returns Promise containing the workflow execution results
1531
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1532
+ * @param params - Object containing the optional runId and triggerData
1533
+ * @returns Promise containing the workflow execution results
1534
+ */
1535
+ startAsync(params) {
1536
+ const searchParams = new URLSearchParams();
1537
+ if (!!params?.runId) {
1538
+ searchParams.set("runId", params.runId);
1539
+ }
1540
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1541
+ method: "POST",
1542
+ body: params?.triggerData
1543
+ });
1544
+ }
1545
+ /**
1546
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1547
+ * @param params - Object containing the runId, stepId, and context
1548
+ * @returns Promise containing the workflow resume results
1549
+ */
1550
+ resumeAsync(params) {
1551
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1552
+ method: "POST",
1553
+ body: {
1554
+ stepId: params.stepId,
1555
+ context: params.context
1556
+ }
1557
+ });
1558
+ }
1559
+ /**
1560
+ * Creates an async generator that processes a readable stream and yields records
1561
+ * separated by the Record Separator character (\x1E)
1562
+ *
1563
+ * @param stream - The readable stream to process
1564
+ * @returns An async generator that yields parsed records
1565
+ */
1566
+ async *streamProcessor(stream) {
1567
+ const reader = stream.getReader();
1568
+ let doneReading = false;
1569
+ let buffer = "";
1570
+ try {
1571
+ while (!doneReading) {
1572
+ const { done, value } = await reader.read();
1573
+ doneReading = done;
1574
+ if (done && !value) continue;
1575
+ try {
1576
+ const decoded = value ? new TextDecoder().decode(value) : "";
1577
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1578
+ buffer = chunks.pop() || "";
1579
+ for (const chunk of chunks) {
1580
+ if (chunk) {
1581
+ if (typeof chunk === "string") {
1582
+ try {
1583
+ const parsedChunk = JSON.parse(chunk);
1584
+ yield parsedChunk;
1585
+ } catch {
1586
+ }
1587
+ }
1588
+ }
1589
+ }
1590
+ } catch {
1591
+ }
1592
+ }
1593
+ if (buffer) {
1594
+ try {
1595
+ yield JSON.parse(buffer);
1596
+ } catch {
1597
+ }
1598
+ }
1599
+ } finally {
1600
+ reader.cancel().catch(() => {
1601
+ });
1602
+ }
1603
+ }
1604
+ /**
1605
+ * Watches legacy workflow transitions in real-time
1606
+ * @param runId - Optional run ID to filter the watch stream
1607
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1608
+ */
1609
+ async watch({ runId }, onRecord) {
1610
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1611
+ stream: true
1612
+ });
1613
+ if (!response.ok) {
1614
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1615
+ }
1616
+ if (!response.body) {
1617
+ throw new Error("Response body is null");
1618
+ }
1619
+ for await (const record of this.streamProcessor(response.body)) {
1620
+ onRecord(record);
1621
+ }
1622
+ }
1623
+ };
1624
+
1625
+ // src/resources/tool.ts
1626
+ var Tool = class extends BaseResource {
1627
+ constructor(options, toolId) {
1628
+ super(options);
1629
+ this.toolId = toolId;
1630
+ }
1631
+ /**
1632
+ * Retrieves details about the tool
1633
+ * @returns Promise containing tool details including description and schemas
1634
+ */
1635
+ details() {
1636
+ return this.request(`/api/tools/${this.toolId}`);
1637
+ }
1638
+ /**
1639
+ * Executes the tool with the provided parameters
1640
+ * @param params - Parameters required for tool execution
1641
+ * @returns Promise containing the tool execution results
1642
+ */
1643
+ execute(params) {
1644
+ const url = new URLSearchParams();
1645
+ if (params.runId) {
1646
+ url.set("runId", params.runId);
1647
+ }
1648
+ const body = {
1649
+ data: params.data,
1650
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1651
+ };
1652
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1653
+ method: "POST",
1654
+ body
1655
+ });
1656
+ }
1657
+ };
1658
+
1659
+ // src/resources/workflow.ts
1660
+ var RECORD_SEPARATOR2 = "";
1661
+ var Workflow = class extends BaseResource {
1662
+ constructor(options, workflowId) {
1663
+ super(options);
1664
+ this.workflowId = workflowId;
1665
+ }
1666
+ /**
1667
+ * Creates an async generator that processes a readable stream and yields workflow records
1668
+ * separated by the Record Separator character (\x1E)
1669
+ *
1670
+ * @param stream - The readable stream to process
1671
+ * @returns An async generator that yields parsed records
1672
+ */
1673
+ async *streamProcessor(stream) {
1674
+ const reader = stream.getReader();
1675
+ let doneReading = false;
1676
+ let buffer = "";
1677
+ try {
1678
+ while (!doneReading) {
1679
+ const { done, value } = await reader.read();
1680
+ doneReading = done;
1681
+ if (done && !value) continue;
1682
+ try {
1683
+ const decoded = value ? new TextDecoder().decode(value) : "";
1684
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1685
+ buffer = chunks.pop() || "";
1686
+ for (const chunk of chunks) {
1687
+ if (chunk) {
1688
+ if (typeof chunk === "string") {
1689
+ try {
1690
+ const parsedChunk = JSON.parse(chunk);
1691
+ yield parsedChunk;
1692
+ } catch {
1693
+ }
1694
+ }
1695
+ }
1696
+ }
1697
+ } catch {
1698
+ }
1699
+ }
1700
+ if (buffer) {
1701
+ try {
1702
+ yield JSON.parse(buffer);
1703
+ } catch {
1704
+ }
1705
+ }
1706
+ } finally {
1707
+ reader.cancel().catch(() => {
1708
+ });
1709
+ }
1710
+ }
1711
+ /**
1712
+ * Retrieves details about the workflow
1713
+ * @returns Promise containing workflow details including steps and graphs
1714
+ */
1715
+ details() {
1716
+ return this.request(`/api/workflows/${this.workflowId}`);
1717
+ }
1718
+ /**
1719
+ * Retrieves all runs for a workflow
1720
+ * @param params - Parameters for filtering runs
1721
+ * @returns Promise containing workflow runs array
1722
+ */
1723
+ runs(params) {
1724
+ const searchParams = new URLSearchParams();
1725
+ if (params?.fromDate) {
1726
+ searchParams.set("fromDate", params.fromDate.toISOString());
1727
+ }
1728
+ if (params?.toDate) {
1729
+ searchParams.set("toDate", params.toDate.toISOString());
1730
+ }
1731
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1732
+ searchParams.set("limit", String(params.limit));
1733
+ }
1734
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1735
+ searchParams.set("offset", String(params.offset));
1736
+ }
1737
+ if (params?.resourceId) {
1738
+ searchParams.set("resourceId", params.resourceId);
1739
+ }
1740
+ if (searchParams.size) {
1741
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1742
+ } else {
1743
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1744
+ }
1745
+ }
1746
+ /**
1747
+ * Retrieves a specific workflow run by its ID
1748
+ * @param runId - The ID of the workflow run to retrieve
1749
+ * @returns Promise containing the workflow run details
1750
+ */
1751
+ runById(runId) {
1752
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1753
+ }
1754
+ /**
1755
+ * Retrieves the execution result for a specific workflow run by its ID
1756
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1757
+ * @returns Promise containing the workflow run execution result
1758
+ */
1759
+ runExecutionResult(runId) {
1760
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1761
+ }
1762
+ /**
1763
+ * Cancels a specific workflow run by its ID
1764
+ * @param runId - The ID of the workflow run to cancel
1765
+ * @returns Promise containing a success message
1766
+ */
1767
+ cancelRun(runId) {
1768
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1769
+ method: "POST"
1770
+ });
1771
+ }
1772
+ /**
1773
+ * Sends an event to a specific workflow run by its ID
1774
+ * @param params - Object containing the runId, event and data
1775
+ * @returns Promise containing a success message
1776
+ */
1777
+ sendRunEvent(params) {
1778
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1779
+ method: "POST",
1780
+ body: { event: params.event, data: params.data }
1781
+ });
1782
+ }
1783
+ /**
1784
+ * Creates a new workflow run
1785
+ * @param params - Optional object containing the optional runId
1786
+ * @returns Promise containing the runId of the created run
1787
+ */
1788
+ createRun(params) {
1789
+ const searchParams = new URLSearchParams();
1790
+ if (!!params?.runId) {
1791
+ searchParams.set("runId", params.runId);
1792
+ }
1793
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1794
+ method: "POST"
1795
+ });
1796
+ }
1797
+ /**
1798
+ * Creates a new workflow run (alias for createRun)
1799
+ * @param params - Optional object containing the optional runId
1800
+ * @returns Promise containing the runId of the created run
1801
+ */
1802
+ createRunAsync(params) {
1803
+ return this.createRun(params);
1804
+ }
1805
+ /**
1806
+ * Starts a workflow run synchronously without waiting for the workflow to complete
1807
+ * @param params - Object containing the runId, inputData and runtimeContext
1808
+ * @returns Promise containing success message
1809
+ */
1810
+ start(params) {
1811
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1812
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1813
+ method: "POST",
1814
+ body: { inputData: params?.inputData, runtimeContext }
1815
+ });
1816
+ }
1817
+ /**
1818
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1819
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1820
+ * @returns Promise containing success message
1821
+ */
1822
+ resume({
1823
+ step,
1824
+ runId,
1825
+ resumeData,
1826
+ ...rest
1827
+ }) {
1828
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1829
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1830
+ method: "POST",
1831
+ stream: true,
1832
+ body: {
1833
+ step,
1834
+ resumeData,
1835
+ runtimeContext
1836
+ }
1837
+ });
1838
+ }
1839
+ /**
1840
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1841
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1842
+ * @returns Promise containing the workflow execution results
1843
+ */
1844
+ startAsync(params) {
1845
+ const searchParams = new URLSearchParams();
1846
+ if (!!params?.runId) {
1847
+ searchParams.set("runId", params.runId);
1848
+ }
1849
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1850
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1851
+ method: "POST",
1852
+ body: { inputData: params.inputData, runtimeContext }
1853
+ });
1854
+ }
1855
+ /**
1856
+ * Starts a workflow run and returns a stream
1857
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1858
+ * @returns Promise containing the workflow execution results
1859
+ */
1860
+ async stream(params) {
1861
+ const searchParams = new URLSearchParams();
1862
+ if (!!params?.runId) {
1863
+ searchParams.set("runId", params.runId);
1864
+ }
1865
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1866
+ const response = await this.request(
1867
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1868
+ {
1869
+ method: "POST",
1870
+ body: { inputData: params.inputData, runtimeContext },
1871
+ stream: true
1872
+ }
1873
+ );
1874
+ if (!response.ok) {
1875
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1876
+ }
1877
+ if (!response.body) {
1878
+ throw new Error("Response body is null");
1879
+ }
1880
+ let failedChunk = void 0;
1881
+ const transformStream = new TransformStream({
1882
+ start() {
1883
+ },
1884
+ async transform(chunk, controller) {
1885
+ try {
1886
+ const decoded = new TextDecoder().decode(chunk);
1887
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1888
+ for (const chunk2 of chunks) {
1889
+ if (chunk2) {
1890
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1891
+ try {
1892
+ const parsedChunk = JSON.parse(newChunk);
1893
+ controller.enqueue(parsedChunk);
1894
+ failedChunk = void 0;
1895
+ } catch {
1896
+ failedChunk = newChunk;
1897
+ }
1898
+ }
1899
+ }
1900
+ } catch {
1901
+ }
1902
+ }
1903
+ });
1904
+ return response.body.pipeThrough(transformStream);
1905
+ }
1906
+ /**
1907
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1908
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1909
+ * @returns Promise containing the workflow resume results
1910
+ */
1911
+ resumeAsync(params) {
1912
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1913
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1914
+ method: "POST",
1915
+ body: {
1916
+ step: params.step,
1917
+ resumeData: params.resumeData,
1918
+ runtimeContext
1919
+ }
1920
+ });
1921
+ }
1922
+ /**
1923
+ * Watches workflow transitions in real-time
1924
+ * @param runId - Optional run ID to filter the watch stream
1925
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1926
+ */
1927
+ async watch({ runId }, onRecord) {
1928
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1929
+ stream: true
1930
+ });
1931
+ if (!response.ok) {
1932
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1933
+ }
1934
+ if (!response.body) {
1935
+ throw new Error("Response body is null");
1936
+ }
1937
+ for await (const record of this.streamProcessor(response.body)) {
1938
+ if (typeof record === "string") {
1939
+ onRecord(JSON.parse(record));
1940
+ } else {
1941
+ onRecord(record);
1942
+ }
1943
+ }
1944
+ }
1945
+ /**
1946
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1947
+ * serializing each as JSON and separating them with the record separator (\x1E).
1948
+ *
1949
+ * @param records - An iterable or async iterable of objects to stream
1950
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1951
+ */
1952
+ static createRecordStream(records) {
1953
+ const encoder = new TextEncoder();
1954
+ return new ReadableStream({
1955
+ async start(controller) {
1956
+ try {
1957
+ for await (const record of records) {
1958
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1959
+ controller.enqueue(encoder.encode(json));
1960
+ }
1961
+ controller.close();
1962
+ } catch (err) {
1963
+ controller.error(err);
1964
+ }
1965
+ }
1966
+ });
1967
+ }
1968
+ };
1969
+
1970
+ // src/resources/a2a.ts
1971
+ var A2A = class extends BaseResource {
1972
+ constructor(options, agentId) {
1973
+ super(options);
1974
+ this.agentId = agentId;
1975
+ }
1976
+ /**
1977
+ * Get the agent card with metadata about the agent
1978
+ * @returns Promise containing the agent card information
1979
+ */
1980
+ async getCard() {
1981
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1982
+ }
1983
+ /**
1984
+ * Send a message to the agent and gets a message or task response
1985
+ * @param params - Parameters for the task
1986
+ * @returns Promise containing the response
1987
+ */
1988
+ async sendMessage(params) {
1989
+ const response = await this.request(`/a2a/${this.agentId}`, {
1990
+ method: "POST",
1991
+ body: {
1992
+ method: "message/send",
1993
+ params
1994
+ }
1995
+ });
1996
+ return response;
1997
+ }
1998
+ /**
1999
+ * Sends a message to an agent to initiate/continue a task and subscribes
2000
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2001
+ * @param params - Parameters for the task
2002
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2003
+ */
2004
+ async sendStreamingMessage(params) {
2005
+ const response = await this.request(`/a2a/${this.agentId}`, {
2006
+ method: "POST",
2007
+ body: {
2008
+ method: "message/stream",
2009
+ params
2010
+ }
2011
+ });
2012
+ return response;
2013
+ }
2014
+ /**
2015
+ * Get the status and result of a task
2016
+ * @param params - Parameters for querying the task
2017
+ * @returns Promise containing the task response
2018
+ */
2019
+ async getTask(params) {
2020
+ const response = await this.request(`/a2a/${this.agentId}`, {
2021
+ method: "POST",
2022
+ body: {
2023
+ method: "tasks/get",
2024
+ params
2025
+ }
2026
+ });
2027
+ return response;
2028
+ }
2029
+ /**
2030
+ * Cancel a running task
2031
+ * @param params - Parameters identifying the task to cancel
2032
+ * @returns Promise containing the task response
2033
+ */
2034
+ async cancelTask(params) {
2035
+ return this.request(`/a2a/${this.agentId}`, {
2036
+ method: "POST",
2037
+ body: {
2038
+ method: "tasks/cancel",
2039
+ params
2040
+ }
2041
+ });
2042
+ }
2043
+ };
2044
+
2045
+ // src/resources/mcp-tool.ts
2046
+ var MCPTool = class extends BaseResource {
2047
+ serverId;
2048
+ toolId;
2049
+ constructor(options, serverId, toolId) {
2050
+ super(options);
2051
+ this.serverId = serverId;
2052
+ this.toolId = toolId;
2053
+ }
2054
+ /**
2055
+ * Retrieves details about this specific tool from the MCP server.
2056
+ * @returns Promise containing the tool's information (name, description, schema).
2057
+ */
2058
+ details() {
2059
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2060
+ }
2061
+ /**
2062
+ * Executes this specific tool on the MCP server.
2063
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2064
+ * @returns Promise containing the result of the tool execution.
2065
+ */
2066
+ execute(params) {
2067
+ const body = {};
2068
+ if (params.data !== void 0) body.data = params.data;
2069
+ if (params.runtimeContext !== void 0) {
2070
+ body.runtimeContext = params.runtimeContext;
2071
+ }
2072
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2073
+ method: "POST",
2074
+ body: Object.keys(body).length > 0 ? body : void 0
2075
+ });
2076
+ }
2077
+ };
2078
+
2079
+ // src/resources/agent-builder.ts
2080
+ var RECORD_SEPARATOR3 = "";
2081
+ var AgentBuilder = class extends BaseResource {
2082
+ constructor(options, actionId) {
2083
+ super(options);
2084
+ this.actionId = actionId;
2085
+ }
2086
+ // Helper function to transform workflow result to action result
2087
+ transformWorkflowResult(result) {
2088
+ if (result.status === "success") {
2089
+ return {
2090
+ success: result.result.success || false,
2091
+ applied: result.result.applied || false,
2092
+ branchName: result.result.branchName,
2093
+ message: result.result.message || "Agent builder action completed",
2094
+ validationResults: result.result.validationResults,
2095
+ error: result.result.error,
2096
+ errors: result.result.errors,
2097
+ stepResults: result.result.stepResults
2098
+ };
2099
+ } else if (result.status === "failed") {
2100
+ return {
2101
+ success: false,
2102
+ applied: false,
2103
+ message: `Agent builder action failed: ${result.error.message}`,
2104
+ error: result.error.message
2105
+ };
2106
+ } else {
2107
+ return {
2108
+ success: false,
2109
+ applied: false,
2110
+ message: "Agent builder action was suspended",
2111
+ error: "Workflow suspended - manual intervention required"
2112
+ };
2113
+ }
2114
+ }
2115
+ /**
2116
+ * Creates a new agent builder action run and returns the runId.
2117
+ * This calls `/api/agent-builder/:actionId/create-run`.
2118
+ */
2119
+ async createRun(params) {
2120
+ const searchParams = new URLSearchParams();
2121
+ if (!!params?.runId) {
2122
+ searchParams.set("runId", params.runId);
2123
+ }
2124
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2125
+ return this.request(url, {
2126
+ method: "POST"
2127
+ });
2128
+ }
2129
+ /**
2130
+ * Creates a new workflow run (alias for createRun)
2131
+ * @param params - Optional object containing the optional runId
2132
+ * @returns Promise containing the runId of the created run
2133
+ */
2134
+ createRunAsync(params) {
2135
+ return this.createRun(params);
2136
+ }
2137
+ /**
2138
+ * Starts agent builder action asynchronously and waits for completion.
2139
+ * This calls `/api/agent-builder/:actionId/start-async`.
2140
+ */
2141
+ async startAsync(params, runId) {
2142
+ const searchParams = new URLSearchParams();
2143
+ if (runId) {
2144
+ searchParams.set("runId", runId);
2145
+ }
2146
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2147
+ const { runtimeContext: _, ...actionParams } = params;
2148
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2149
+ const result = await this.request(url, {
2150
+ method: "POST",
2151
+ body: { ...actionParams, runtimeContext }
2152
+ });
2153
+ return this.transformWorkflowResult(result);
2154
+ }
2155
+ /**
2156
+ * Starts an existing agent builder action run.
2157
+ * This calls `/api/agent-builder/:actionId/start`.
2158
+ */
2159
+ async startActionRun(params, runId) {
2160
+ const searchParams = new URLSearchParams();
2161
+ searchParams.set("runId", runId);
2162
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2163
+ const { runtimeContext: _, ...actionParams } = params;
2164
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2165
+ return this.request(url, {
2166
+ method: "POST",
2167
+ body: { ...actionParams, runtimeContext }
2168
+ });
2169
+ }
2170
+ /**
2171
+ * Resumes a suspended agent builder action step.
2172
+ * This calls `/api/agent-builder/:actionId/resume`.
2173
+ */
2174
+ async resume(params, runId) {
2175
+ const searchParams = new URLSearchParams();
2176
+ searchParams.set("runId", runId);
2177
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2178
+ const { runtimeContext: _, ...resumeParams } = params;
2179
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2180
+ return this.request(url, {
2181
+ method: "POST",
2182
+ body: { ...resumeParams, runtimeContext }
2183
+ });
2184
+ }
2185
+ /**
2186
+ * Resumes a suspended agent builder action step asynchronously.
2187
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2188
+ */
2189
+ async resumeAsync(params, runId) {
2190
+ const searchParams = new URLSearchParams();
2191
+ searchParams.set("runId", runId);
2192
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2193
+ const { runtimeContext: _, ...resumeParams } = params;
2194
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2195
+ const result = await this.request(url, {
2196
+ method: "POST",
2197
+ body: { ...resumeParams, runtimeContext }
2198
+ });
2199
+ return this.transformWorkflowResult(result);
2200
+ }
2201
+ /**
2202
+ * Creates an async generator that processes a readable stream and yields action records
2203
+ * separated by the Record Separator character (\x1E)
2204
+ *
2205
+ * @param stream - The readable stream to process
2206
+ * @returns An async generator that yields parsed records
2207
+ */
2208
+ async *streamProcessor(stream) {
2209
+ const reader = stream.getReader();
2210
+ let doneReading = false;
2211
+ let buffer = "";
2212
+ try {
2213
+ while (!doneReading) {
2214
+ const { done, value } = await reader.read();
2215
+ doneReading = done;
2216
+ if (done && !value) continue;
2217
+ try {
2218
+ const decoded = value ? new TextDecoder().decode(value) : "";
2219
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2220
+ buffer = chunks.pop() || "";
2221
+ for (const chunk of chunks) {
2222
+ if (chunk) {
2223
+ if (typeof chunk === "string") {
2224
+ try {
2225
+ const parsedChunk = JSON.parse(chunk);
2226
+ yield parsedChunk;
2227
+ } catch {
2228
+ }
2229
+ }
2230
+ }
2231
+ }
2232
+ } catch {
2233
+ }
2234
+ }
2235
+ if (buffer) {
2236
+ try {
2237
+ yield JSON.parse(buffer);
2238
+ } catch {
2239
+ }
2240
+ }
2241
+ } finally {
2242
+ reader.cancel().catch(() => {
2243
+ });
2244
+ }
2245
+ }
2246
+ /**
2247
+ * Streams agent builder action progress in real-time.
2248
+ * This calls `/api/agent-builder/:actionId/stream`.
2249
+ */
2250
+ async stream(params, runId) {
2251
+ const searchParams = new URLSearchParams();
2252
+ if (runId) {
2253
+ searchParams.set("runId", runId);
2254
+ }
2255
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2256
+ const { runtimeContext: _, ...actionParams } = params;
2257
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2258
+ const response = await this.request(url, {
2259
+ method: "POST",
2260
+ body: { ...actionParams, runtimeContext },
2261
+ stream: true
2262
+ });
2263
+ if (!response.ok) {
2264
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2265
+ }
2266
+ if (!response.body) {
2267
+ throw new Error("Response body is null");
2268
+ }
2269
+ let failedChunk = void 0;
2270
+ const transformStream = new TransformStream({
2271
+ start() {
2272
+ },
2273
+ async transform(chunk, controller) {
2274
+ try {
2275
+ const decoded = new TextDecoder().decode(chunk);
2276
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2277
+ for (const chunk2 of chunks) {
2278
+ if (chunk2) {
2279
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2280
+ try {
2281
+ const parsedChunk = JSON.parse(newChunk);
2282
+ controller.enqueue(parsedChunk);
2283
+ failedChunk = void 0;
2284
+ } catch {
2285
+ failedChunk = newChunk;
2286
+ }
2287
+ }
2288
+ }
2289
+ } catch {
2290
+ }
2291
+ }
2292
+ });
2293
+ return response.body.pipeThrough(transformStream);
2294
+ }
2295
+ /**
2296
+ * Streams agent builder action progress in real-time using VNext streaming.
2297
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2298
+ */
2299
+ async streamVNext(params, runId) {
2300
+ const searchParams = new URLSearchParams();
2301
+ if (runId) {
2302
+ searchParams.set("runId", runId);
2303
+ }
2304
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2305
+ const { runtimeContext: _, ...actionParams } = params;
2306
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2307
+ const response = await this.request(url, {
2308
+ method: "POST",
2309
+ body: { ...actionParams, runtimeContext },
2310
+ stream: true
2311
+ });
2312
+ if (!response.ok) {
2313
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2314
+ }
2315
+ if (!response.body) {
2316
+ throw new Error("Response body is null");
2317
+ }
2318
+ let failedChunk = void 0;
2319
+ const transformStream = new TransformStream({
2320
+ start() {
2321
+ },
2322
+ async transform(chunk, controller) {
2323
+ try {
2324
+ const decoded = new TextDecoder().decode(chunk);
2325
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2326
+ for (const chunk2 of chunks) {
2327
+ if (chunk2) {
2328
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2329
+ try {
2330
+ const parsedChunk = JSON.parse(newChunk);
2331
+ controller.enqueue(parsedChunk);
2332
+ failedChunk = void 0;
2333
+ } catch {
2334
+ failedChunk = newChunk;
2335
+ }
2336
+ }
2337
+ }
2338
+ } catch {
2339
+ }
2340
+ }
2341
+ });
2342
+ return response.body.pipeThrough(transformStream);
2343
+ }
2344
+ /**
2345
+ * Watches an existing agent builder action run by runId.
2346
+ * This is used for hot reload recovery - it loads the existing run state
2347
+ * and streams any remaining progress.
2348
+ * This calls `/api/agent-builder/:actionId/watch`.
2349
+ */
2350
+ async watch({ runId, eventType }, onRecord) {
2351
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2352
+ const response = await this.request(url, {
2353
+ method: "GET",
2354
+ stream: true
2355
+ });
2356
+ if (!response.ok) {
2357
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2358
+ }
2359
+ if (!response.body) {
2360
+ throw new Error("Response body is null");
2361
+ }
2362
+ for await (const record of this.streamProcessor(response.body)) {
2363
+ if (typeof record === "string") {
2364
+ onRecord(JSON.parse(record));
2365
+ } else {
2366
+ onRecord(record);
2367
+ }
2368
+ }
2369
+ }
2370
+ /**
2371
+ * Gets a specific action run by its ID.
2372
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2373
+ */
2374
+ async runById(runId) {
2375
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2376
+ return this.request(url, {
2377
+ method: "GET"
2378
+ });
2379
+ }
2380
+ /**
2381
+ * Gets details about this agent builder action.
2382
+ * This calls `/api/agent-builder/:actionId`.
2383
+ */
2384
+ async details() {
2385
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2386
+ return result;
2387
+ }
2388
+ /**
2389
+ * Gets all runs for this agent builder action.
2390
+ * This calls `/api/agent-builder/:actionId/runs`.
2391
+ */
2392
+ async runs(params) {
2393
+ const searchParams = new URLSearchParams();
2394
+ if (params?.fromDate) {
2395
+ searchParams.set("fromDate", params.fromDate.toISOString());
2396
+ }
2397
+ if (params?.toDate) {
2398
+ searchParams.set("toDate", params.toDate.toISOString());
2399
+ }
2400
+ if (params?.limit !== void 0) {
2401
+ searchParams.set("limit", String(params.limit));
2402
+ }
2403
+ if (params?.offset !== void 0) {
2404
+ searchParams.set("offset", String(params.offset));
2405
+ }
2406
+ if (params?.resourceId) {
2407
+ searchParams.set("resourceId", params.resourceId);
2408
+ }
2409
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2410
+ return this.request(url, {
2411
+ method: "GET"
2412
+ });
2413
+ }
2414
+ /**
2415
+ * Gets the execution result of an agent builder action run.
2416
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2417
+ */
2418
+ async runExecutionResult(runId) {
2419
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2420
+ return this.request(url, {
2421
+ method: "GET"
2422
+ });
2423
+ }
2424
+ /**
2425
+ * Cancels an agent builder action run.
2426
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2427
+ */
2428
+ async cancelRun(runId) {
2429
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2430
+ return this.request(url, {
2431
+ method: "POST"
2432
+ });
2433
+ }
2434
+ /**
2435
+ * Sends an event to an agent builder action run.
2436
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2437
+ */
2438
+ async sendRunEvent(params) {
2439
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2440
+ return this.request(url, {
2441
+ method: "POST",
2442
+ body: { event: params.event, data: params.data }
2443
+ });
2444
+ }
2445
+ };
2446
+
2447
+ // src/resources/observability.ts
2448
+ var Observability = class extends BaseResource {
2449
+ constructor(options) {
2450
+ super(options);
2451
+ }
2452
+ /**
2453
+ * Retrieves a specific AI trace by ID
2454
+ * @param traceId - ID of the trace to retrieve
2455
+ * @returns Promise containing the AI trace with all its spans
2456
+ */
2457
+ getTrace(traceId) {
2458
+ return this.request(`/api/observability/traces/${traceId}`);
2459
+ }
2460
+ /**
2461
+ * Retrieves paginated list of AI traces with optional filtering
2462
+ * @param params - Parameters for pagination and filtering
2463
+ * @returns Promise containing paginated traces and pagination info
2464
+ */
2465
+ getTraces(params) {
2466
+ const { pagination, filters } = params;
2467
+ const { page, perPage, dateRange } = pagination || {};
2468
+ const { name, spanType } = filters || {};
2469
+ const searchParams = new URLSearchParams();
2470
+ if (page !== void 0) {
2471
+ searchParams.set("page", String(page));
2472
+ }
2473
+ if (perPage !== void 0) {
2474
+ searchParams.set("perPage", String(perPage));
2475
+ }
2476
+ if (name) {
2477
+ searchParams.set("name", name);
2478
+ }
2479
+ if (spanType !== void 0) {
2480
+ searchParams.set("spanType", String(spanType));
2481
+ }
2482
+ if (dateRange) {
2483
+ const dateRangeStr = JSON.stringify({
2484
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2485
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2486
+ });
2487
+ searchParams.set("dateRange", dateRangeStr);
2488
+ }
2489
+ const queryString = searchParams.toString();
2490
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2491
+ }
2492
+ };
2493
+
2494
+ // src/resources/network-memory-thread.ts
2495
+ var NetworkMemoryThread = class extends BaseResource {
2496
+ constructor(options, threadId, networkId) {
2497
+ super(options);
2498
+ this.threadId = threadId;
2499
+ this.networkId = networkId;
2500
+ }
2501
+ /**
2502
+ * Retrieves the memory thread details
2503
+ * @returns Promise containing thread details including title and metadata
2504
+ */
2505
+ get() {
2506
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
2507
+ }
2508
+ /**
2509
+ * Updates the memory thread properties
2510
+ * @param params - Update parameters including title and metadata
2511
+ * @returns Promise containing updated thread details
2512
+ */
2513
+ update(params) {
2514
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2515
+ method: "PATCH",
2516
+ body: params
2517
+ });
2518
+ }
2519
+ /**
2520
+ * Deletes the memory thread
2521
+ * @returns Promise containing deletion result
2522
+ */
2523
+ delete() {
2524
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2525
+ method: "DELETE"
2526
+ });
2527
+ }
2528
+ /**
2529
+ * Retrieves messages associated with the thread
2530
+ * @param params - Optional parameters including limit for number of messages to retrieve
2531
+ * @returns Promise containing thread messages and UI messages
2532
+ */
2533
+ getMessages(params) {
2534
+ const query = new URLSearchParams({
2535
+ networkId: this.networkId,
2536
+ ...params?.limit ? { limit: params.limit.toString() } : {}
2537
+ });
2538
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
2539
+ }
2540
+ /**
2541
+ * Deletes one or more messages from the thread
2542
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2543
+ * message object with id property, or array of message objects
2544
+ * @returns Promise containing deletion result
436
2545
  */
437
- startAsync(params) {
438
- const searchParams = new URLSearchParams();
439
- if (!!params?.runId) {
440
- searchParams.set("runId", params.runId);
441
- }
442
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
2546
+ deleteMessages(messageIds) {
2547
+ const query = new URLSearchParams({
2548
+ networkId: this.networkId
2549
+ });
2550
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
443
2551
  method: "POST",
444
- body: params?.triggerData
2552
+ body: { messageIds }
445
2553
  });
446
2554
  }
2555
+ };
2556
+
2557
+ // src/resources/vNextNetwork.ts
2558
+ var RECORD_SEPARATOR4 = "";
2559
+ var VNextNetwork = class extends BaseResource {
2560
+ constructor(options, networkId) {
2561
+ super(options);
2562
+ this.networkId = networkId;
2563
+ }
447
2564
  /**
448
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
449
- * @param params - Object containing the runId, stepId, and context
450
- * @returns Promise containing the workflow resume results
2565
+ * Retrieves details about the network
2566
+ * @returns Promise containing vNext network details
451
2567
  */
452
- resumeAsync(params) {
453
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2568
+ details() {
2569
+ return this.request(`/api/networks/v-next/${this.networkId}`);
2570
+ }
2571
+ /**
2572
+ * Generates a response from the v-next network
2573
+ * @param params - Generation parameters including message
2574
+ * @returns Promise containing the generated response
2575
+ */
2576
+ generate(params) {
2577
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
454
2578
  method: "POST",
455
2579
  body: {
456
- stepId: params.stepId,
457
- context: params.context
2580
+ ...params,
2581
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
458
2582
  }
459
2583
  });
460
2584
  }
461
2585
  /**
462
- * Creates an async generator that processes a readable stream and yields records
463
- * separated by the Record Separator character (\x1E)
464
- *
465
- * @param stream - The readable stream to process
466
- * @returns An async generator that yields parsed records
2586
+ * Generates a response from the v-next network using multiple primitives
2587
+ * @param params - Generation parameters including message
2588
+ * @returns Promise containing the generated response
467
2589
  */
2590
+ loop(params) {
2591
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
2592
+ method: "POST",
2593
+ body: {
2594
+ ...params,
2595
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2596
+ }
2597
+ });
2598
+ }
468
2599
  async *streamProcessor(stream) {
469
2600
  const reader = stream.getReader();
470
2601
  let doneReading = false;
@@ -476,7 +2607,7 @@ var Workflow = class extends BaseResource {
476
2607
  if (done && !value) continue;
477
2608
  try {
478
2609
  const decoded = value ? new TextDecoder().decode(value) : "";
479
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
2610
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
480
2611
  buffer = chunks.pop() || "";
481
2612
  for (const chunk of chunks) {
482
2613
  if (chunk) {
@@ -489,7 +2620,7 @@ var Workflow = class extends BaseResource {
489
2620
  }
490
2621
  }
491
2622
  }
492
- } catch (error) {
2623
+ } catch {
493
2624
  }
494
2625
  }
495
2626
  if (buffer) {
@@ -504,56 +2635,69 @@ var Workflow = class extends BaseResource {
504
2635
  }
505
2636
  }
506
2637
  /**
507
- * Watches workflow transitions in real-time
508
- * @param runId - Optional run ID to filter the watch stream
509
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2638
+ * Streams a response from the v-next network
2639
+ * @param params - Stream parameters including message
2640
+ * @returns Promise containing the results
510
2641
  */
511
- async watch({ runId }, onRecord) {
512
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2642
+ async stream(params, onRecord) {
2643
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
2644
+ method: "POST",
2645
+ body: {
2646
+ ...params,
2647
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2648
+ },
513
2649
  stream: true
514
2650
  });
515
2651
  if (!response.ok) {
516
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
2652
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
517
2653
  }
518
2654
  if (!response.body) {
519
2655
  throw new Error("Response body is null");
520
2656
  }
521
2657
  for await (const record of this.streamProcessor(response.body)) {
522
- onRecord(record);
2658
+ if (typeof record === "string") {
2659
+ onRecord(JSON.parse(record));
2660
+ } else {
2661
+ onRecord(record);
2662
+ }
523
2663
  }
524
2664
  }
525
- };
526
-
527
- // src/resources/tool.ts
528
- var Tool = class extends BaseResource {
529
- constructor(options, toolId) {
530
- super(options);
531
- this.toolId = toolId;
532
- }
533
- /**
534
- * Retrieves details about the tool
535
- * @returns Promise containing tool details including description and schemas
536
- */
537
- details() {
538
- return this.request(`/api/tools/${this.toolId}`);
539
- }
540
2665
  /**
541
- * Executes the tool with the provided parameters
542
- * @param params - Parameters required for tool execution
543
- * @returns Promise containing the tool execution results
2666
+ * Streams a response from the v-next network loop
2667
+ * @param params - Stream parameters including message
2668
+ * @returns Promise containing the results
544
2669
  */
545
- execute(params) {
546
- return this.request(`/api/tools/${this.toolId}/execute`, {
2670
+ async loopStream(params, onRecord) {
2671
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
547
2672
  method: "POST",
548
- body: params
2673
+ body: {
2674
+ ...params,
2675
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2676
+ },
2677
+ stream: true
549
2678
  });
2679
+ if (!response.ok) {
2680
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2681
+ }
2682
+ if (!response.body) {
2683
+ throw new Error("Response body is null");
2684
+ }
2685
+ for await (const record of this.streamProcessor(response.body)) {
2686
+ if (typeof record === "string") {
2687
+ onRecord(JSON.parse(record));
2688
+ } else {
2689
+ onRecord(record);
2690
+ }
2691
+ }
550
2692
  }
551
2693
  };
552
2694
 
553
2695
  // src/client.ts
554
2696
  var MastraClient = class extends BaseResource {
2697
+ observability;
555
2698
  constructor(options) {
556
2699
  super(options);
2700
+ this.observability = new Observability(options);
557
2701
  }
558
2702
  /**
559
2703
  * Retrieves all available agents
@@ -612,6 +2756,48 @@ var MastraClient = class extends BaseResource {
612
2756
  getMemoryStatus(agentId) {
613
2757
  return this.request(`/api/memory/status?agentId=${agentId}`);
614
2758
  }
2759
+ /**
2760
+ * Retrieves memory threads for a resource
2761
+ * @param params - Parameters containing the resource ID
2762
+ * @returns Promise containing array of memory threads
2763
+ */
2764
+ getNetworkMemoryThreads(params) {
2765
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
2766
+ }
2767
+ /**
2768
+ * Creates a new memory thread
2769
+ * @param params - Parameters for creating the memory thread
2770
+ * @returns Promise containing the created memory thread
2771
+ */
2772
+ createNetworkMemoryThread(params) {
2773
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
2774
+ }
2775
+ /**
2776
+ * Gets a memory thread instance by ID
2777
+ * @param threadId - ID of the memory thread to retrieve
2778
+ * @returns MemoryThread instance
2779
+ */
2780
+ getNetworkMemoryThread(threadId, networkId) {
2781
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2782
+ }
2783
+ /**
2784
+ * Saves messages to memory
2785
+ * @param params - Parameters containing messages to save
2786
+ * @returns Promise containing the saved messages
2787
+ */
2788
+ saveNetworkMessageToMemory(params) {
2789
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2790
+ method: "POST",
2791
+ body: params
2792
+ });
2793
+ }
2794
+ /**
2795
+ * Gets the status of the memory system
2796
+ * @returns Promise containing memory system status
2797
+ */
2798
+ getNetworkMemoryStatus(networkId) {
2799
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2800
+ }
615
2801
  /**
616
2802
  * Retrieves all available tools
617
2803
  * @returns Promise containing map of tool IDs to tool details
@@ -627,6 +2813,21 @@ var MastraClient = class extends BaseResource {
627
2813
  getTool(toolId) {
628
2814
  return new Tool(this.options, toolId);
629
2815
  }
2816
+ /**
2817
+ * Retrieves all available legacy workflows
2818
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2819
+ */
2820
+ getLegacyWorkflows() {
2821
+ return this.request("/api/workflows/legacy");
2822
+ }
2823
+ /**
2824
+ * Gets a legacy workflow instance by ID
2825
+ * @param workflowId - ID of the legacy workflow to retrieve
2826
+ * @returns Legacy Workflow instance
2827
+ */
2828
+ getLegacyWorkflow(workflowId) {
2829
+ return new LegacyWorkflow(this.options, workflowId);
2830
+ }
630
2831
  /**
631
2832
  * Retrieves all available workflows
632
2833
  * @returns Promise containing map of workflow IDs to workflow details
@@ -642,6 +2843,20 @@ var MastraClient = class extends BaseResource {
642
2843
  getWorkflow(workflowId) {
643
2844
  return new Workflow(this.options, workflowId);
644
2845
  }
2846
+ /**
2847
+ * Gets all available agent builder actions
2848
+ * @returns Promise containing map of action IDs to action details
2849
+ */
2850
+ getAgentBuilderActions() {
2851
+ return this.request("/api/agent-builder/");
2852
+ }
2853
+ /**
2854
+ * Gets an agent builder instance for executing agent-builder workflows
2855
+ * @returns AgentBuilder instance
2856
+ */
2857
+ getAgentBuilderAction(actionId) {
2858
+ return new AgentBuilder(this.options, actionId);
2859
+ }
645
2860
  /**
646
2861
  * Gets a vector instance by name
647
2862
  * @param vectorName - Name of the vector to retrieve
@@ -656,7 +2871,41 @@ var MastraClient = class extends BaseResource {
656
2871
  * @returns Promise containing array of log messages
657
2872
  */
658
2873
  getLogs(params) {
659
- return this.request(`/api/logs?transportId=${params.transportId}`);
2874
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2875
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2876
+ const searchParams = new URLSearchParams();
2877
+ if (transportId) {
2878
+ searchParams.set("transportId", transportId);
2879
+ }
2880
+ if (fromDate) {
2881
+ searchParams.set("fromDate", fromDate.toISOString());
2882
+ }
2883
+ if (toDate) {
2884
+ searchParams.set("toDate", toDate.toISOString());
2885
+ }
2886
+ if (logLevel) {
2887
+ searchParams.set("logLevel", logLevel);
2888
+ }
2889
+ if (page) {
2890
+ searchParams.set("page", String(page));
2891
+ }
2892
+ if (perPage) {
2893
+ searchParams.set("perPage", String(perPage));
2894
+ }
2895
+ if (_filters) {
2896
+ if (Array.isArray(_filters)) {
2897
+ for (const filter of _filters) {
2898
+ searchParams.append("filters", filter);
2899
+ }
2900
+ } else {
2901
+ searchParams.set("filters", _filters);
2902
+ }
2903
+ }
2904
+ if (searchParams.size) {
2905
+ return this.request(`/api/logs?${searchParams}`);
2906
+ } else {
2907
+ return this.request(`/api/logs`);
2908
+ }
660
2909
  }
661
2910
  /**
662
2911
  * Gets logs for a specific run
@@ -664,7 +2913,44 @@ var MastraClient = class extends BaseResource {
664
2913
  * @returns Promise containing array of log messages
665
2914
  */
666
2915
  getLogForRun(params) {
667
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2916
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2917
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2918
+ const searchParams = new URLSearchParams();
2919
+ if (runId) {
2920
+ searchParams.set("runId", runId);
2921
+ }
2922
+ if (transportId) {
2923
+ searchParams.set("transportId", transportId);
2924
+ }
2925
+ if (fromDate) {
2926
+ searchParams.set("fromDate", fromDate.toISOString());
2927
+ }
2928
+ if (toDate) {
2929
+ searchParams.set("toDate", toDate.toISOString());
2930
+ }
2931
+ if (logLevel) {
2932
+ searchParams.set("logLevel", logLevel);
2933
+ }
2934
+ if (page) {
2935
+ searchParams.set("page", String(page));
2936
+ }
2937
+ if (perPage) {
2938
+ searchParams.set("perPage", String(perPage));
2939
+ }
2940
+ if (_filters) {
2941
+ if (Array.isArray(_filters)) {
2942
+ for (const filter of _filters) {
2943
+ searchParams.append("filters", filter);
2944
+ }
2945
+ } else {
2946
+ searchParams.set("filters", _filters);
2947
+ }
2948
+ }
2949
+ if (searchParams.size) {
2950
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2951
+ } else {
2952
+ return this.request(`/api/logs/${runId}`);
2953
+ }
668
2954
  }
669
2955
  /**
670
2956
  * List of all log transports
@@ -679,7 +2965,7 @@ var MastraClient = class extends BaseResource {
679
2965
  * @returns Promise containing telemetry data
680
2966
  */
681
2967
  getTelemetry(params) {
682
- const { name, scope, page, perPage, attribute } = params || {};
2968
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
683
2969
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
684
2970
  const searchParams = new URLSearchParams();
685
2971
  if (name) {
@@ -703,6 +2989,12 @@ var MastraClient = class extends BaseResource {
703
2989
  searchParams.set("attribute", _attribute);
704
2990
  }
705
2991
  }
2992
+ if (fromDate) {
2993
+ searchParams.set("fromDate", fromDate.toISOString());
2994
+ }
2995
+ if (toDate) {
2996
+ searchParams.set("toDate", toDate.toISOString());
2997
+ }
706
2998
  if (searchParams.size) {
707
2999
  return this.request(`/api/telemetry?${searchParams}`);
708
3000
  } else {
@@ -716,6 +3008,13 @@ var MastraClient = class extends BaseResource {
716
3008
  getNetworks() {
717
3009
  return this.request("/api/networks");
718
3010
  }
3011
+ /**
3012
+ * Retrieves all available vNext networks
3013
+ * @returns Promise containing map of vNext network IDs to vNext network details
3014
+ */
3015
+ getVNextNetworks() {
3016
+ return this.request("/api/networks/v-next");
3017
+ }
719
3018
  /**
720
3019
  * Gets a network instance by ID
721
3020
  * @param networkId - ID of the network to retrieve
@@ -724,6 +3023,198 @@ var MastraClient = class extends BaseResource {
724
3023
  getNetwork(networkId) {
725
3024
  return new Network(this.options, networkId);
726
3025
  }
3026
+ /**
3027
+ * Gets a vNext network instance by ID
3028
+ * @param networkId - ID of the vNext network to retrieve
3029
+ * @returns vNext Network instance
3030
+ */
3031
+ getVNextNetwork(networkId) {
3032
+ return new VNextNetwork(this.options, networkId);
3033
+ }
3034
+ /**
3035
+ * Retrieves a list of available MCP servers.
3036
+ * @param params - Optional parameters for pagination (limit, offset).
3037
+ * @returns Promise containing the list of MCP servers and pagination info.
3038
+ */
3039
+ getMcpServers(params) {
3040
+ const searchParams = new URLSearchParams();
3041
+ if (params?.limit !== void 0) {
3042
+ searchParams.set("limit", String(params.limit));
3043
+ }
3044
+ if (params?.offset !== void 0) {
3045
+ searchParams.set("offset", String(params.offset));
3046
+ }
3047
+ const queryString = searchParams.toString();
3048
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
3049
+ }
3050
+ /**
3051
+ * Retrieves detailed information for a specific MCP server.
3052
+ * @param serverId - The ID of the MCP server to retrieve.
3053
+ * @param params - Optional parameters, e.g., specific version.
3054
+ * @returns Promise containing the detailed MCP server information.
3055
+ */
3056
+ getMcpServerDetails(serverId, params) {
3057
+ const searchParams = new URLSearchParams();
3058
+ if (params?.version) {
3059
+ searchParams.set("version", params.version);
3060
+ }
3061
+ const queryString = searchParams.toString();
3062
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
3063
+ }
3064
+ /**
3065
+ * Retrieves a list of tools for a specific MCP server.
3066
+ * @param serverId - The ID of the MCP server.
3067
+ * @returns Promise containing the list of tools.
3068
+ */
3069
+ getMcpServerTools(serverId) {
3070
+ return this.request(`/api/mcp/${serverId}/tools`);
3071
+ }
3072
+ /**
3073
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
3074
+ * This instance can then be used to fetch details or execute the tool.
3075
+ * @param serverId - The ID of the MCP server.
3076
+ * @param toolId - The ID of the tool.
3077
+ * @returns MCPTool instance.
3078
+ */
3079
+ getMcpServerTool(serverId, toolId) {
3080
+ return new MCPTool(this.options, serverId, toolId);
3081
+ }
3082
+ /**
3083
+ * Gets an A2A client for interacting with an agent via the A2A protocol
3084
+ * @param agentId - ID of the agent to interact with
3085
+ * @returns A2A client instance
3086
+ */
3087
+ getA2A(agentId) {
3088
+ return new A2A(this.options, agentId);
3089
+ }
3090
+ /**
3091
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3092
+ * @param agentId - ID of the agent.
3093
+ * @param threadId - ID of the thread.
3094
+ * @param resourceId - Optional ID of the resource.
3095
+ * @returns Working memory for the specified thread or resource.
3096
+ */
3097
+ getWorkingMemory({
3098
+ agentId,
3099
+ threadId,
3100
+ resourceId
3101
+ }) {
3102
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3103
+ }
3104
+ /**
3105
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3106
+ * @param agentId - ID of the agent.
3107
+ * @param threadId - ID of the thread.
3108
+ * @param workingMemory - The new working memory content.
3109
+ * @param resourceId - Optional ID of the resource.
3110
+ */
3111
+ updateWorkingMemory({
3112
+ agentId,
3113
+ threadId,
3114
+ workingMemory,
3115
+ resourceId
3116
+ }) {
3117
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
3118
+ method: "POST",
3119
+ body: {
3120
+ workingMemory,
3121
+ resourceId
3122
+ }
3123
+ });
3124
+ }
3125
+ /**
3126
+ * Retrieves all available scorers
3127
+ * @returns Promise containing list of available scorers
3128
+ */
3129
+ getScorers() {
3130
+ return this.request("/api/scores/scorers");
3131
+ }
3132
+ /**
3133
+ * Retrieves a scorer by ID
3134
+ * @param scorerId - ID of the scorer to retrieve
3135
+ * @returns Promise containing the scorer
3136
+ */
3137
+ getScorer(scorerId) {
3138
+ return this.request(`/api/scores/scorers/${scorerId}`);
3139
+ }
3140
+ getScoresByScorerId(params) {
3141
+ const { page, perPage, scorerId, entityId, entityType } = params;
3142
+ const searchParams = new URLSearchParams();
3143
+ if (entityId) {
3144
+ searchParams.set("entityId", entityId);
3145
+ }
3146
+ if (entityType) {
3147
+ searchParams.set("entityType", entityType);
3148
+ }
3149
+ if (page !== void 0) {
3150
+ searchParams.set("page", String(page));
3151
+ }
3152
+ if (perPage !== void 0) {
3153
+ searchParams.set("perPage", String(perPage));
3154
+ }
3155
+ const queryString = searchParams.toString();
3156
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3157
+ }
3158
+ /**
3159
+ * Retrieves scores by run ID
3160
+ * @param params - Parameters containing run ID and pagination options
3161
+ * @returns Promise containing scores and pagination info
3162
+ */
3163
+ getScoresByRunId(params) {
3164
+ const { runId, page, perPage } = params;
3165
+ const searchParams = new URLSearchParams();
3166
+ if (page !== void 0) {
3167
+ searchParams.set("page", String(page));
3168
+ }
3169
+ if (perPage !== void 0) {
3170
+ searchParams.set("perPage", String(perPage));
3171
+ }
3172
+ const queryString = searchParams.toString();
3173
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3174
+ }
3175
+ /**
3176
+ * Retrieves scores by entity ID and type
3177
+ * @param params - Parameters containing entity ID, type, and pagination options
3178
+ * @returns Promise containing scores and pagination info
3179
+ */
3180
+ getScoresByEntityId(params) {
3181
+ const { entityId, entityType, page, perPage } = params;
3182
+ const searchParams = new URLSearchParams();
3183
+ if (page !== void 0) {
3184
+ searchParams.set("page", String(page));
3185
+ }
3186
+ if (perPage !== void 0) {
3187
+ searchParams.set("perPage", String(perPage));
3188
+ }
3189
+ const queryString = searchParams.toString();
3190
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3191
+ }
3192
+ /**
3193
+ * Saves a score
3194
+ * @param params - Parameters containing the score data to save
3195
+ * @returns Promise containing the saved score
3196
+ */
3197
+ saveScore(params) {
3198
+ return this.request("/api/scores", {
3199
+ method: "POST",
3200
+ body: params
3201
+ });
3202
+ }
3203
+ /**
3204
+ * Retrieves model providers with available keys
3205
+ * @returns Promise containing model providers with available keys
3206
+ */
3207
+ getModelProviders() {
3208
+ return this.request(`/api/model-providers`);
3209
+ }
3210
+ getAITrace(traceId) {
3211
+ return this.observability.getTrace(traceId);
3212
+ }
3213
+ getAITraces(params) {
3214
+ return this.observability.getTraces(params);
3215
+ }
727
3216
  };
728
3217
 
729
3218
  exports.MastraClient = MastraClient;
3219
+ //# sourceMappingURL=index.cjs.map
3220
+ //# sourceMappingURL=index.cjs.map