@mastra/client-js 0.0.0-mcp-server-deploy-20250507160341 → 0.0.0-memory-system-message-error-20250813233316

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 (84) hide show
  1. package/CHANGELOG.md +1278 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +2 -1
  4. package/dist/adapters/agui.d.ts +23 -0
  5. package/dist/adapters/agui.d.ts.map +1 -0
  6. package/dist/client.d.ts +270 -0
  7. package/dist/client.d.ts.map +1 -0
  8. package/dist/example.d.ts +2 -0
  9. package/dist/example.d.ts.map +1 -0
  10. package/dist/index.cjs +1607 -152
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.ts +4 -760
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +1606 -155
  15. package/dist/index.js.map +1 -0
  16. package/dist/resources/a2a.d.ts +41 -0
  17. package/dist/resources/a2a.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +123 -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 +11 -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/tool.d.ts +23 -0
  35. package/dist/resources/tool.d.ts.map +1 -0
  36. package/dist/resources/vNextNetwork.d.ts +42 -0
  37. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  38. package/dist/resources/vector.d.ts +48 -0
  39. package/dist/resources/vector.d.ts.map +1 -0
  40. package/dist/resources/workflow.d.ts +154 -0
  41. package/dist/resources/workflow.d.ts.map +1 -0
  42. package/dist/types.d.ts +422 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/utils/index.d.ts +3 -0
  45. package/dist/utils/index.d.ts.map +1 -0
  46. package/dist/utils/process-client-tools.d.ts +3 -0
  47. package/dist/utils/process-client-tools.d.ts.map +1 -0
  48. package/dist/utils/zod-to-json-schema.d.ts +105 -0
  49. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  50. package/integration-tests/agui-adapter.test.ts +122 -0
  51. package/integration-tests/package.json +18 -0
  52. package/integration-tests/src/mastra/index.ts +35 -0
  53. package/integration-tests/vitest.config.ts +9 -0
  54. package/package.json +32 -19
  55. package/src/adapters/agui.test.ts +322 -0
  56. package/src/adapters/agui.ts +257 -0
  57. package/src/client.ts +398 -33
  58. package/src/example.ts +59 -29
  59. package/src/index.test.ts +522 -6
  60. package/src/index.ts +1 -0
  61. package/src/resources/a2a.ts +98 -0
  62. package/src/resources/agent.ts +641 -48
  63. package/src/resources/base.ts +7 -1
  64. package/src/resources/index.ts +4 -3
  65. package/src/resources/{vnext-workflow.ts → legacy-workflow.ts} +124 -139
  66. package/src/resources/mcp-tool.ts +48 -0
  67. package/src/resources/memory-thread.test.ts +285 -0
  68. package/src/resources/memory-thread.ts +49 -3
  69. package/src/resources/network-memory-thread.test.ts +269 -0
  70. package/src/resources/network-memory-thread.ts +81 -0
  71. package/src/resources/network.ts +10 -16
  72. package/src/resources/tool.ts +9 -2
  73. package/src/resources/vNextNetwork.ts +194 -0
  74. package/src/resources/workflow.ts +255 -96
  75. package/src/types.ts +258 -29
  76. package/src/utils/index.ts +11 -0
  77. package/src/utils/process-client-tools.ts +32 -0
  78. package/src/utils/zod-to-json-schema.ts +10 -0
  79. package/src/v2-messages.test.ts +180 -0
  80. package/tsconfig.build.json +9 -0
  81. package/tsconfig.json +1 -1
  82. package/tsup.config.ts +17 -0
  83. package/dist/index.d.cts +0 -760
  84. package/src/resources/mcp.ts +0 -22
package/dist/index.cjs CHANGED
@@ -1,10 +1,250 @@
1
1
  'use strict';
2
2
 
3
+ var client = require('@ag-ui/client');
4
+ var rxjs = require('rxjs');
3
5
  var uiUtils = require('@ai-sdk/ui-utils');
4
6
  var zod = require('zod');
5
- var zodToJsonSchema = require('zod-to-json-schema');
7
+ var originalZodToJsonSchema = require('zod-to-json-schema');
8
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
9
+ var uuid = require('@lukeed/uuid');
10
+ var runtimeContext = require('@mastra/core/runtime-context');
6
11
 
7
- // src/resources/agent.ts
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
15
+
16
+ // src/adapters/agui.ts
17
+ var AGUIAdapter = class extends client.AbstractAgent {
18
+ agent;
19
+ resourceId;
20
+ constructor({ agent, agentId, resourceId, ...rest }) {
21
+ super({
22
+ agentId,
23
+ ...rest
24
+ });
25
+ this.agent = agent;
26
+ this.resourceId = resourceId;
27
+ }
28
+ run(input) {
29
+ return new rxjs.Observable((subscriber) => {
30
+ const convertedMessages = convertMessagesToMastraMessages(input.messages);
31
+ subscriber.next({
32
+ type: client.EventType.RUN_STARTED,
33
+ threadId: input.threadId,
34
+ runId: input.runId
35
+ });
36
+ this.agent.stream({
37
+ threadId: input.threadId,
38
+ resourceId: this.resourceId ?? "",
39
+ runId: input.runId,
40
+ messages: convertedMessages,
41
+ clientTools: input.tools.reduce(
42
+ (acc, tool) => {
43
+ acc[tool.name] = {
44
+ id: tool.name,
45
+ description: tool.description,
46
+ inputSchema: tool.parameters
47
+ };
48
+ return acc;
49
+ },
50
+ {}
51
+ )
52
+ }).then((response) => {
53
+ let currentMessageId = void 0;
54
+ let isInTextMessage = false;
55
+ return response.processDataStream({
56
+ onTextPart: (text) => {
57
+ if (currentMessageId === void 0) {
58
+ currentMessageId = generateUUID();
59
+ const message2 = {
60
+ type: client.EventType.TEXT_MESSAGE_START,
61
+ messageId: currentMessageId,
62
+ role: "assistant"
63
+ };
64
+ subscriber.next(message2);
65
+ isInTextMessage = true;
66
+ }
67
+ const message = {
68
+ type: client.EventType.TEXT_MESSAGE_CONTENT,
69
+ messageId: currentMessageId,
70
+ delta: text
71
+ };
72
+ subscriber.next(message);
73
+ },
74
+ onFinishMessagePart: () => {
75
+ if (currentMessageId !== void 0) {
76
+ const message = {
77
+ type: client.EventType.TEXT_MESSAGE_END,
78
+ messageId: currentMessageId
79
+ };
80
+ subscriber.next(message);
81
+ isInTextMessage = false;
82
+ }
83
+ subscriber.next({
84
+ type: client.EventType.RUN_FINISHED,
85
+ threadId: input.threadId,
86
+ runId: input.runId
87
+ });
88
+ subscriber.complete();
89
+ },
90
+ onToolCallPart(streamPart) {
91
+ const parentMessageId = currentMessageId || generateUUID();
92
+ if (isInTextMessage) {
93
+ const message = {
94
+ type: client.EventType.TEXT_MESSAGE_END,
95
+ messageId: parentMessageId
96
+ };
97
+ subscriber.next(message);
98
+ isInTextMessage = false;
99
+ }
100
+ subscriber.next({
101
+ type: client.EventType.TOOL_CALL_START,
102
+ toolCallId: streamPart.toolCallId,
103
+ toolCallName: streamPart.toolName,
104
+ parentMessageId
105
+ });
106
+ subscriber.next({
107
+ type: client.EventType.TOOL_CALL_ARGS,
108
+ toolCallId: streamPart.toolCallId,
109
+ delta: JSON.stringify(streamPart.args),
110
+ parentMessageId
111
+ });
112
+ subscriber.next({
113
+ type: client.EventType.TOOL_CALL_END,
114
+ toolCallId: streamPart.toolCallId,
115
+ parentMessageId
116
+ });
117
+ }
118
+ });
119
+ }).catch((error) => {
120
+ console.error("error", error);
121
+ subscriber.error(error);
122
+ });
123
+ return () => {
124
+ };
125
+ });
126
+ }
127
+ };
128
+ function generateUUID() {
129
+ if (typeof crypto !== "undefined") {
130
+ if (typeof crypto.randomUUID === "function") {
131
+ return crypto.randomUUID();
132
+ }
133
+ if (typeof crypto.getRandomValues === "function") {
134
+ const buffer = new Uint8Array(16);
135
+ crypto.getRandomValues(buffer);
136
+ buffer[6] = buffer[6] & 15 | 64;
137
+ buffer[8] = buffer[8] & 63 | 128;
138
+ let hex = "";
139
+ for (let i = 0; i < 16; i++) {
140
+ hex += buffer[i].toString(16).padStart(2, "0");
141
+ if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
142
+ }
143
+ return hex;
144
+ }
145
+ }
146
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
147
+ const r = Math.random() * 16 | 0;
148
+ const v = c === "x" ? r : r & 3 | 8;
149
+ return v.toString(16);
150
+ });
151
+ }
152
+ function convertMessagesToMastraMessages(messages) {
153
+ const result = [];
154
+ const toolCallsWithResults = /* @__PURE__ */ new Set();
155
+ for (const message of messages) {
156
+ if (message.role === "tool" && message.toolCallId) {
157
+ toolCallsWithResults.add(message.toolCallId);
158
+ }
159
+ }
160
+ for (const message of messages) {
161
+ if (message.role === "assistant") {
162
+ const parts = message.content ? [{ type: "text", text: message.content }] : [];
163
+ for (const toolCall of message.toolCalls ?? []) {
164
+ parts.push({
165
+ type: "tool-call",
166
+ toolCallId: toolCall.id,
167
+ toolName: toolCall.function.name,
168
+ args: JSON.parse(toolCall.function.arguments)
169
+ });
170
+ }
171
+ result.push({
172
+ role: "assistant",
173
+ content: parts
174
+ });
175
+ if (message.toolCalls?.length) {
176
+ for (const toolCall of message.toolCalls) {
177
+ if (!toolCallsWithResults.has(toolCall.id)) {
178
+ result.push({
179
+ role: "tool",
180
+ content: [
181
+ {
182
+ type: "tool-result",
183
+ toolCallId: toolCall.id,
184
+ toolName: toolCall.function.name,
185
+ result: JSON.parse(toolCall.function.arguments)
186
+ // This is still wrong but matches test expectations
187
+ }
188
+ ]
189
+ });
190
+ }
191
+ }
192
+ }
193
+ } else if (message.role === "user") {
194
+ result.push({
195
+ role: "user",
196
+ content: message.content || ""
197
+ });
198
+ } else if (message.role === "tool") {
199
+ result.push({
200
+ role: "tool",
201
+ content: [
202
+ {
203
+ type: "tool-result",
204
+ toolCallId: message.toolCallId || "unknown",
205
+ toolName: "unknown",
206
+ // toolName is not available in tool messages from CopilotKit
207
+ result: message.content
208
+ }
209
+ ]
210
+ });
211
+ }
212
+ }
213
+ return result;
214
+ }
215
+ function zodToJsonSchema(zodSchema) {
216
+ if (!(zodSchema instanceof zod.ZodSchema)) {
217
+ return zodSchema;
218
+ }
219
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
220
+ }
221
+ function processClientTools(clientTools) {
222
+ if (!clientTools) {
223
+ return void 0;
224
+ }
225
+ return Object.fromEntries(
226
+ Object.entries(clientTools).map(([key, value]) => {
227
+ if (isVercelTool.isVercelTool(value)) {
228
+ return [
229
+ key,
230
+ {
231
+ ...value,
232
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
233
+ }
234
+ ];
235
+ } else {
236
+ return [
237
+ key,
238
+ {
239
+ ...value,
240
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
241
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
242
+ }
243
+ ];
244
+ }
245
+ })
246
+ );
247
+ }
8
248
 
9
249
  // src/resources/base.ts
10
250
  var BaseResource = class {
@@ -24,14 +264,16 @@ var BaseResource = class {
24
264
  let delay = backoffMs;
25
265
  for (let attempt = 0; attempt <= retries; attempt++) {
26
266
  try {
27
- const response = await fetch(`${baseUrl}${path}`, {
267
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
28
268
  ...options,
29
269
  headers: {
270
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
30
271
  ...headers,
31
272
  ...options.headers
32
273
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
33
274
  // 'x-mastra-client-type': 'js',
34
275
  },
276
+ signal: this.options.abortSignal,
35
277
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
36
278
  });
37
279
  if (!response.ok) {
@@ -64,8 +306,15 @@ var BaseResource = class {
64
306
  throw lastError || new Error("Request failed");
65
307
  }
66
308
  };
67
-
68
- // src/resources/agent.ts
309
+ function parseClientRuntimeContext(runtimeContext$1) {
310
+ if (runtimeContext$1) {
311
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
312
+ return Object.fromEntries(runtimeContext$1.entries());
313
+ }
314
+ return runtimeContext$1;
315
+ }
316
+ return void 0;
317
+ }
69
318
  var AgentVoice = class extends BaseResource {
70
319
  constructor(options, agentId) {
71
320
  super(options);
@@ -112,6 +361,13 @@ var AgentVoice = class extends BaseResource {
112
361
  getSpeakers() {
113
362
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
114
363
  }
364
+ /**
365
+ * Get the listener configuration for the agent's voice provider
366
+ * @returns Promise containing a check if the agent has listening capabilities
367
+ */
368
+ getListener() {
369
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
370
+ }
115
371
  };
116
372
  var Agent = class extends BaseResource {
117
373
  constructor(options, agentId) {
@@ -127,21 +383,325 @@ var Agent = class extends BaseResource {
127
383
  details() {
128
384
  return this.request(`/api/agents/${this.agentId}`);
129
385
  }
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) {
386
+ async generate(params) {
136
387
  const processedParams = {
137
388
  ...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
389
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
390
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
391
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
392
+ clientTools: processClientTools(params.clientTools)
140
393
  };
141
- return this.request(`/api/agents/${this.agentId}/generate`, {
142
- method: "POST",
143
- body: processedParams
394
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
395
+ const response = await this.request(
396
+ `/api/agents/${this.agentId}/generate`,
397
+ {
398
+ method: "POST",
399
+ body: processedParams
400
+ }
401
+ );
402
+ if (response.finishReason === "tool-calls") {
403
+ const toolCalls = response.toolCalls;
404
+ if (!toolCalls || !Array.isArray(toolCalls)) {
405
+ return response;
406
+ }
407
+ for (const toolCall of toolCalls) {
408
+ const clientTool = params.clientTools?.[toolCall.toolName];
409
+ if (clientTool && clientTool.execute) {
410
+ const result = await clientTool.execute(
411
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
412
+ {
413
+ messages: response.messages,
414
+ toolCallId: toolCall?.toolCallId
415
+ }
416
+ );
417
+ const updatedMessages = [
418
+ {
419
+ role: "user",
420
+ content: params.messages
421
+ },
422
+ ...response.response.messages,
423
+ {
424
+ role: "tool",
425
+ content: [
426
+ {
427
+ type: "tool-result",
428
+ toolCallId: toolCall.toolCallId,
429
+ toolName: toolCall.toolName,
430
+ result
431
+ }
432
+ ]
433
+ }
434
+ ];
435
+ return this.generate({
436
+ ...params,
437
+ messages: updatedMessages
438
+ });
439
+ }
440
+ }
441
+ }
442
+ return response;
443
+ }
444
+ async processChatResponse({
445
+ stream,
446
+ update,
447
+ onToolCall,
448
+ onFinish,
449
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
450
+ lastMessage
451
+ }) {
452
+ const replaceLastMessage = lastMessage?.role === "assistant";
453
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
454
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
455
+ return Math.max(max, toolInvocation.step ?? 0);
456
+ }, 0) ?? 0) : 0;
457
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
458
+ id: uuid.v4(),
459
+ createdAt: getCurrentDate(),
460
+ role: "assistant",
461
+ content: "",
462
+ parts: []
463
+ };
464
+ let currentTextPart = void 0;
465
+ let currentReasoningPart = void 0;
466
+ let currentReasoningTextDetail = void 0;
467
+ function updateToolInvocationPart(toolCallId, invocation) {
468
+ const part = message.parts.find(
469
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
470
+ );
471
+ if (part != null) {
472
+ part.toolInvocation = invocation;
473
+ } else {
474
+ message.parts.push({
475
+ type: "tool-invocation",
476
+ toolInvocation: invocation
477
+ });
478
+ }
479
+ }
480
+ const data = [];
481
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
482
+ const partialToolCalls = {};
483
+ let usage = {
484
+ completionTokens: NaN,
485
+ promptTokens: NaN,
486
+ totalTokens: NaN
487
+ };
488
+ let finishReason = "unknown";
489
+ function execUpdate() {
490
+ const copiedData = [...data];
491
+ if (messageAnnotations?.length) {
492
+ message.annotations = messageAnnotations;
493
+ }
494
+ const copiedMessage = {
495
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
496
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
497
+ ...structuredClone(message),
498
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
499
+ // hashing approach by default to detect changes, but it only works for shallow
500
+ // changes. This is why we need to add a revision id to ensure that the message
501
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
502
+ // forwarded to rendering):
503
+ revisionId: uuid.v4()
504
+ };
505
+ update({
506
+ message: copiedMessage,
507
+ data: copiedData,
508
+ replaceLastMessage
509
+ });
510
+ }
511
+ await uiUtils.processDataStream({
512
+ stream,
513
+ onTextPart(value) {
514
+ if (currentTextPart == null) {
515
+ currentTextPart = {
516
+ type: "text",
517
+ text: value
518
+ };
519
+ message.parts.push(currentTextPart);
520
+ } else {
521
+ currentTextPart.text += value;
522
+ }
523
+ message.content += value;
524
+ execUpdate();
525
+ },
526
+ onReasoningPart(value) {
527
+ if (currentReasoningTextDetail == null) {
528
+ currentReasoningTextDetail = { type: "text", text: value };
529
+ if (currentReasoningPart != null) {
530
+ currentReasoningPart.details.push(currentReasoningTextDetail);
531
+ }
532
+ } else {
533
+ currentReasoningTextDetail.text += value;
534
+ }
535
+ if (currentReasoningPart == null) {
536
+ currentReasoningPart = {
537
+ type: "reasoning",
538
+ reasoning: value,
539
+ details: [currentReasoningTextDetail]
540
+ };
541
+ message.parts.push(currentReasoningPart);
542
+ } else {
543
+ currentReasoningPart.reasoning += value;
544
+ }
545
+ message.reasoning = (message.reasoning ?? "") + value;
546
+ execUpdate();
547
+ },
548
+ onReasoningSignaturePart(value) {
549
+ if (currentReasoningTextDetail != null) {
550
+ currentReasoningTextDetail.signature = value.signature;
551
+ }
552
+ },
553
+ onRedactedReasoningPart(value) {
554
+ if (currentReasoningPart == null) {
555
+ currentReasoningPart = {
556
+ type: "reasoning",
557
+ reasoning: "",
558
+ details: []
559
+ };
560
+ message.parts.push(currentReasoningPart);
561
+ }
562
+ currentReasoningPart.details.push({
563
+ type: "redacted",
564
+ data: value.data
565
+ });
566
+ currentReasoningTextDetail = void 0;
567
+ execUpdate();
568
+ },
569
+ onFilePart(value) {
570
+ message.parts.push({
571
+ type: "file",
572
+ mimeType: value.mimeType,
573
+ data: value.data
574
+ });
575
+ execUpdate();
576
+ },
577
+ onSourcePart(value) {
578
+ message.parts.push({
579
+ type: "source",
580
+ source: value
581
+ });
582
+ execUpdate();
583
+ },
584
+ onToolCallStreamingStartPart(value) {
585
+ if (message.toolInvocations == null) {
586
+ message.toolInvocations = [];
587
+ }
588
+ partialToolCalls[value.toolCallId] = {
589
+ text: "",
590
+ step,
591
+ toolName: value.toolName,
592
+ index: message.toolInvocations.length
593
+ };
594
+ const invocation = {
595
+ state: "partial-call",
596
+ step,
597
+ toolCallId: value.toolCallId,
598
+ toolName: value.toolName,
599
+ args: void 0
600
+ };
601
+ message.toolInvocations.push(invocation);
602
+ updateToolInvocationPart(value.toolCallId, invocation);
603
+ execUpdate();
604
+ },
605
+ onToolCallDeltaPart(value) {
606
+ const partialToolCall = partialToolCalls[value.toolCallId];
607
+ partialToolCall.text += value.argsTextDelta;
608
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
609
+ const invocation = {
610
+ state: "partial-call",
611
+ step: partialToolCall.step,
612
+ toolCallId: value.toolCallId,
613
+ toolName: partialToolCall.toolName,
614
+ args: partialArgs
615
+ };
616
+ message.toolInvocations[partialToolCall.index] = invocation;
617
+ updateToolInvocationPart(value.toolCallId, invocation);
618
+ execUpdate();
619
+ },
620
+ async onToolCallPart(value) {
621
+ const invocation = {
622
+ state: "call",
623
+ step,
624
+ ...value
625
+ };
626
+ if (partialToolCalls[value.toolCallId] != null) {
627
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
628
+ } else {
629
+ if (message.toolInvocations == null) {
630
+ message.toolInvocations = [];
631
+ }
632
+ message.toolInvocations.push(invocation);
633
+ }
634
+ updateToolInvocationPart(value.toolCallId, invocation);
635
+ execUpdate();
636
+ if (onToolCall) {
637
+ const result = await onToolCall({ toolCall: value });
638
+ if (result != null) {
639
+ const invocation2 = {
640
+ state: "result",
641
+ step,
642
+ ...value,
643
+ result
644
+ };
645
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
646
+ updateToolInvocationPart(value.toolCallId, invocation2);
647
+ execUpdate();
648
+ }
649
+ }
650
+ },
651
+ onToolResultPart(value) {
652
+ const toolInvocations = message.toolInvocations;
653
+ if (toolInvocations == null) {
654
+ throw new Error("tool_result must be preceded by a tool_call");
655
+ }
656
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
657
+ if (toolInvocationIndex === -1) {
658
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
659
+ }
660
+ const invocation = {
661
+ ...toolInvocations[toolInvocationIndex],
662
+ state: "result",
663
+ ...value
664
+ };
665
+ toolInvocations[toolInvocationIndex] = invocation;
666
+ updateToolInvocationPart(value.toolCallId, invocation);
667
+ execUpdate();
668
+ },
669
+ onDataPart(value) {
670
+ data.push(...value);
671
+ execUpdate();
672
+ },
673
+ onMessageAnnotationsPart(value) {
674
+ if (messageAnnotations == null) {
675
+ messageAnnotations = [...value];
676
+ } else {
677
+ messageAnnotations.push(...value);
678
+ }
679
+ execUpdate();
680
+ },
681
+ onFinishStepPart(value) {
682
+ step += 1;
683
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
684
+ currentReasoningPart = void 0;
685
+ currentReasoningTextDetail = void 0;
686
+ },
687
+ onStartStepPart(value) {
688
+ if (!replaceLastMessage) {
689
+ message.id = value.messageId;
690
+ }
691
+ message.parts.push({ type: "step-start" });
692
+ execUpdate();
693
+ },
694
+ onFinishMessagePart(value) {
695
+ finishReason = value.finishReason;
696
+ if (value.usage != null) {
697
+ usage = value.usage;
698
+ }
699
+ },
700
+ onErrorPart(error) {
701
+ throw new Error(error);
702
+ }
144
703
  });
704
+ onFinish?.({ message, finishReason, usage });
145
705
  }
146
706
  /**
147
707
  * Streams a response from the agent
@@ -151,9 +711,30 @@ var Agent = class extends BaseResource {
151
711
  async stream(params) {
152
712
  const processedParams = {
153
713
  ...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
714
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
715
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
716
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
717
+ clientTools: processClientTools(params.clientTools)
718
+ };
719
+ const { readable, writable } = new TransformStream();
720
+ const response = await this.processStreamResponse(processedParams, writable);
721
+ const streamResponse = new Response(readable, {
722
+ status: response.status,
723
+ statusText: response.statusText,
724
+ headers: response.headers
725
+ });
726
+ streamResponse.processDataStream = async (options = {}) => {
727
+ await uiUtils.processDataStream({
728
+ stream: streamResponse.body,
729
+ ...options
730
+ });
156
731
  };
732
+ return streamResponse;
733
+ }
734
+ /**
735
+ * Processes the stream response and handles tool calls
736
+ */
737
+ async processStreamResponse(processedParams, writable) {
157
738
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
158
739
  method: "POST",
159
740
  body: processedParams,
@@ -162,12 +743,104 @@ var Agent = class extends BaseResource {
162
743
  if (!response.body) {
163
744
  throw new Error("No response body");
164
745
  }
165
- response.processDataStream = async (options = {}) => {
166
- await uiUtils.processDataStream({
167
- stream: response.body,
168
- ...options
746
+ try {
747
+ let toolCalls = [];
748
+ let messages = [];
749
+ const [streamForWritable, streamForProcessing] = response.body.tee();
750
+ streamForWritable.pipeTo(writable, {
751
+ preventClose: true
752
+ }).catch((error) => {
753
+ console.error("Error piping to writable stream:", error);
169
754
  });
170
- };
755
+ this.processChatResponse({
756
+ stream: streamForProcessing,
757
+ update: ({ message }) => {
758
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
759
+ if (existingIndex !== -1) {
760
+ messages[existingIndex] = message;
761
+ } else {
762
+ messages.push(message);
763
+ }
764
+ },
765
+ onFinish: async ({ finishReason, message }) => {
766
+ if (finishReason === "tool-calls") {
767
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
768
+ if (toolCall) {
769
+ toolCalls.push(toolCall);
770
+ }
771
+ for (const toolCall2 of toolCalls) {
772
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
773
+ if (clientTool && clientTool.execute) {
774
+ const result = await clientTool.execute(
775
+ {
776
+ context: toolCall2?.args,
777
+ runId: processedParams.runId,
778
+ resourceId: processedParams.resourceId,
779
+ threadId: processedParams.threadId,
780
+ runtimeContext: processedParams.runtimeContext
781
+ },
782
+ {
783
+ messages: response.messages,
784
+ toolCallId: toolCall2?.toolCallId
785
+ }
786
+ );
787
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
788
+ const toolInvocationPart = lastMessage?.parts?.find(
789
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
790
+ );
791
+ if (toolInvocationPart) {
792
+ toolInvocationPart.toolInvocation = {
793
+ ...toolInvocationPart.toolInvocation,
794
+ state: "result",
795
+ result
796
+ };
797
+ }
798
+ const toolInvocation = lastMessage?.toolInvocations?.find(
799
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
800
+ );
801
+ if (toolInvocation) {
802
+ toolInvocation.state = "result";
803
+ toolInvocation.result = result;
804
+ }
805
+ const writer = writable.getWriter();
806
+ try {
807
+ await writer.write(
808
+ new TextEncoder().encode(
809
+ "a:" + JSON.stringify({
810
+ toolCallId: toolCall2.toolCallId,
811
+ result
812
+ }) + "\n"
813
+ )
814
+ );
815
+ } finally {
816
+ writer.releaseLock();
817
+ }
818
+ const originalMessages = processedParams.messages;
819
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
820
+ this.processStreamResponse(
821
+ {
822
+ ...processedParams,
823
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
824
+ },
825
+ writable
826
+ ).catch((error) => {
827
+ console.error("Error processing stream response:", error);
828
+ });
829
+ }
830
+ }
831
+ } else {
832
+ setTimeout(() => {
833
+ writable.close();
834
+ }, 0);
835
+ }
836
+ },
837
+ lastMessage: void 0
838
+ }).catch((error) => {
839
+ console.error("Error processing stream response:", error);
840
+ });
841
+ } catch (error) {
842
+ console.error("Error processing stream response:", error);
843
+ }
171
844
  return response;
172
845
  }
173
846
  /**
@@ -178,6 +851,22 @@ var Agent = class extends BaseResource {
178
851
  getTool(toolId) {
179
852
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
180
853
  }
854
+ /**
855
+ * Executes a tool for the agent
856
+ * @param toolId - ID of the tool to execute
857
+ * @param params - Parameters required for tool execution
858
+ * @returns Promise containing the tool execution results
859
+ */
860
+ executeTool(toolId, params) {
861
+ const body = {
862
+ data: params.data,
863
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
864
+ };
865
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
866
+ method: "POST",
867
+ body
868
+ });
869
+ }
181
870
  /**
182
871
  * Retrieves evaluation results for the agent
183
872
  * @returns Promise containing agent evaluations
@@ -192,6 +881,17 @@ var Agent = class extends BaseResource {
192
881
  liveEvals() {
193
882
  return this.request(`/api/agents/${this.agentId}/evals/live`);
194
883
  }
884
+ /**
885
+ * Updates the model for the agent
886
+ * @param params - Parameters for updating the model
887
+ * @returns Promise containing the updated model
888
+ */
889
+ updateModel(params) {
890
+ return this.request(`/api/agents/${this.agentId}/model`, {
891
+ method: "POST",
892
+ body: params
893
+ });
894
+ }
195
895
  };
196
896
  var Network = class extends BaseResource {
197
897
  constructor(options, networkId) {
@@ -213,8 +913,8 @@ var Network = class extends BaseResource {
213
913
  generate(params) {
214
914
  const processedParams = {
215
915
  ...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
916
+ output: zodToJsonSchema(params.output),
917
+ experimental_output: zodToJsonSchema(params.experimental_output)
218
918
  };
219
919
  return this.request(`/api/networks/${this.networkId}/generate`, {
220
920
  method: "POST",
@@ -229,8 +929,8 @@ var Network = class extends BaseResource {
229
929
  async stream(params) {
230
930
  const processedParams = {
231
931
  ...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
932
+ output: zodToJsonSchema(params.output),
933
+ experimental_output: zodToJsonSchema(params.experimental_output)
234
934
  };
235
935
  const response = await this.request(`/api/networks/${this.networkId}/stream`, {
236
936
  method: "POST",
@@ -286,10 +986,45 @@ var MemoryThread = class extends BaseResource {
286
986
  }
287
987
  /**
288
988
  * Retrieves messages associated with the thread
989
+ * @param params - Optional parameters including limit for number of messages to retrieve
289
990
  * @returns Promise containing thread messages and UI messages
290
991
  */
291
- getMessages() {
292
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
992
+ getMessages(params) {
993
+ const query = new URLSearchParams({
994
+ agentId: this.agentId,
995
+ ...params?.limit ? { limit: params.limit.toString() } : {}
996
+ });
997
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
998
+ }
999
+ /**
1000
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1001
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1002
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1003
+ */
1004
+ getMessagesPaginated({
1005
+ selectBy,
1006
+ ...rest
1007
+ }) {
1008
+ const query = new URLSearchParams({
1009
+ ...rest,
1010
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1011
+ });
1012
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1013
+ }
1014
+ /**
1015
+ * Deletes one or more messages from the thread
1016
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1017
+ * message object with id property, or array of message objects
1018
+ * @returns Promise containing deletion result
1019
+ */
1020
+ deleteMessages(messageIds) {
1021
+ const query = new URLSearchParams({
1022
+ agentId: this.agentId
1023
+ });
1024
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1025
+ method: "POST",
1026
+ body: { messageIds }
1027
+ });
293
1028
  }
294
1029
  };
295
1030
 
@@ -359,24 +1094,24 @@ var Vector = class extends BaseResource {
359
1094
  }
360
1095
  };
361
1096
 
362
- // src/resources/workflow.ts
1097
+ // src/resources/legacy-workflow.ts
363
1098
  var RECORD_SEPARATOR = "";
364
- var Workflow = class extends BaseResource {
1099
+ var LegacyWorkflow = class extends BaseResource {
365
1100
  constructor(options, workflowId) {
366
1101
  super(options);
367
1102
  this.workflowId = workflowId;
368
1103
  }
369
1104
  /**
370
- * Retrieves details about the workflow
371
- * @returns Promise containing workflow details including steps and graphs
1105
+ * Retrieves details about the legacy workflow
1106
+ * @returns Promise containing legacy workflow details including steps and graphs
372
1107
  */
373
1108
  details() {
374
- return this.request(`/api/workflows/${this.workflowId}`);
1109
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
375
1110
  }
376
1111
  /**
377
- * Retrieves all runs for a workflow
1112
+ * Retrieves all runs for a legacy workflow
378
1113
  * @param params - Parameters for filtering runs
379
- * @returns Promise containing workflow runs array
1114
+ * @returns Promise containing legacy workflow runs array
380
1115
  */
381
1116
  runs(params) {
382
1117
  const searchParams = new URLSearchParams();
@@ -396,25 +1131,13 @@ var Workflow = class extends BaseResource {
396
1131
  searchParams.set("resourceId", params.resourceId);
397
1132
  }
398
1133
  if (searchParams.size) {
399
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1134
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
400
1135
  } else {
401
- return this.request(`/api/workflows/${this.workflowId}/runs`);
1136
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
402
1137
  }
403
1138
  }
404
1139
  /**
405
- * @deprecated Use `startAsync` instead
406
- * Executes the workflow with the provided parameters
407
- * @param params - Parameters required for workflow execution
408
- * @returns Promise containing the workflow execution results
409
- */
410
- execute(params) {
411
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
412
- method: "POST",
413
- body: params
414
- });
415
- }
416
- /**
417
- * Creates a new workflow run
1140
+ * Creates a new legacy workflow run
418
1141
  * @returns Promise containing the generated run ID
419
1142
  */
420
1143
  createRun(params) {
@@ -422,34 +1145,34 @@ var Workflow = class extends BaseResource {
422
1145
  if (!!params?.runId) {
423
1146
  searchParams.set("runId", params.runId);
424
1147
  }
425
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
1148
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
426
1149
  method: "POST"
427
1150
  });
428
1151
  }
429
1152
  /**
430
- * Starts a workflow run synchronously without waiting for the workflow to complete
1153
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
431
1154
  * @param params - Object containing the runId and triggerData
432
1155
  * @returns Promise containing success message
433
1156
  */
434
1157
  start(params) {
435
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1158
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
436
1159
  method: "POST",
437
1160
  body: params?.triggerData
438
1161
  });
439
1162
  }
440
1163
  /**
441
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1164
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
442
1165
  * @param stepId - ID of the step to resume
443
- * @param runId - ID of the workflow run
444
- * @param context - Context to resume the workflow with
445
- * @returns Promise containing the workflow resume results
1166
+ * @param runId - ID of the legacy workflow run
1167
+ * @param context - Context to resume the legacy workflow with
1168
+ * @returns Promise containing the legacy workflow resume results
446
1169
  */
447
1170
  resume({
448
1171
  stepId,
449
1172
  runId,
450
1173
  context
451
1174
  }) {
452
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1175
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
453
1176
  method: "POST",
454
1177
  body: {
455
1178
  stepId,
@@ -467,18 +1190,18 @@ var Workflow = class extends BaseResource {
467
1190
  if (!!params?.runId) {
468
1191
  searchParams.set("runId", params.runId);
469
1192
  }
470
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1193
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
471
1194
  method: "POST",
472
1195
  body: params?.triggerData
473
1196
  });
474
1197
  }
475
1198
  /**
476
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1199
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
477
1200
  * @param params - Object containing the runId, stepId, and context
478
1201
  * @returns Promise containing the workflow resume results
479
1202
  */
480
1203
  resumeAsync(params) {
481
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1204
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
482
1205
  method: "POST",
483
1206
  body: {
484
1207
  stepId: params.stepId,
@@ -532,16 +1255,16 @@ var Workflow = class extends BaseResource {
532
1255
  }
533
1256
  }
534
1257
  /**
535
- * Watches workflow transitions in real-time
1258
+ * Watches legacy workflow transitions in real-time
536
1259
  * @param runId - Optional run ID to filter the watch stream
537
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1260
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
538
1261
  */
539
1262
  async watch({ runId }, onRecord) {
540
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1263
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
541
1264
  stream: true
542
1265
  });
543
1266
  if (!response.ok) {
544
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
1267
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
545
1268
  }
546
1269
  if (!response.body) {
547
1270
  throw new Error("Response body is null");
@@ -553,7 +1276,7 @@ var Workflow = class extends BaseResource {
553
1276
  };
554
1277
 
555
1278
  // src/resources/tool.ts
556
- var Tool = class extends BaseResource {
1279
+ var Tool2 = class extends BaseResource {
557
1280
  constructor(options, toolId) {
558
1281
  super(options);
559
1282
  this.toolId = toolId;
@@ -575,22 +1298,26 @@ var Tool = class extends BaseResource {
575
1298
  if (params.runId) {
576
1299
  url.set("runId", params.runId);
577
1300
  }
1301
+ const body = {
1302
+ data: params.data,
1303
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1304
+ };
578
1305
  return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
579
1306
  method: "POST",
580
- body: params.data
1307
+ body
581
1308
  });
582
1309
  }
583
1310
  };
584
1311
 
585
- // src/resources/vnext-workflow.ts
1312
+ // src/resources/workflow.ts
586
1313
  var RECORD_SEPARATOR2 = "";
587
- var VNextWorkflow = class extends BaseResource {
1314
+ var Workflow = class extends BaseResource {
588
1315
  constructor(options, workflowId) {
589
1316
  super(options);
590
1317
  this.workflowId = workflowId;
591
1318
  }
592
1319
  /**
593
- * Creates an async generator that processes a readable stream and yields vNext workflow records
1320
+ * Creates an async generator that processes a readable stream and yields workflow records
594
1321
  * separated by the Record Separator character (\x1E)
595
1322
  *
596
1323
  * @param stream - The readable stream to process
@@ -635,16 +1362,16 @@ var VNextWorkflow = class extends BaseResource {
635
1362
  }
636
1363
  }
637
1364
  /**
638
- * Retrieves details about the vNext workflow
639
- * @returns Promise containing vNext workflow details including steps and graphs
1365
+ * Retrieves details about the workflow
1366
+ * @returns Promise containing workflow details including steps and graphs
640
1367
  */
641
1368
  details() {
642
- return this.request(`/api/workflows/v-next/${this.workflowId}`);
1369
+ return this.request(`/api/workflows/${this.workflowId}`);
643
1370
  }
644
1371
  /**
645
- * Retrieves all runs for a vNext workflow
1372
+ * Retrieves all runs for a workflow
646
1373
  * @param params - Parameters for filtering runs
647
- * @returns Promise containing vNext workflow runs array
1374
+ * @returns Promise containing workflow runs array
648
1375
  */
649
1376
  runs(params) {
650
1377
  const searchParams = new URLSearchParams();
@@ -654,23 +1381,60 @@ var VNextWorkflow = class extends BaseResource {
654
1381
  if (params?.toDate) {
655
1382
  searchParams.set("toDate", params.toDate.toISOString());
656
1383
  }
657
- if (params?.limit) {
1384
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
658
1385
  searchParams.set("limit", String(params.limit));
659
1386
  }
660
- if (params?.offset) {
1387
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
661
1388
  searchParams.set("offset", String(params.offset));
662
1389
  }
663
1390
  if (params?.resourceId) {
664
1391
  searchParams.set("resourceId", params.resourceId);
665
1392
  }
666
1393
  if (searchParams.size) {
667
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs?${searchParams}`);
1394
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
668
1395
  } else {
669
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
1396
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
670
1397
  }
671
1398
  }
672
1399
  /**
673
- * Creates a new vNext workflow run
1400
+ * Retrieves a specific workflow run by its ID
1401
+ * @param runId - The ID of the workflow run to retrieve
1402
+ * @returns Promise containing the workflow run details
1403
+ */
1404
+ runById(runId) {
1405
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1406
+ }
1407
+ /**
1408
+ * Retrieves the execution result for a specific workflow run by its ID
1409
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1410
+ * @returns Promise containing the workflow run execution result
1411
+ */
1412
+ runExecutionResult(runId) {
1413
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1414
+ }
1415
+ /**
1416
+ * Cancels a specific workflow run by its ID
1417
+ * @param runId - The ID of the workflow run to cancel
1418
+ * @returns Promise containing a success message
1419
+ */
1420
+ cancelRun(runId) {
1421
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1422
+ method: "POST"
1423
+ });
1424
+ }
1425
+ /**
1426
+ * Sends an event to a specific workflow run by its ID
1427
+ * @param params - Object containing the runId, event and data
1428
+ * @returns Promise containing a success message
1429
+ */
1430
+ sendRunEvent(params) {
1431
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1432
+ method: "POST",
1433
+ body: { event: params.event, data: params.data }
1434
+ });
1435
+ }
1436
+ /**
1437
+ * Creates a new workflow run
674
1438
  * @param params - Optional object containing the optional runId
675
1439
  * @returns Promise containing the runId of the created run
676
1440
  */
@@ -679,23 +1443,32 @@ var VNextWorkflow = class extends BaseResource {
679
1443
  if (!!params?.runId) {
680
1444
  searchParams.set("runId", params.runId);
681
1445
  }
682
- return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
1446
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
683
1447
  method: "POST"
684
1448
  });
685
1449
  }
686
1450
  /**
687
- * Starts a vNext workflow run synchronously without waiting for the workflow to complete
1451
+ * Creates a new workflow run (alias for createRun)
1452
+ * @param params - Optional object containing the optional runId
1453
+ * @returns Promise containing the runId of the created run
1454
+ */
1455
+ createRunAsync(params) {
1456
+ return this.createRun(params);
1457
+ }
1458
+ /**
1459
+ * Starts a workflow run synchronously without waiting for the workflow to complete
688
1460
  * @param params - Object containing the runId, inputData and runtimeContext
689
1461
  * @returns Promise containing success message
690
1462
  */
691
1463
  start(params) {
692
- return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
1464
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1465
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
693
1466
  method: "POST",
694
- body: { inputData: params?.inputData, runtimeContext: params.runtimeContext }
1467
+ body: { inputData: params?.inputData, runtimeContext }
695
1468
  });
696
1469
  }
697
1470
  /**
698
- * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
1471
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
699
1472
  * @param params - Object containing the runId, step, resumeData and runtimeContext
700
1473
  * @returns Promise containing success message
701
1474
  */
@@ -703,9 +1476,10 @@ var VNextWorkflow = class extends BaseResource {
703
1476
  step,
704
1477
  runId,
705
1478
  resumeData,
706
- runtimeContext
1479
+ ...rest
707
1480
  }) {
708
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
1481
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1482
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
709
1483
  method: "POST",
710
1484
  stream: true,
711
1485
  body: {
@@ -716,68 +1490,443 @@ var VNextWorkflow = class extends BaseResource {
716
1490
  });
717
1491
  }
718
1492
  /**
719
- * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
1493
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
720
1494
  * @param params - Object containing the optional runId, inputData and runtimeContext
721
- * @returns Promise containing the vNext workflow execution results
1495
+ * @returns Promise containing the workflow execution results
722
1496
  */
723
1497
  startAsync(params) {
724
1498
  const searchParams = new URLSearchParams();
725
1499
  if (!!params?.runId) {
726
1500
  searchParams.set("runId", params.runId);
727
1501
  }
728
- return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
1502
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1503
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
729
1504
  method: "POST",
730
- body: { inputData: params.inputData, runtimeContext: params.runtimeContext }
1505
+ body: { inputData: params.inputData, runtimeContext }
731
1506
  });
732
1507
  }
733
1508
  /**
734
- * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
735
- * @param params - Object containing the runId, step, resumeData and runtimeContext
736
- * @returns Promise containing the vNext workflow resume results
1509
+ * Starts a workflow run and returns a stream
1510
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1511
+ * @returns Promise containing the workflow execution results
737
1512
  */
738
- resumeAsync(params) {
739
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
740
- method: "POST",
741
- body: {
742
- step: params.step,
743
- resumeData: params.resumeData,
744
- runtimeContext: params.runtimeContext
1513
+ async stream(params) {
1514
+ const searchParams = new URLSearchParams();
1515
+ if (!!params?.runId) {
1516
+ searchParams.set("runId", params.runId);
1517
+ }
1518
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1519
+ const response = await this.request(
1520
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1521
+ {
1522
+ method: "POST",
1523
+ body: { inputData: params.inputData, runtimeContext },
1524
+ stream: true
745
1525
  }
746
- });
747
- }
748
- /**
749
- * Watches vNext workflow transitions in real-time
750
- * @param runId - Optional run ID to filter the watch stream
751
- * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
752
- */
753
- async watch({ runId }, onRecord) {
754
- const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
755
- stream: true
756
- });
1526
+ );
757
1527
  if (!response.ok) {
758
- throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
1528
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
759
1529
  }
760
1530
  if (!response.body) {
761
1531
  throw new Error("Response body is null");
762
1532
  }
763
- for await (const record of this.streamProcessor(response.body)) {
764
- onRecord(record);
765
- }
766
- }
767
- };
1533
+ let failedChunk = void 0;
1534
+ const transformStream = new TransformStream({
1535
+ start() {
1536
+ },
1537
+ async transform(chunk, controller) {
1538
+ try {
1539
+ const decoded = new TextDecoder().decode(chunk);
1540
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1541
+ for (const chunk2 of chunks) {
1542
+ if (chunk2) {
1543
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1544
+ try {
1545
+ const parsedChunk = JSON.parse(newChunk);
1546
+ controller.enqueue(parsedChunk);
1547
+ failedChunk = void 0;
1548
+ } catch (error) {
1549
+ failedChunk = newChunk;
1550
+ }
1551
+ }
1552
+ }
1553
+ } catch {
1554
+ }
1555
+ }
1556
+ });
1557
+ return response.body.pipeThrough(transformStream);
1558
+ }
1559
+ /**
1560
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1561
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1562
+ * @returns Promise containing the workflow resume results
1563
+ */
1564
+ resumeAsync(params) {
1565
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1566
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1567
+ method: "POST",
1568
+ body: {
1569
+ step: params.step,
1570
+ resumeData: params.resumeData,
1571
+ runtimeContext
1572
+ }
1573
+ });
1574
+ }
1575
+ /**
1576
+ * Watches workflow transitions in real-time
1577
+ * @param runId - Optional run ID to filter the watch stream
1578
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1579
+ */
1580
+ async watch({ runId }, onRecord) {
1581
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1582
+ stream: true
1583
+ });
1584
+ if (!response.ok) {
1585
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1586
+ }
1587
+ if (!response.body) {
1588
+ throw new Error("Response body is null");
1589
+ }
1590
+ for await (const record of this.streamProcessor(response.body)) {
1591
+ if (typeof record === "string") {
1592
+ onRecord(JSON.parse(record));
1593
+ } else {
1594
+ onRecord(record);
1595
+ }
1596
+ }
1597
+ }
1598
+ /**
1599
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1600
+ * serializing each as JSON and separating them with the record separator (\x1E).
1601
+ *
1602
+ * @param records - An iterable or async iterable of objects to stream
1603
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1604
+ */
1605
+ static createRecordStream(records) {
1606
+ const encoder = new TextEncoder();
1607
+ return new ReadableStream({
1608
+ async start(controller) {
1609
+ try {
1610
+ for await (const record of records) {
1611
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1612
+ controller.enqueue(encoder.encode(json));
1613
+ }
1614
+ controller.close();
1615
+ } catch (err) {
1616
+ controller.error(err);
1617
+ }
1618
+ }
1619
+ });
1620
+ }
1621
+ };
768
1622
 
769
- // src/resources/mcp.ts
770
- var MCPServer = class extends BaseResource {
771
- constructor(options, serverId) {
1623
+ // src/resources/a2a.ts
1624
+ var A2A = class extends BaseResource {
1625
+ constructor(options, agentId) {
1626
+ super(options);
1627
+ this.agentId = agentId;
1628
+ }
1629
+ /**
1630
+ * Get the agent card with metadata about the agent
1631
+ * @returns Promise containing the agent card information
1632
+ */
1633
+ async getCard() {
1634
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1635
+ }
1636
+ /**
1637
+ * Send a message to the agent and gets a message or task response
1638
+ * @param params - Parameters for the task
1639
+ * @returns Promise containing the response
1640
+ */
1641
+ async sendMessage(params) {
1642
+ const response = await this.request(`/a2a/${this.agentId}`, {
1643
+ method: "POST",
1644
+ body: {
1645
+ method: "message/send",
1646
+ params
1647
+ }
1648
+ });
1649
+ return response;
1650
+ }
1651
+ /**
1652
+ * Sends a message to an agent to initiate/continue a task and subscribes
1653
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
1654
+ * @param params - Parameters for the task
1655
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
1656
+ */
1657
+ async sendStreamingMessage(params) {
1658
+ const response = await this.request(`/a2a/${this.agentId}`, {
1659
+ method: "POST",
1660
+ body: {
1661
+ method: "message/stream",
1662
+ params
1663
+ }
1664
+ });
1665
+ return response;
1666
+ }
1667
+ /**
1668
+ * Get the status and result of a task
1669
+ * @param params - Parameters for querying the task
1670
+ * @returns Promise containing the task response
1671
+ */
1672
+ async getTask(params) {
1673
+ const response = await this.request(`/a2a/${this.agentId}`, {
1674
+ method: "POST",
1675
+ body: {
1676
+ method: "tasks/get",
1677
+ params
1678
+ }
1679
+ });
1680
+ return response;
1681
+ }
1682
+ /**
1683
+ * Cancel a running task
1684
+ * @param params - Parameters identifying the task to cancel
1685
+ * @returns Promise containing the task response
1686
+ */
1687
+ async cancelTask(params) {
1688
+ return this.request(`/a2a/${this.agentId}`, {
1689
+ method: "POST",
1690
+ body: {
1691
+ method: "tasks/cancel",
1692
+ params
1693
+ }
1694
+ });
1695
+ }
1696
+ };
1697
+
1698
+ // src/resources/mcp-tool.ts
1699
+ var MCPTool = class extends BaseResource {
1700
+ serverId;
1701
+ toolId;
1702
+ constructor(options, serverId, toolId) {
772
1703
  super(options);
773
1704
  this.serverId = serverId;
1705
+ this.toolId = toolId;
774
1706
  }
775
1707
  /**
776
- * Get details about the MCP server
777
- * @returns Promise containing server details
1708
+ * Retrieves details about this specific tool from the MCP server.
1709
+ * @returns Promise containing the tool's information (name, description, schema).
778
1710
  */
779
1711
  details() {
780
- return this.request(`/api/mcp/servers/${this.serverId}`);
1712
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1713
+ }
1714
+ /**
1715
+ * Executes this specific tool on the MCP server.
1716
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1717
+ * @returns Promise containing the result of the tool execution.
1718
+ */
1719
+ execute(params) {
1720
+ const body = {};
1721
+ if (params.data !== void 0) body.data = params.data;
1722
+ if (params.runtimeContext !== void 0) {
1723
+ body.runtimeContext = params.runtimeContext;
1724
+ }
1725
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1726
+ method: "POST",
1727
+ body: Object.keys(body).length > 0 ? body : void 0
1728
+ });
1729
+ }
1730
+ };
1731
+
1732
+ // src/resources/network-memory-thread.ts
1733
+ var NetworkMemoryThread = class extends BaseResource {
1734
+ constructor(options, threadId, networkId) {
1735
+ super(options);
1736
+ this.threadId = threadId;
1737
+ this.networkId = networkId;
1738
+ }
1739
+ /**
1740
+ * Retrieves the memory thread details
1741
+ * @returns Promise containing thread details including title and metadata
1742
+ */
1743
+ get() {
1744
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1745
+ }
1746
+ /**
1747
+ * Updates the memory thread properties
1748
+ * @param params - Update parameters including title and metadata
1749
+ * @returns Promise containing updated thread details
1750
+ */
1751
+ update(params) {
1752
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1753
+ method: "PATCH",
1754
+ body: params
1755
+ });
1756
+ }
1757
+ /**
1758
+ * Deletes the memory thread
1759
+ * @returns Promise containing deletion result
1760
+ */
1761
+ delete() {
1762
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1763
+ method: "DELETE"
1764
+ });
1765
+ }
1766
+ /**
1767
+ * Retrieves messages associated with the thread
1768
+ * @param params - Optional parameters including limit for number of messages to retrieve
1769
+ * @returns Promise containing thread messages and UI messages
1770
+ */
1771
+ getMessages(params) {
1772
+ const query = new URLSearchParams({
1773
+ networkId: this.networkId,
1774
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1775
+ });
1776
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1777
+ }
1778
+ /**
1779
+ * Deletes one or more messages from the thread
1780
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1781
+ * message object with id property, or array of message objects
1782
+ * @returns Promise containing deletion result
1783
+ */
1784
+ deleteMessages(messageIds) {
1785
+ const query = new URLSearchParams({
1786
+ networkId: this.networkId
1787
+ });
1788
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
1789
+ method: "POST",
1790
+ body: { messageIds }
1791
+ });
1792
+ }
1793
+ };
1794
+
1795
+ // src/resources/vNextNetwork.ts
1796
+ var RECORD_SEPARATOR3 = "";
1797
+ var VNextNetwork = class extends BaseResource {
1798
+ constructor(options, networkId) {
1799
+ super(options);
1800
+ this.networkId = networkId;
1801
+ }
1802
+ /**
1803
+ * Retrieves details about the network
1804
+ * @returns Promise containing vNext network details
1805
+ */
1806
+ details() {
1807
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1808
+ }
1809
+ /**
1810
+ * Generates a response from the v-next network
1811
+ * @param params - Generation parameters including message
1812
+ * @returns Promise containing the generated response
1813
+ */
1814
+ generate(params) {
1815
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1816
+ method: "POST",
1817
+ body: {
1818
+ ...params,
1819
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1820
+ }
1821
+ });
1822
+ }
1823
+ /**
1824
+ * Generates a response from the v-next network using multiple primitives
1825
+ * @param params - Generation parameters including message
1826
+ * @returns Promise containing the generated response
1827
+ */
1828
+ loop(params) {
1829
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1830
+ method: "POST",
1831
+ body: {
1832
+ ...params,
1833
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1834
+ }
1835
+ });
1836
+ }
1837
+ async *streamProcessor(stream) {
1838
+ const reader = stream.getReader();
1839
+ let doneReading = false;
1840
+ let buffer = "";
1841
+ try {
1842
+ while (!doneReading) {
1843
+ const { done, value } = await reader.read();
1844
+ doneReading = done;
1845
+ if (done && !value) continue;
1846
+ try {
1847
+ const decoded = value ? new TextDecoder().decode(value) : "";
1848
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1849
+ buffer = chunks.pop() || "";
1850
+ for (const chunk of chunks) {
1851
+ if (chunk) {
1852
+ if (typeof chunk === "string") {
1853
+ try {
1854
+ const parsedChunk = JSON.parse(chunk);
1855
+ yield parsedChunk;
1856
+ } catch {
1857
+ }
1858
+ }
1859
+ }
1860
+ }
1861
+ } catch {
1862
+ }
1863
+ }
1864
+ if (buffer) {
1865
+ try {
1866
+ yield JSON.parse(buffer);
1867
+ } catch {
1868
+ }
1869
+ }
1870
+ } finally {
1871
+ reader.cancel().catch(() => {
1872
+ });
1873
+ }
1874
+ }
1875
+ /**
1876
+ * Streams a response from the v-next network
1877
+ * @param params - Stream parameters including message
1878
+ * @returns Promise containing the results
1879
+ */
1880
+ async stream(params, onRecord) {
1881
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1882
+ method: "POST",
1883
+ body: {
1884
+ ...params,
1885
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1886
+ },
1887
+ stream: true
1888
+ });
1889
+ if (!response.ok) {
1890
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1891
+ }
1892
+ if (!response.body) {
1893
+ throw new Error("Response body is null");
1894
+ }
1895
+ for await (const record of this.streamProcessor(response.body)) {
1896
+ if (typeof record === "string") {
1897
+ onRecord(JSON.parse(record));
1898
+ } else {
1899
+ onRecord(record);
1900
+ }
1901
+ }
1902
+ }
1903
+ /**
1904
+ * Streams a response from the v-next network loop
1905
+ * @param params - Stream parameters including message
1906
+ * @returns Promise containing the results
1907
+ */
1908
+ async loopStream(params, onRecord) {
1909
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1910
+ method: "POST",
1911
+ body: {
1912
+ ...params,
1913
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1914
+ },
1915
+ stream: true
1916
+ });
1917
+ if (!response.ok) {
1918
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1919
+ }
1920
+ if (!response.body) {
1921
+ throw new Error("Response body is null");
1922
+ }
1923
+ for await (const record of this.streamProcessor(response.body)) {
1924
+ if (typeof record === "string") {
1925
+ onRecord(JSON.parse(record));
1926
+ } else {
1927
+ onRecord(record);
1928
+ }
1929
+ }
781
1930
  }
782
1931
  };
783
1932
 
@@ -793,6 +1942,21 @@ var MastraClient = class extends BaseResource {
793
1942
  getAgents() {
794
1943
  return this.request("/api/agents");
795
1944
  }
1945
+ async getAGUI({ resourceId }) {
1946
+ const agents = await this.getAgents();
1947
+ return Object.entries(agents).reduce(
1948
+ (acc, [agentId]) => {
1949
+ const agent = this.getAgent(agentId);
1950
+ acc[agentId] = new AGUIAdapter({
1951
+ agentId,
1952
+ agent,
1953
+ resourceId
1954
+ });
1955
+ return acc;
1956
+ },
1957
+ {}
1958
+ );
1959
+ }
796
1960
  /**
797
1961
  * Gets an agent instance by ID
798
1962
  * @param agentId - ID of the agent to retrieve
@@ -843,6 +2007,48 @@ var MastraClient = class extends BaseResource {
843
2007
  getMemoryStatus(agentId) {
844
2008
  return this.request(`/api/memory/status?agentId=${agentId}`);
845
2009
  }
2010
+ /**
2011
+ * Retrieves memory threads for a resource
2012
+ * @param params - Parameters containing the resource ID
2013
+ * @returns Promise containing array of memory threads
2014
+ */
2015
+ getNetworkMemoryThreads(params) {
2016
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
2017
+ }
2018
+ /**
2019
+ * Creates a new memory thread
2020
+ * @param params - Parameters for creating the memory thread
2021
+ * @returns Promise containing the created memory thread
2022
+ */
2023
+ createNetworkMemoryThread(params) {
2024
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
2025
+ }
2026
+ /**
2027
+ * Gets a memory thread instance by ID
2028
+ * @param threadId - ID of the memory thread to retrieve
2029
+ * @returns MemoryThread instance
2030
+ */
2031
+ getNetworkMemoryThread(threadId, networkId) {
2032
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2033
+ }
2034
+ /**
2035
+ * Saves messages to memory
2036
+ * @param params - Parameters containing messages to save
2037
+ * @returns Promise containing the saved messages
2038
+ */
2039
+ saveNetworkMessageToMemory(params) {
2040
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2041
+ method: "POST",
2042
+ body: params
2043
+ });
2044
+ }
2045
+ /**
2046
+ * Gets the status of the memory system
2047
+ * @returns Promise containing memory system status
2048
+ */
2049
+ getNetworkMemoryStatus(networkId) {
2050
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2051
+ }
846
2052
  /**
847
2053
  * Retrieves all available tools
848
2054
  * @returns Promise containing map of tool IDs to tool details
@@ -856,7 +2062,22 @@ var MastraClient = class extends BaseResource {
856
2062
  * @returns Tool instance
857
2063
  */
858
2064
  getTool(toolId) {
859
- return new Tool(this.options, toolId);
2065
+ return new Tool2(this.options, toolId);
2066
+ }
2067
+ /**
2068
+ * Retrieves all available legacy workflows
2069
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2070
+ */
2071
+ getLegacyWorkflows() {
2072
+ return this.request("/api/workflows/legacy");
2073
+ }
2074
+ /**
2075
+ * Gets a legacy workflow instance by ID
2076
+ * @param workflowId - ID of the legacy workflow to retrieve
2077
+ * @returns Legacy Workflow instance
2078
+ */
2079
+ getLegacyWorkflow(workflowId) {
2080
+ return new LegacyWorkflow(this.options, workflowId);
860
2081
  }
861
2082
  /**
862
2083
  * Retrieves all available workflows
@@ -873,21 +2094,6 @@ var MastraClient = class extends BaseResource {
873
2094
  getWorkflow(workflowId) {
874
2095
  return new Workflow(this.options, workflowId);
875
2096
  }
876
- /**
877
- * Retrieves all available vNext workflows
878
- * @returns Promise containing map of vNext workflow IDs to vNext workflow details
879
- */
880
- getVNextWorkflows() {
881
- return this.request("/api/workflows/v-next");
882
- }
883
- /**
884
- * Gets a vNext workflow instance by ID
885
- * @param workflowId - ID of the vNext workflow to retrieve
886
- * @returns vNext Workflow instance
887
- */
888
- getVNextWorkflow(workflowId) {
889
- return new VNextWorkflow(this.options, workflowId);
890
- }
891
2097
  /**
892
2098
  * Gets a vector instance by name
893
2099
  * @param vectorName - Name of the vector to retrieve
@@ -902,7 +2108,41 @@ var MastraClient = class extends BaseResource {
902
2108
  * @returns Promise containing array of log messages
903
2109
  */
904
2110
  getLogs(params) {
905
- return this.request(`/api/logs?transportId=${params.transportId}`);
2111
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2112
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2113
+ const searchParams = new URLSearchParams();
2114
+ if (transportId) {
2115
+ searchParams.set("transportId", transportId);
2116
+ }
2117
+ if (fromDate) {
2118
+ searchParams.set("fromDate", fromDate.toISOString());
2119
+ }
2120
+ if (toDate) {
2121
+ searchParams.set("toDate", toDate.toISOString());
2122
+ }
2123
+ if (logLevel) {
2124
+ searchParams.set("logLevel", logLevel);
2125
+ }
2126
+ if (page) {
2127
+ searchParams.set("page", String(page));
2128
+ }
2129
+ if (perPage) {
2130
+ searchParams.set("perPage", String(perPage));
2131
+ }
2132
+ if (_filters) {
2133
+ if (Array.isArray(_filters)) {
2134
+ for (const filter of _filters) {
2135
+ searchParams.append("filters", filter);
2136
+ }
2137
+ } else {
2138
+ searchParams.set("filters", _filters);
2139
+ }
2140
+ }
2141
+ if (searchParams.size) {
2142
+ return this.request(`/api/logs?${searchParams}`);
2143
+ } else {
2144
+ return this.request(`/api/logs`);
2145
+ }
906
2146
  }
907
2147
  /**
908
2148
  * Gets logs for a specific run
@@ -910,7 +2150,44 @@ var MastraClient = class extends BaseResource {
910
2150
  * @returns Promise containing array of log messages
911
2151
  */
912
2152
  getLogForRun(params) {
913
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2153
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2154
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2155
+ const searchParams = new URLSearchParams();
2156
+ if (runId) {
2157
+ searchParams.set("runId", runId);
2158
+ }
2159
+ if (transportId) {
2160
+ searchParams.set("transportId", transportId);
2161
+ }
2162
+ if (fromDate) {
2163
+ searchParams.set("fromDate", fromDate.toISOString());
2164
+ }
2165
+ if (toDate) {
2166
+ searchParams.set("toDate", toDate.toISOString());
2167
+ }
2168
+ if (logLevel) {
2169
+ searchParams.set("logLevel", logLevel);
2170
+ }
2171
+ if (page) {
2172
+ searchParams.set("page", String(page));
2173
+ }
2174
+ if (perPage) {
2175
+ searchParams.set("perPage", String(perPage));
2176
+ }
2177
+ if (_filters) {
2178
+ if (Array.isArray(_filters)) {
2179
+ for (const filter of _filters) {
2180
+ searchParams.append("filters", filter);
2181
+ }
2182
+ } else {
2183
+ searchParams.set("filters", _filters);
2184
+ }
2185
+ }
2186
+ if (searchParams.size) {
2187
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2188
+ } else {
2189
+ return this.request(`/api/logs/${runId}`);
2190
+ }
914
2191
  }
915
2192
  /**
916
2193
  * List of all log transports
@@ -968,6 +2245,13 @@ var MastraClient = class extends BaseResource {
968
2245
  getNetworks() {
969
2246
  return this.request("/api/networks");
970
2247
  }
2248
+ /**
2249
+ * Retrieves all available vNext networks
2250
+ * @returns Promise containing map of vNext network IDs to vNext network details
2251
+ */
2252
+ getVNextNetworks() {
2253
+ return this.request("/api/networks/v-next");
2254
+ }
971
2255
  /**
972
2256
  * Gets a network instance by ID
973
2257
  * @param networkId - ID of the network to retrieve
@@ -977,20 +2261,191 @@ var MastraClient = class extends BaseResource {
977
2261
  return new Network(this.options, networkId);
978
2262
  }
979
2263
  /**
980
- * Retrieves all available MCP servers
981
- * @returns Promise containing map of MCP server IDs to server details
2264
+ * Gets a vNext network instance by ID
2265
+ * @param networkId - ID of the vNext network to retrieve
2266
+ * @returns vNext Network instance
2267
+ */
2268
+ getVNextNetwork(networkId) {
2269
+ return new VNextNetwork(this.options, networkId);
2270
+ }
2271
+ /**
2272
+ * Retrieves a list of available MCP servers.
2273
+ * @param params - Optional parameters for pagination (limit, offset).
2274
+ * @returns Promise containing the list of MCP servers and pagination info.
2275
+ */
2276
+ getMcpServers(params) {
2277
+ const searchParams = new URLSearchParams();
2278
+ if (params?.limit !== void 0) {
2279
+ searchParams.set("limit", String(params.limit));
2280
+ }
2281
+ if (params?.offset !== void 0) {
2282
+ searchParams.set("offset", String(params.offset));
2283
+ }
2284
+ const queryString = searchParams.toString();
2285
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
2286
+ }
2287
+ /**
2288
+ * Retrieves detailed information for a specific MCP server.
2289
+ * @param serverId - The ID of the MCP server to retrieve.
2290
+ * @param params - Optional parameters, e.g., specific version.
2291
+ * @returns Promise containing the detailed MCP server information.
2292
+ */
2293
+ getMcpServerDetails(serverId, params) {
2294
+ const searchParams = new URLSearchParams();
2295
+ if (params?.version) {
2296
+ searchParams.set("version", params.version);
2297
+ }
2298
+ const queryString = searchParams.toString();
2299
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
2300
+ }
2301
+ /**
2302
+ * Retrieves a list of tools for a specific MCP server.
2303
+ * @param serverId - The ID of the MCP server.
2304
+ * @returns Promise containing the list of tools.
2305
+ */
2306
+ getMcpServerTools(serverId) {
2307
+ return this.request(`/api/mcp/${serverId}/tools`);
2308
+ }
2309
+ /**
2310
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
2311
+ * This instance can then be used to fetch details or execute the tool.
2312
+ * @param serverId - The ID of the MCP server.
2313
+ * @param toolId - The ID of the tool.
2314
+ * @returns MCPTool instance.
982
2315
  */
983
- getMCPServers() {
984
- return this.request("/api/mcp/servers");
2316
+ getMcpServerTool(serverId, toolId) {
2317
+ return new MCPTool(this.options, serverId, toolId);
2318
+ }
2319
+ /**
2320
+ * Gets an A2A client for interacting with an agent via the A2A protocol
2321
+ * @param agentId - ID of the agent to interact with
2322
+ * @returns A2A client instance
2323
+ */
2324
+ getA2A(agentId) {
2325
+ return new A2A(this.options, agentId);
2326
+ }
2327
+ /**
2328
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2329
+ * @param agentId - ID of the agent.
2330
+ * @param threadId - ID of the thread.
2331
+ * @param resourceId - Optional ID of the resource.
2332
+ * @returns Working memory for the specified thread or resource.
2333
+ */
2334
+ getWorkingMemory({
2335
+ agentId,
2336
+ threadId,
2337
+ resourceId
2338
+ }) {
2339
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2340
+ }
2341
+ /**
2342
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2343
+ * @param agentId - ID of the agent.
2344
+ * @param threadId - ID of the thread.
2345
+ * @param workingMemory - The new working memory content.
2346
+ * @param resourceId - Optional ID of the resource.
2347
+ */
2348
+ updateWorkingMemory({
2349
+ agentId,
2350
+ threadId,
2351
+ workingMemory,
2352
+ resourceId
2353
+ }) {
2354
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2355
+ method: "POST",
2356
+ body: {
2357
+ workingMemory,
2358
+ resourceId
2359
+ }
2360
+ });
2361
+ }
2362
+ /**
2363
+ * Retrieves all available scorers
2364
+ * @returns Promise containing list of available scorers
2365
+ */
2366
+ getScorers() {
2367
+ return this.request("/api/scores/scorers");
2368
+ }
2369
+ /**
2370
+ * Retrieves a scorer by ID
2371
+ * @param scorerId - ID of the scorer to retrieve
2372
+ * @returns Promise containing the scorer
2373
+ */
2374
+ getScorer(scorerId) {
2375
+ return this.request(`/api/scores/scorers/${scorerId}`);
2376
+ }
2377
+ getScoresByScorerId(params) {
2378
+ const { page, perPage, scorerId, entityId, entityType } = params;
2379
+ const searchParams = new URLSearchParams();
2380
+ if (entityId) {
2381
+ searchParams.set("entityId", entityId);
2382
+ }
2383
+ if (entityType) {
2384
+ searchParams.set("entityType", entityType);
2385
+ }
2386
+ if (page !== void 0) {
2387
+ searchParams.set("page", String(page));
2388
+ }
2389
+ if (perPage !== void 0) {
2390
+ searchParams.set("perPage", String(perPage));
2391
+ }
2392
+ const queryString = searchParams.toString();
2393
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
2394
+ }
2395
+ /**
2396
+ * Retrieves scores by run ID
2397
+ * @param params - Parameters containing run ID and pagination options
2398
+ * @returns Promise containing scores and pagination info
2399
+ */
2400
+ getScoresByRunId(params) {
2401
+ const { runId, page, perPage } = params;
2402
+ const searchParams = new URLSearchParams();
2403
+ if (page !== void 0) {
2404
+ searchParams.set("page", String(page));
2405
+ }
2406
+ if (perPage !== void 0) {
2407
+ searchParams.set("perPage", String(perPage));
2408
+ }
2409
+ const queryString = searchParams.toString();
2410
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
2411
+ }
2412
+ /**
2413
+ * Retrieves scores by entity ID and type
2414
+ * @param params - Parameters containing entity ID, type, and pagination options
2415
+ * @returns Promise containing scores and pagination info
2416
+ */
2417
+ getScoresByEntityId(params) {
2418
+ const { entityId, entityType, page, perPage } = params;
2419
+ const searchParams = new URLSearchParams();
2420
+ if (page !== void 0) {
2421
+ searchParams.set("page", String(page));
2422
+ }
2423
+ if (perPage !== void 0) {
2424
+ searchParams.set("perPage", String(perPage));
2425
+ }
2426
+ const queryString = searchParams.toString();
2427
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
2428
+ }
2429
+ /**
2430
+ * Saves a score
2431
+ * @param params - Parameters containing the score data to save
2432
+ * @returns Promise containing the saved score
2433
+ */
2434
+ saveScore(params) {
2435
+ return this.request("/api/scores", {
2436
+ method: "POST",
2437
+ body: params
2438
+ });
985
2439
  }
986
2440
  /**
987
- * Gets an MCP server instance by ID
988
- * @param serverId - ID of the MCP server to retrieve
989
- * @returns MCPServer instance
2441
+ * Retrieves model providers with available keys
2442
+ * @returns Promise containing model providers with available keys
990
2443
  */
991
- getMCPServer(serverId) {
992
- return new MCPServer(this.options, serverId);
2444
+ getModelProviders() {
2445
+ return this.request(`/api/model-providers`);
993
2446
  }
994
2447
  };
995
2448
 
996
2449
  exports.MastraClient = MastraClient;
2450
+ //# sourceMappingURL=index.cjs.map
2451
+ //# sourceMappingURL=index.cjs.map