@mastra/client-js 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-remove-unused-import-20250909212718

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