@mastra/client-js 0.0.0-working-memory-per-user-20250620163010 → 0.0.0-zod-v4-compat-part-2-20250820135355

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 (76) hide show
  1. package/CHANGELOG.md +601 -3
  2. package/LICENSE.md +11 -42
  3. package/README.md +1 -0
  4. package/dist/adapters/agui.d.ts +23 -0
  5. package/dist/adapters/agui.d.ts.map +1 -0
  6. package/dist/client.d.ts +265 -0
  7. package/dist/client.d.ts.map +1 -0
  8. package/dist/example.d.ts +2 -0
  9. package/dist/example.d.ts.map +1 -0
  10. package/dist/index.cjs +883 -22
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.ts +4 -952
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +884 -23
  15. package/dist/index.js.map +1 -0
  16. package/dist/resources/a2a.d.ts +44 -0
  17. package/dist/resources/a2a.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +112 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +11 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/legacy-workflow.d.ts +87 -0
  25. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  26. package/dist/resources/mcp-tool.d.ts +27 -0
  27. package/dist/resources/mcp-tool.d.ts.map +1 -0
  28. package/dist/resources/memory-thread.d.ts +53 -0
  29. package/dist/resources/memory-thread.d.ts.map +1 -0
  30. package/dist/resources/network-memory-thread.d.ts +47 -0
  31. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  32. package/dist/resources/network.d.ts +30 -0
  33. package/dist/resources/network.d.ts.map +1 -0
  34. package/dist/resources/tool.d.ts +23 -0
  35. package/dist/resources/tool.d.ts.map +1 -0
  36. package/dist/resources/vNextNetwork.d.ts +42 -0
  37. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  38. package/dist/resources/vector.d.ts +48 -0
  39. package/dist/resources/vector.d.ts.map +1 -0
  40. package/dist/resources/workflow.d.ts +154 -0
  41. package/dist/resources/workflow.d.ts.map +1 -0
  42. package/dist/types.d.ts +422 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/utils/index.d.ts +3 -0
  45. package/dist/utils/index.d.ts.map +1 -0
  46. package/dist/utils/process-client-tools.d.ts +3 -0
  47. package/dist/utils/process-client-tools.d.ts.map +1 -0
  48. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  49. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  50. package/integration-tests/agui-adapter.test.ts +122 -0
  51. package/integration-tests/package.json +18 -0
  52. package/integration-tests/src/mastra/index.ts +35 -0
  53. package/integration-tests/vitest.config.ts +9 -0
  54. package/package.json +16 -12
  55. package/src/adapters/agui.test.ts +145 -3
  56. package/src/client.ts +214 -1
  57. package/src/example.ts +46 -15
  58. package/src/index.test.ts +402 -6
  59. package/src/index.ts +1 -0
  60. package/src/resources/agent.ts +593 -25
  61. package/src/resources/base.ts +6 -0
  62. package/src/resources/memory-thread.test.ts +285 -0
  63. package/src/resources/memory-thread.ts +36 -0
  64. package/src/resources/network-memory-thread.test.ts +269 -0
  65. package/src/resources/network-memory-thread.ts +81 -0
  66. package/src/resources/network.ts +6 -6
  67. package/src/resources/vNextNetwork.ts +194 -0
  68. package/src/resources/workflow.ts +45 -8
  69. package/src/types.ts +171 -8
  70. package/src/utils/process-client-tools.ts +4 -3
  71. package/src/utils/zod-to-json-schema.ts +20 -3
  72. package/src/v2-messages.test.ts +180 -0
  73. package/tsconfig.build.json +9 -0
  74. package/tsconfig.json +1 -1
  75. package/tsup.config.ts +22 -0
  76. package/dist/index.d.cts +0 -952
package/dist/index.cjs CHANGED
@@ -5,7 +5,8 @@ var rxjs = require('rxjs');
5
5
  var uiUtils = require('@ai-sdk/ui-utils');
6
6
  var zod = require('zod');
7
7
  var originalZodToJsonSchema = require('zod-to-json-schema');
8
- var tools = require('@mastra/core/tools');
8
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
9
+ var uuid = require('@lukeed/uuid');
9
10
  var runtimeContext = require('@mastra/core/runtime-context');
10
11
 
11
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -197,10 +198,16 @@ function convertMessagesToMastraMessages(messages) {
197
198
  }
198
199
  return result;
199
200
  }
201
+ function isZodType(value) {
202
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
203
+ }
200
204
  function zodToJsonSchema(zodSchema) {
201
- if (!(zodSchema instanceof zod.ZodSchema)) {
205
+ if (!isZodType(zodSchema)) {
202
206
  return zodSchema;
203
207
  }
208
+ if ("toJSONSchema" in zod.z) {
209
+ return zod.z.toJSONSchema(zodSchema);
210
+ }
204
211
  return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
205
212
  }
206
213
  function processClientTools(clientTools) {
@@ -209,7 +216,7 @@ function processClientTools(clientTools) {
209
216
  }
210
217
  return Object.fromEntries(
211
218
  Object.entries(clientTools).map(([key, value]) => {
212
- if (tools.isVercelTool(value)) {
219
+ if (isVercelTool.isVercelTool(value)) {
213
220
  return [
214
221
  key,
215
222
  {
@@ -252,11 +259,13 @@ var BaseResource = class {
252
259
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
253
260
  ...options,
254
261
  headers: {
262
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
255
263
  ...headers,
256
264
  ...options.headers
257
265
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
258
266
  // 'x-mastra-client-type': 'js',
259
267
  },
268
+ signal: this.options.abortSignal,
260
269
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
261
270
  });
262
271
  if (!response.ok) {
@@ -298,8 +307,6 @@ function parseClientRuntimeContext(runtimeContext$1) {
298
307
  }
299
308
  return void 0;
300
309
  }
301
-
302
- // src/resources/agent.ts
303
310
  var AgentVoice = class extends BaseResource {
304
311
  constructor(options, agentId) {
305
312
  super(options);
@@ -368,7 +375,7 @@ var Agent = class extends BaseResource {
368
375
  details() {
369
376
  return this.request(`/api/agents/${this.agentId}`);
370
377
  }
371
- generate(params) {
378
+ async generate(params) {
372
379
  const processedParams = {
373
380
  ...params,
374
381
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -376,10 +383,317 @@ var Agent = class extends BaseResource {
376
383
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
377
384
  clientTools: processClientTools(params.clientTools)
378
385
  };
379
- return this.request(`/api/agents/${this.agentId}/generate`, {
380
- method: "POST",
381
- body: processedParams
386
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
387
+ const response = await this.request(
388
+ `/api/agents/${this.agentId}/generate`,
389
+ {
390
+ method: "POST",
391
+ body: processedParams
392
+ }
393
+ );
394
+ if (response.finishReason === "tool-calls") {
395
+ const toolCalls = response.toolCalls;
396
+ if (!toolCalls || !Array.isArray(toolCalls)) {
397
+ return response;
398
+ }
399
+ for (const toolCall of toolCalls) {
400
+ const clientTool = params.clientTools?.[toolCall.toolName];
401
+ if (clientTool && clientTool.execute) {
402
+ const result = await clientTool.execute(
403
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
404
+ {
405
+ messages: response.messages,
406
+ toolCallId: toolCall?.toolCallId
407
+ }
408
+ );
409
+ const updatedMessages = [
410
+ {
411
+ role: "user",
412
+ content: params.messages
413
+ },
414
+ ...response.response.messages,
415
+ {
416
+ role: "tool",
417
+ content: [
418
+ {
419
+ type: "tool-result",
420
+ toolCallId: toolCall.toolCallId,
421
+ toolName: toolCall.toolName,
422
+ result
423
+ }
424
+ ]
425
+ }
426
+ ];
427
+ return this.generate({
428
+ ...params,
429
+ messages: updatedMessages
430
+ });
431
+ }
432
+ }
433
+ }
434
+ return response;
435
+ }
436
+ async processChatResponse({
437
+ stream,
438
+ update,
439
+ onToolCall,
440
+ onFinish,
441
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
442
+ lastMessage
443
+ }) {
444
+ const replaceLastMessage = lastMessage?.role === "assistant";
445
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
446
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
447
+ return Math.max(max, toolInvocation.step ?? 0);
448
+ }, 0) ?? 0) : 0;
449
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
450
+ id: uuid.v4(),
451
+ createdAt: getCurrentDate(),
452
+ role: "assistant",
453
+ content: "",
454
+ parts: []
455
+ };
456
+ let currentTextPart = void 0;
457
+ let currentReasoningPart = void 0;
458
+ let currentReasoningTextDetail = void 0;
459
+ function updateToolInvocationPart(toolCallId, invocation) {
460
+ const part = message.parts.find(
461
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
462
+ );
463
+ if (part != null) {
464
+ part.toolInvocation = invocation;
465
+ } else {
466
+ message.parts.push({
467
+ type: "tool-invocation",
468
+ toolInvocation: invocation
469
+ });
470
+ }
471
+ }
472
+ const data = [];
473
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
474
+ const partialToolCalls = {};
475
+ let usage = {
476
+ completionTokens: NaN,
477
+ promptTokens: NaN,
478
+ totalTokens: NaN
479
+ };
480
+ let finishReason = "unknown";
481
+ function execUpdate() {
482
+ const copiedData = [...data];
483
+ if (messageAnnotations?.length) {
484
+ message.annotations = messageAnnotations;
485
+ }
486
+ const copiedMessage = {
487
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
488
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
489
+ ...structuredClone(message),
490
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
491
+ // hashing approach by default to detect changes, but it only works for shallow
492
+ // changes. This is why we need to add a revision id to ensure that the message
493
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
494
+ // forwarded to rendering):
495
+ revisionId: uuid.v4()
496
+ };
497
+ update({
498
+ message: copiedMessage,
499
+ data: copiedData,
500
+ replaceLastMessage
501
+ });
502
+ }
503
+ await uiUtils.processDataStream({
504
+ stream,
505
+ onTextPart(value) {
506
+ if (currentTextPart == null) {
507
+ currentTextPart = {
508
+ type: "text",
509
+ text: value
510
+ };
511
+ message.parts.push(currentTextPart);
512
+ } else {
513
+ currentTextPart.text += value;
514
+ }
515
+ message.content += value;
516
+ execUpdate();
517
+ },
518
+ onReasoningPart(value) {
519
+ if (currentReasoningTextDetail == null) {
520
+ currentReasoningTextDetail = { type: "text", text: value };
521
+ if (currentReasoningPart != null) {
522
+ currentReasoningPart.details.push(currentReasoningTextDetail);
523
+ }
524
+ } else {
525
+ currentReasoningTextDetail.text += value;
526
+ }
527
+ if (currentReasoningPart == null) {
528
+ currentReasoningPart = {
529
+ type: "reasoning",
530
+ reasoning: value,
531
+ details: [currentReasoningTextDetail]
532
+ };
533
+ message.parts.push(currentReasoningPart);
534
+ } else {
535
+ currentReasoningPart.reasoning += value;
536
+ }
537
+ message.reasoning = (message.reasoning ?? "") + value;
538
+ execUpdate();
539
+ },
540
+ onReasoningSignaturePart(value) {
541
+ if (currentReasoningTextDetail != null) {
542
+ currentReasoningTextDetail.signature = value.signature;
543
+ }
544
+ },
545
+ onRedactedReasoningPart(value) {
546
+ if (currentReasoningPart == null) {
547
+ currentReasoningPart = {
548
+ type: "reasoning",
549
+ reasoning: "",
550
+ details: []
551
+ };
552
+ message.parts.push(currentReasoningPart);
553
+ }
554
+ currentReasoningPart.details.push({
555
+ type: "redacted",
556
+ data: value.data
557
+ });
558
+ currentReasoningTextDetail = void 0;
559
+ execUpdate();
560
+ },
561
+ onFilePart(value) {
562
+ message.parts.push({
563
+ type: "file",
564
+ mimeType: value.mimeType,
565
+ data: value.data
566
+ });
567
+ execUpdate();
568
+ },
569
+ onSourcePart(value) {
570
+ message.parts.push({
571
+ type: "source",
572
+ source: value
573
+ });
574
+ execUpdate();
575
+ },
576
+ onToolCallStreamingStartPart(value) {
577
+ if (message.toolInvocations == null) {
578
+ message.toolInvocations = [];
579
+ }
580
+ partialToolCalls[value.toolCallId] = {
581
+ text: "",
582
+ step,
583
+ toolName: value.toolName,
584
+ index: message.toolInvocations.length
585
+ };
586
+ const invocation = {
587
+ state: "partial-call",
588
+ step,
589
+ toolCallId: value.toolCallId,
590
+ toolName: value.toolName,
591
+ args: void 0
592
+ };
593
+ message.toolInvocations.push(invocation);
594
+ updateToolInvocationPart(value.toolCallId, invocation);
595
+ execUpdate();
596
+ },
597
+ onToolCallDeltaPart(value) {
598
+ const partialToolCall = partialToolCalls[value.toolCallId];
599
+ partialToolCall.text += value.argsTextDelta;
600
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
601
+ const invocation = {
602
+ state: "partial-call",
603
+ step: partialToolCall.step,
604
+ toolCallId: value.toolCallId,
605
+ toolName: partialToolCall.toolName,
606
+ args: partialArgs
607
+ };
608
+ message.toolInvocations[partialToolCall.index] = invocation;
609
+ updateToolInvocationPart(value.toolCallId, invocation);
610
+ execUpdate();
611
+ },
612
+ async onToolCallPart(value) {
613
+ const invocation = {
614
+ state: "call",
615
+ step,
616
+ ...value
617
+ };
618
+ if (partialToolCalls[value.toolCallId] != null) {
619
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
620
+ } else {
621
+ if (message.toolInvocations == null) {
622
+ message.toolInvocations = [];
623
+ }
624
+ message.toolInvocations.push(invocation);
625
+ }
626
+ updateToolInvocationPart(value.toolCallId, invocation);
627
+ execUpdate();
628
+ if (onToolCall) {
629
+ const result = await onToolCall({ toolCall: value });
630
+ if (result != null) {
631
+ const invocation2 = {
632
+ state: "result",
633
+ step,
634
+ ...value,
635
+ result
636
+ };
637
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
638
+ updateToolInvocationPart(value.toolCallId, invocation2);
639
+ execUpdate();
640
+ }
641
+ }
642
+ },
643
+ onToolResultPart(value) {
644
+ const toolInvocations = message.toolInvocations;
645
+ if (toolInvocations == null) {
646
+ throw new Error("tool_result must be preceded by a tool_call");
647
+ }
648
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
649
+ if (toolInvocationIndex === -1) {
650
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
651
+ }
652
+ const invocation = {
653
+ ...toolInvocations[toolInvocationIndex],
654
+ state: "result",
655
+ ...value
656
+ };
657
+ toolInvocations[toolInvocationIndex] = invocation;
658
+ updateToolInvocationPart(value.toolCallId, invocation);
659
+ execUpdate();
660
+ },
661
+ onDataPart(value) {
662
+ data.push(...value);
663
+ execUpdate();
664
+ },
665
+ onMessageAnnotationsPart(value) {
666
+ if (messageAnnotations == null) {
667
+ messageAnnotations = [...value];
668
+ } else {
669
+ messageAnnotations.push(...value);
670
+ }
671
+ execUpdate();
672
+ },
673
+ onFinishStepPart(value) {
674
+ step += 1;
675
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
676
+ currentReasoningPart = void 0;
677
+ currentReasoningTextDetail = void 0;
678
+ },
679
+ onStartStepPart(value) {
680
+ if (!replaceLastMessage) {
681
+ message.id = value.messageId;
682
+ }
683
+ message.parts.push({ type: "step-start" });
684
+ execUpdate();
685
+ },
686
+ onFinishMessagePart(value) {
687
+ finishReason = value.finishReason;
688
+ if (value.usage != null) {
689
+ usage = value.usage;
690
+ }
691
+ },
692
+ onErrorPart(error) {
693
+ throw new Error(error);
694
+ }
382
695
  });
696
+ onFinish?.({ message, finishReason, usage });
383
697
  }
384
698
  /**
385
699
  * Streams a response from the agent
@@ -394,6 +708,25 @@ var Agent = class extends BaseResource {
394
708
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
395
709
  clientTools: processClientTools(params.clientTools)
396
710
  };
711
+ const { readable, writable } = new TransformStream();
712
+ const response = await this.processStreamResponse(processedParams, writable);
713
+ const streamResponse = new Response(readable, {
714
+ status: response.status,
715
+ statusText: response.statusText,
716
+ headers: response.headers
717
+ });
718
+ streamResponse.processDataStream = async (options = {}) => {
719
+ await uiUtils.processDataStream({
720
+ stream: streamResponse.body,
721
+ ...options
722
+ });
723
+ };
724
+ return streamResponse;
725
+ }
726
+ /**
727
+ * Processes the stream response and handles tool calls
728
+ */
729
+ async processStreamResponse(processedParams, writable) {
397
730
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
398
731
  method: "POST",
399
732
  body: processedParams,
@@ -402,12 +735,104 @@ var Agent = class extends BaseResource {
402
735
  if (!response.body) {
403
736
  throw new Error("No response body");
404
737
  }
405
- response.processDataStream = async (options = {}) => {
406
- await uiUtils.processDataStream({
407
- stream: response.body,
408
- ...options
738
+ try {
739
+ let toolCalls = [];
740
+ let messages = [];
741
+ const [streamForWritable, streamForProcessing] = response.body.tee();
742
+ streamForWritable.pipeTo(writable, {
743
+ preventClose: true
744
+ }).catch((error) => {
745
+ console.error("Error piping to writable stream:", error);
409
746
  });
410
- };
747
+ this.processChatResponse({
748
+ stream: streamForProcessing,
749
+ update: ({ message }) => {
750
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
751
+ if (existingIndex !== -1) {
752
+ messages[existingIndex] = message;
753
+ } else {
754
+ messages.push(message);
755
+ }
756
+ },
757
+ onFinish: async ({ finishReason, message }) => {
758
+ if (finishReason === "tool-calls") {
759
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
760
+ if (toolCall) {
761
+ toolCalls.push(toolCall);
762
+ }
763
+ for (const toolCall2 of toolCalls) {
764
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
765
+ if (clientTool && clientTool.execute) {
766
+ const result = await clientTool.execute(
767
+ {
768
+ context: toolCall2?.args,
769
+ runId: processedParams.runId,
770
+ resourceId: processedParams.resourceId,
771
+ threadId: processedParams.threadId,
772
+ runtimeContext: processedParams.runtimeContext
773
+ },
774
+ {
775
+ messages: response.messages,
776
+ toolCallId: toolCall2?.toolCallId
777
+ }
778
+ );
779
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
780
+ const toolInvocationPart = lastMessage?.parts?.find(
781
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
782
+ );
783
+ if (toolInvocationPart) {
784
+ toolInvocationPart.toolInvocation = {
785
+ ...toolInvocationPart.toolInvocation,
786
+ state: "result",
787
+ result
788
+ };
789
+ }
790
+ const toolInvocation = lastMessage?.toolInvocations?.find(
791
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
792
+ );
793
+ if (toolInvocation) {
794
+ toolInvocation.state = "result";
795
+ toolInvocation.result = result;
796
+ }
797
+ const writer = writable.getWriter();
798
+ try {
799
+ await writer.write(
800
+ new TextEncoder().encode(
801
+ "a:" + JSON.stringify({
802
+ toolCallId: toolCall2.toolCallId,
803
+ result
804
+ }) + "\n"
805
+ )
806
+ );
807
+ } finally {
808
+ writer.releaseLock();
809
+ }
810
+ const originalMessages = processedParams.messages;
811
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
812
+ this.processStreamResponse(
813
+ {
814
+ ...processedParams,
815
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
816
+ },
817
+ writable
818
+ ).catch((error) => {
819
+ console.error("Error processing stream response:", error);
820
+ });
821
+ }
822
+ }
823
+ } else {
824
+ setTimeout(() => {
825
+ writable.close();
826
+ }, 0);
827
+ }
828
+ },
829
+ lastMessage: void 0
830
+ }).catch((error) => {
831
+ console.error("Error processing stream response:", error);
832
+ });
833
+ } catch (error) {
834
+ console.error("Error processing stream response:", error);
835
+ }
411
836
  return response;
412
837
  }
413
838
  /**
@@ -552,6 +977,36 @@ var MemoryThread = class extends BaseResource {
552
977
  });
553
978
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
554
979
  }
980
+ /**
981
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
982
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
983
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
984
+ */
985
+ getMessagesPaginated({
986
+ selectBy,
987
+ ...rest
988
+ }) {
989
+ const query = new URLSearchParams({
990
+ ...rest,
991
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
992
+ });
993
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
994
+ }
995
+ /**
996
+ * Deletes one or more messages from the thread
997
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
998
+ * message object with id property, or array of message objects
999
+ * @returns Promise containing deletion result
1000
+ */
1001
+ deleteMessages(messageIds) {
1002
+ const query = new URLSearchParams({
1003
+ agentId: this.agentId
1004
+ });
1005
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1006
+ method: "POST",
1007
+ body: { messageIds }
1008
+ });
1009
+ }
555
1010
  };
556
1011
 
557
1012
  // src/resources/vector.ts
@@ -802,7 +1257,7 @@ var LegacyWorkflow = class extends BaseResource {
802
1257
  };
803
1258
 
804
1259
  // src/resources/tool.ts
805
- var Tool = class extends BaseResource {
1260
+ var Tool2 = class extends BaseResource {
806
1261
  constructor(options, toolId) {
807
1262
  super(options);
808
1263
  this.toolId = toolId;
@@ -907,10 +1362,10 @@ var Workflow = class extends BaseResource {
907
1362
  if (params?.toDate) {
908
1363
  searchParams.set("toDate", params.toDate.toISOString());
909
1364
  }
910
- if (params?.limit) {
1365
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
911
1366
  searchParams.set("limit", String(params.limit));
912
1367
  }
913
- if (params?.offset) {
1368
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
914
1369
  searchParams.set("offset", String(params.offset));
915
1370
  }
916
1371
  if (params?.resourceId) {
@@ -938,6 +1393,27 @@ var Workflow = class extends BaseResource {
938
1393
  runExecutionResult(runId) {
939
1394
  return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
940
1395
  }
1396
+ /**
1397
+ * Cancels a specific workflow run by its ID
1398
+ * @param runId - The ID of the workflow run to cancel
1399
+ * @returns Promise containing a success message
1400
+ */
1401
+ cancelRun(runId) {
1402
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1403
+ method: "POST"
1404
+ });
1405
+ }
1406
+ /**
1407
+ * Sends an event to a specific workflow run by its ID
1408
+ * @param params - Object containing the runId, event and data
1409
+ * @returns Promise containing a success message
1410
+ */
1411
+ sendRunEvent(params) {
1412
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1413
+ method: "POST",
1414
+ body: { event: params.event, data: params.data }
1415
+ });
1416
+ }
941
1417
  /**
942
1418
  * Creates a new workflow run
943
1419
  * @param params - Optional object containing the optional runId
@@ -952,6 +1428,14 @@ var Workflow = class extends BaseResource {
952
1428
  method: "POST"
953
1429
  });
954
1430
  }
1431
+ /**
1432
+ * Creates a new workflow run (alias for createRun)
1433
+ * @param params - Optional object containing the optional runId
1434
+ * @returns Promise containing the runId of the created run
1435
+ */
1436
+ createRunAsync(params) {
1437
+ return this.createRun(params);
1438
+ }
955
1439
  /**
956
1440
  * Starts a workflow run synchronously without waiting for the workflow to complete
957
1441
  * @param params - Object containing the runId, inputData and runtimeContext
@@ -1003,9 +1487,9 @@ var Workflow = class extends BaseResource {
1003
1487
  });
1004
1488
  }
1005
1489
  /**
1006
- * Starts a vNext workflow run and returns a stream
1490
+ * Starts a workflow run and returns a stream
1007
1491
  * @param params - Object containing the optional runId, inputData and runtimeContext
1008
- * @returns Promise containing the vNext workflow execution results
1492
+ * @returns Promise containing the workflow execution results
1009
1493
  */
1010
1494
  async stream(params) {
1011
1495
  const searchParams = new URLSearchParams();
@@ -1027,6 +1511,7 @@ var Workflow = class extends BaseResource {
1027
1511
  if (!response.body) {
1028
1512
  throw new Error("Response body is null");
1029
1513
  }
1514
+ let failedChunk = void 0;
1030
1515
  const transformStream = new TransformStream({
1031
1516
  start() {
1032
1517
  },
@@ -1036,10 +1521,13 @@ var Workflow = class extends BaseResource {
1036
1521
  const chunks = decoded.split(RECORD_SEPARATOR2);
1037
1522
  for (const chunk2 of chunks) {
1038
1523
  if (chunk2) {
1524
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1039
1525
  try {
1040
- const parsedChunk = JSON.parse(chunk2);
1526
+ const parsedChunk = JSON.parse(newChunk);
1041
1527
  controller.enqueue(parsedChunk);
1042
- } catch {
1528
+ failedChunk = void 0;
1529
+ } catch (error) {
1530
+ failedChunk = newChunk;
1043
1531
  }
1044
1532
  }
1045
1533
  }
@@ -1221,6 +1709,207 @@ var MCPTool = class extends BaseResource {
1221
1709
  }
1222
1710
  };
1223
1711
 
1712
+ // src/resources/network-memory-thread.ts
1713
+ var NetworkMemoryThread = class extends BaseResource {
1714
+ constructor(options, threadId, networkId) {
1715
+ super(options);
1716
+ this.threadId = threadId;
1717
+ this.networkId = networkId;
1718
+ }
1719
+ /**
1720
+ * Retrieves the memory thread details
1721
+ * @returns Promise containing thread details including title and metadata
1722
+ */
1723
+ get() {
1724
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1725
+ }
1726
+ /**
1727
+ * Updates the memory thread properties
1728
+ * @param params - Update parameters including title and metadata
1729
+ * @returns Promise containing updated thread details
1730
+ */
1731
+ update(params) {
1732
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1733
+ method: "PATCH",
1734
+ body: params
1735
+ });
1736
+ }
1737
+ /**
1738
+ * Deletes the memory thread
1739
+ * @returns Promise containing deletion result
1740
+ */
1741
+ delete() {
1742
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1743
+ method: "DELETE"
1744
+ });
1745
+ }
1746
+ /**
1747
+ * Retrieves messages associated with the thread
1748
+ * @param params - Optional parameters including limit for number of messages to retrieve
1749
+ * @returns Promise containing thread messages and UI messages
1750
+ */
1751
+ getMessages(params) {
1752
+ const query = new URLSearchParams({
1753
+ networkId: this.networkId,
1754
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1755
+ });
1756
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1757
+ }
1758
+ /**
1759
+ * Deletes one or more messages from the thread
1760
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1761
+ * message object with id property, or array of message objects
1762
+ * @returns Promise containing deletion result
1763
+ */
1764
+ deleteMessages(messageIds) {
1765
+ const query = new URLSearchParams({
1766
+ networkId: this.networkId
1767
+ });
1768
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
1769
+ method: "POST",
1770
+ body: { messageIds }
1771
+ });
1772
+ }
1773
+ };
1774
+
1775
+ // src/resources/vNextNetwork.ts
1776
+ var RECORD_SEPARATOR3 = "";
1777
+ var VNextNetwork = class extends BaseResource {
1778
+ constructor(options, networkId) {
1779
+ super(options);
1780
+ this.networkId = networkId;
1781
+ }
1782
+ /**
1783
+ * Retrieves details about the network
1784
+ * @returns Promise containing vNext network details
1785
+ */
1786
+ details() {
1787
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1788
+ }
1789
+ /**
1790
+ * Generates a response from the v-next network
1791
+ * @param params - Generation parameters including message
1792
+ * @returns Promise containing the generated response
1793
+ */
1794
+ generate(params) {
1795
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1796
+ method: "POST",
1797
+ body: {
1798
+ ...params,
1799
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1800
+ }
1801
+ });
1802
+ }
1803
+ /**
1804
+ * Generates a response from the v-next network using multiple primitives
1805
+ * @param params - Generation parameters including message
1806
+ * @returns Promise containing the generated response
1807
+ */
1808
+ loop(params) {
1809
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1810
+ method: "POST",
1811
+ body: {
1812
+ ...params,
1813
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1814
+ }
1815
+ });
1816
+ }
1817
+ async *streamProcessor(stream) {
1818
+ const reader = stream.getReader();
1819
+ let doneReading = false;
1820
+ let buffer = "";
1821
+ try {
1822
+ while (!doneReading) {
1823
+ const { done, value } = await reader.read();
1824
+ doneReading = done;
1825
+ if (done && !value) continue;
1826
+ try {
1827
+ const decoded = value ? new TextDecoder().decode(value) : "";
1828
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1829
+ buffer = chunks.pop() || "";
1830
+ for (const chunk of chunks) {
1831
+ if (chunk) {
1832
+ if (typeof chunk === "string") {
1833
+ try {
1834
+ const parsedChunk = JSON.parse(chunk);
1835
+ yield parsedChunk;
1836
+ } catch {
1837
+ }
1838
+ }
1839
+ }
1840
+ }
1841
+ } catch {
1842
+ }
1843
+ }
1844
+ if (buffer) {
1845
+ try {
1846
+ yield JSON.parse(buffer);
1847
+ } catch {
1848
+ }
1849
+ }
1850
+ } finally {
1851
+ reader.cancel().catch(() => {
1852
+ });
1853
+ }
1854
+ }
1855
+ /**
1856
+ * Streams a response from the v-next network
1857
+ * @param params - Stream parameters including message
1858
+ * @returns Promise containing the results
1859
+ */
1860
+ async stream(params, onRecord) {
1861
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1862
+ method: "POST",
1863
+ body: {
1864
+ ...params,
1865
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1866
+ },
1867
+ stream: true
1868
+ });
1869
+ if (!response.ok) {
1870
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1871
+ }
1872
+ if (!response.body) {
1873
+ throw new Error("Response body is null");
1874
+ }
1875
+ for await (const record of this.streamProcessor(response.body)) {
1876
+ if (typeof record === "string") {
1877
+ onRecord(JSON.parse(record));
1878
+ } else {
1879
+ onRecord(record);
1880
+ }
1881
+ }
1882
+ }
1883
+ /**
1884
+ * Streams a response from the v-next network loop
1885
+ * @param params - Stream parameters including message
1886
+ * @returns Promise containing the results
1887
+ */
1888
+ async loopStream(params, onRecord) {
1889
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1890
+ method: "POST",
1891
+ body: {
1892
+ ...params,
1893
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1894
+ },
1895
+ stream: true
1896
+ });
1897
+ if (!response.ok) {
1898
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1899
+ }
1900
+ if (!response.body) {
1901
+ throw new Error("Response body is null");
1902
+ }
1903
+ for await (const record of this.streamProcessor(response.body)) {
1904
+ if (typeof record === "string") {
1905
+ onRecord(JSON.parse(record));
1906
+ } else {
1907
+ onRecord(record);
1908
+ }
1909
+ }
1910
+ }
1911
+ };
1912
+
1224
1913
  // src/client.ts
1225
1914
  var MastraClient = class extends BaseResource {
1226
1915
  constructor(options) {
@@ -1298,6 +1987,48 @@ var MastraClient = class extends BaseResource {
1298
1987
  getMemoryStatus(agentId) {
1299
1988
  return this.request(`/api/memory/status?agentId=${agentId}`);
1300
1989
  }
1990
+ /**
1991
+ * Retrieves memory threads for a resource
1992
+ * @param params - Parameters containing the resource ID
1993
+ * @returns Promise containing array of memory threads
1994
+ */
1995
+ getNetworkMemoryThreads(params) {
1996
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1997
+ }
1998
+ /**
1999
+ * Creates a new memory thread
2000
+ * @param params - Parameters for creating the memory thread
2001
+ * @returns Promise containing the created memory thread
2002
+ */
2003
+ createNetworkMemoryThread(params) {
2004
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
2005
+ }
2006
+ /**
2007
+ * Gets a memory thread instance by ID
2008
+ * @param threadId - ID of the memory thread to retrieve
2009
+ * @returns MemoryThread instance
2010
+ */
2011
+ getNetworkMemoryThread(threadId, networkId) {
2012
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2013
+ }
2014
+ /**
2015
+ * Saves messages to memory
2016
+ * @param params - Parameters containing messages to save
2017
+ * @returns Promise containing the saved messages
2018
+ */
2019
+ saveNetworkMessageToMemory(params) {
2020
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2021
+ method: "POST",
2022
+ body: params
2023
+ });
2024
+ }
2025
+ /**
2026
+ * Gets the status of the memory system
2027
+ * @returns Promise containing memory system status
2028
+ */
2029
+ getNetworkMemoryStatus(networkId) {
2030
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2031
+ }
1301
2032
  /**
1302
2033
  * Retrieves all available tools
1303
2034
  * @returns Promise containing map of tool IDs to tool details
@@ -1311,7 +2042,7 @@ var MastraClient = class extends BaseResource {
1311
2042
  * @returns Tool instance
1312
2043
  */
1313
2044
  getTool(toolId) {
1314
- return new Tool(this.options, toolId);
2045
+ return new Tool2(this.options, toolId);
1315
2046
  }
1316
2047
  /**
1317
2048
  * Retrieves all available legacy workflows
@@ -1494,6 +2225,13 @@ var MastraClient = class extends BaseResource {
1494
2225
  getNetworks() {
1495
2226
  return this.request("/api/networks");
1496
2227
  }
2228
+ /**
2229
+ * Retrieves all available vNext networks
2230
+ * @returns Promise containing map of vNext network IDs to vNext network details
2231
+ */
2232
+ getVNextNetworks() {
2233
+ return this.request("/api/networks/v-next");
2234
+ }
1497
2235
  /**
1498
2236
  * Gets a network instance by ID
1499
2237
  * @param networkId - ID of the network to retrieve
@@ -1502,6 +2240,14 @@ var MastraClient = class extends BaseResource {
1502
2240
  getNetwork(networkId) {
1503
2241
  return new Network(this.options, networkId);
1504
2242
  }
2243
+ /**
2244
+ * Gets a vNext network instance by ID
2245
+ * @param networkId - ID of the vNext network to retrieve
2246
+ * @returns vNext Network instance
2247
+ */
2248
+ getVNextNetwork(networkId) {
2249
+ return new VNextNetwork(this.options, networkId);
2250
+ }
1505
2251
  /**
1506
2252
  * Retrieves a list of available MCP servers.
1507
2253
  * @param params - Optional parameters for pagination (limit, offset).
@@ -1558,6 +2304,121 @@ var MastraClient = class extends BaseResource {
1558
2304
  getA2A(agentId) {
1559
2305
  return new A2A(this.options, agentId);
1560
2306
  }
2307
+ /**
2308
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2309
+ * @param agentId - ID of the agent.
2310
+ * @param threadId - ID of the thread.
2311
+ * @param resourceId - Optional ID of the resource.
2312
+ * @returns Working memory for the specified thread or resource.
2313
+ */
2314
+ getWorkingMemory({
2315
+ agentId,
2316
+ threadId,
2317
+ resourceId
2318
+ }) {
2319
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2320
+ }
2321
+ /**
2322
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2323
+ * @param agentId - ID of the agent.
2324
+ * @param threadId - ID of the thread.
2325
+ * @param workingMemory - The new working memory content.
2326
+ * @param resourceId - Optional ID of the resource.
2327
+ */
2328
+ updateWorkingMemory({
2329
+ agentId,
2330
+ threadId,
2331
+ workingMemory,
2332
+ resourceId
2333
+ }) {
2334
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2335
+ method: "POST",
2336
+ body: {
2337
+ workingMemory,
2338
+ resourceId
2339
+ }
2340
+ });
2341
+ }
2342
+ /**
2343
+ * Retrieves all available scorers
2344
+ * @returns Promise containing list of available scorers
2345
+ */
2346
+ getScorers() {
2347
+ return this.request("/api/scores/scorers");
2348
+ }
2349
+ /**
2350
+ * Retrieves a scorer by ID
2351
+ * @param scorerId - ID of the scorer to retrieve
2352
+ * @returns Promise containing the scorer
2353
+ */
2354
+ getScorer(scorerId) {
2355
+ return this.request(`/api/scores/scorers/${scorerId}`);
2356
+ }
2357
+ getScoresByScorerId(params) {
2358
+ const { page, perPage, scorerId, entityId, entityType } = params;
2359
+ const searchParams = new URLSearchParams();
2360
+ if (entityId) {
2361
+ searchParams.set("entityId", entityId);
2362
+ }
2363
+ if (entityType) {
2364
+ searchParams.set("entityType", entityType);
2365
+ }
2366
+ if (page !== void 0) {
2367
+ searchParams.set("page", String(page));
2368
+ }
2369
+ if (perPage !== void 0) {
2370
+ searchParams.set("perPage", String(perPage));
2371
+ }
2372
+ const queryString = searchParams.toString();
2373
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
2374
+ }
2375
+ /**
2376
+ * Retrieves scores by run ID
2377
+ * @param params - Parameters containing run ID and pagination options
2378
+ * @returns Promise containing scores and pagination info
2379
+ */
2380
+ getScoresByRunId(params) {
2381
+ const { runId, page, perPage } = params;
2382
+ const searchParams = new URLSearchParams();
2383
+ if (page !== void 0) {
2384
+ searchParams.set("page", String(page));
2385
+ }
2386
+ if (perPage !== void 0) {
2387
+ searchParams.set("perPage", String(perPage));
2388
+ }
2389
+ const queryString = searchParams.toString();
2390
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
2391
+ }
2392
+ /**
2393
+ * Retrieves scores by entity ID and type
2394
+ * @param params - Parameters containing entity ID, type, and pagination options
2395
+ * @returns Promise containing scores and pagination info
2396
+ */
2397
+ getScoresByEntityId(params) {
2398
+ const { entityId, entityType, page, perPage } = params;
2399
+ const searchParams = new URLSearchParams();
2400
+ if (page !== void 0) {
2401
+ searchParams.set("page", String(page));
2402
+ }
2403
+ if (perPage !== void 0) {
2404
+ searchParams.set("perPage", String(perPage));
2405
+ }
2406
+ const queryString = searchParams.toString();
2407
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
2408
+ }
2409
+ /**
2410
+ * Saves a score
2411
+ * @param params - Parameters containing the score data to save
2412
+ * @returns Promise containing the saved score
2413
+ */
2414
+ saveScore(params) {
2415
+ return this.request("/api/scores", {
2416
+ method: "POST",
2417
+ body: params
2418
+ });
2419
+ }
1561
2420
  };
1562
2421
 
1563
2422
  exports.MastraClient = MastraClient;
2423
+ //# sourceMappingURL=index.cjs.map
2424
+ //# sourceMappingURL=index.cjs.map