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

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.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { AbstractAgent, EventType } from '@ag-ui/client';
2
2
  import { Observable } from 'rxjs';
3
- import { processDataStream } from '@ai-sdk/ui-utils';
4
- import { ZodSchema } from 'zod';
3
+ import { processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
4
+ import { z } from 'zod';
5
5
  import originalZodToJsonSchema from 'zod-to-json-schema';
6
- import { isVercelTool } from '@mastra/core/tools';
6
+ import { isVercelTool } from '@mastra/core/tools/is-vercel-tool';
7
+ import { v4 } from '@lukeed/uuid';
7
8
  import { RuntimeContext } from '@mastra/core/runtime-context';
8
9
 
9
10
  // src/adapters/agui.ts
@@ -191,10 +192,16 @@ function convertMessagesToMastraMessages(messages) {
191
192
  }
192
193
  return result;
193
194
  }
195
+ function isZodType(value) {
196
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
197
+ }
194
198
  function zodToJsonSchema(zodSchema) {
195
- if (!(zodSchema instanceof ZodSchema)) {
199
+ if (!isZodType(zodSchema)) {
196
200
  return zodSchema;
197
201
  }
202
+ if ("toJSONSchema" in z) {
203
+ return z.toJSONSchema(zodSchema);
204
+ }
198
205
  return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
199
206
  }
200
207
  function processClientTools(clientTools) {
@@ -246,11 +253,13 @@ var BaseResource = class {
246
253
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
247
254
  ...options,
248
255
  headers: {
256
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
249
257
  ...headers,
250
258
  ...options.headers
251
259
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
252
260
  // 'x-mastra-client-type': 'js',
253
261
  },
262
+ signal: this.options.abortSignal,
254
263
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
255
264
  });
256
265
  if (!response.ok) {
@@ -292,8 +301,6 @@ function parseClientRuntimeContext(runtimeContext) {
292
301
  }
293
302
  return void 0;
294
303
  }
295
-
296
- // src/resources/agent.ts
297
304
  var AgentVoice = class extends BaseResource {
298
305
  constructor(options, agentId) {
299
306
  super(options);
@@ -362,7 +369,7 @@ var Agent = class extends BaseResource {
362
369
  details() {
363
370
  return this.request(`/api/agents/${this.agentId}`);
364
371
  }
365
- generate(params) {
372
+ async generate(params) {
366
373
  const processedParams = {
367
374
  ...params,
368
375
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -370,10 +377,317 @@ var Agent = class extends BaseResource {
370
377
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
371
378
  clientTools: processClientTools(params.clientTools)
372
379
  };
373
- return this.request(`/api/agents/${this.agentId}/generate`, {
374
- method: "POST",
375
- body: processedParams
380
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
381
+ const response = await this.request(
382
+ `/api/agents/${this.agentId}/generate`,
383
+ {
384
+ method: "POST",
385
+ body: processedParams
386
+ }
387
+ );
388
+ if (response.finishReason === "tool-calls") {
389
+ const toolCalls = response.toolCalls;
390
+ if (!toolCalls || !Array.isArray(toolCalls)) {
391
+ return response;
392
+ }
393
+ for (const toolCall of toolCalls) {
394
+ const clientTool = params.clientTools?.[toolCall.toolName];
395
+ if (clientTool && clientTool.execute) {
396
+ const result = await clientTool.execute(
397
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
398
+ {
399
+ messages: response.messages,
400
+ toolCallId: toolCall?.toolCallId
401
+ }
402
+ );
403
+ const updatedMessages = [
404
+ {
405
+ role: "user",
406
+ content: params.messages
407
+ },
408
+ ...response.response.messages,
409
+ {
410
+ role: "tool",
411
+ content: [
412
+ {
413
+ type: "tool-result",
414
+ toolCallId: toolCall.toolCallId,
415
+ toolName: toolCall.toolName,
416
+ result
417
+ }
418
+ ]
419
+ }
420
+ ];
421
+ return this.generate({
422
+ ...params,
423
+ messages: updatedMessages
424
+ });
425
+ }
426
+ }
427
+ }
428
+ return response;
429
+ }
430
+ async processChatResponse({
431
+ stream,
432
+ update,
433
+ onToolCall,
434
+ onFinish,
435
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
436
+ lastMessage
437
+ }) {
438
+ const replaceLastMessage = lastMessage?.role === "assistant";
439
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
440
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
441
+ return Math.max(max, toolInvocation.step ?? 0);
442
+ }, 0) ?? 0) : 0;
443
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
444
+ id: v4(),
445
+ createdAt: getCurrentDate(),
446
+ role: "assistant",
447
+ content: "",
448
+ parts: []
449
+ };
450
+ let currentTextPart = void 0;
451
+ let currentReasoningPart = void 0;
452
+ let currentReasoningTextDetail = void 0;
453
+ function updateToolInvocationPart(toolCallId, invocation) {
454
+ const part = message.parts.find(
455
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
456
+ );
457
+ if (part != null) {
458
+ part.toolInvocation = invocation;
459
+ } else {
460
+ message.parts.push({
461
+ type: "tool-invocation",
462
+ toolInvocation: invocation
463
+ });
464
+ }
465
+ }
466
+ const data = [];
467
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
468
+ const partialToolCalls = {};
469
+ let usage = {
470
+ completionTokens: NaN,
471
+ promptTokens: NaN,
472
+ totalTokens: NaN
473
+ };
474
+ let finishReason = "unknown";
475
+ function execUpdate() {
476
+ const copiedData = [...data];
477
+ if (messageAnnotations?.length) {
478
+ message.annotations = messageAnnotations;
479
+ }
480
+ const copiedMessage = {
481
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
482
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
483
+ ...structuredClone(message),
484
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
485
+ // hashing approach by default to detect changes, but it only works for shallow
486
+ // changes. This is why we need to add a revision id to ensure that the message
487
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
488
+ // forwarded to rendering):
489
+ revisionId: v4()
490
+ };
491
+ update({
492
+ message: copiedMessage,
493
+ data: copiedData,
494
+ replaceLastMessage
495
+ });
496
+ }
497
+ await processDataStream({
498
+ stream,
499
+ onTextPart(value) {
500
+ if (currentTextPart == null) {
501
+ currentTextPart = {
502
+ type: "text",
503
+ text: value
504
+ };
505
+ message.parts.push(currentTextPart);
506
+ } else {
507
+ currentTextPart.text += value;
508
+ }
509
+ message.content += value;
510
+ execUpdate();
511
+ },
512
+ onReasoningPart(value) {
513
+ if (currentReasoningTextDetail == null) {
514
+ currentReasoningTextDetail = { type: "text", text: value };
515
+ if (currentReasoningPart != null) {
516
+ currentReasoningPart.details.push(currentReasoningTextDetail);
517
+ }
518
+ } else {
519
+ currentReasoningTextDetail.text += value;
520
+ }
521
+ if (currentReasoningPart == null) {
522
+ currentReasoningPart = {
523
+ type: "reasoning",
524
+ reasoning: value,
525
+ details: [currentReasoningTextDetail]
526
+ };
527
+ message.parts.push(currentReasoningPart);
528
+ } else {
529
+ currentReasoningPart.reasoning += value;
530
+ }
531
+ message.reasoning = (message.reasoning ?? "") + value;
532
+ execUpdate();
533
+ },
534
+ onReasoningSignaturePart(value) {
535
+ if (currentReasoningTextDetail != null) {
536
+ currentReasoningTextDetail.signature = value.signature;
537
+ }
538
+ },
539
+ onRedactedReasoningPart(value) {
540
+ if (currentReasoningPart == null) {
541
+ currentReasoningPart = {
542
+ type: "reasoning",
543
+ reasoning: "",
544
+ details: []
545
+ };
546
+ message.parts.push(currentReasoningPart);
547
+ }
548
+ currentReasoningPart.details.push({
549
+ type: "redacted",
550
+ data: value.data
551
+ });
552
+ currentReasoningTextDetail = void 0;
553
+ execUpdate();
554
+ },
555
+ onFilePart(value) {
556
+ message.parts.push({
557
+ type: "file",
558
+ mimeType: value.mimeType,
559
+ data: value.data
560
+ });
561
+ execUpdate();
562
+ },
563
+ onSourcePart(value) {
564
+ message.parts.push({
565
+ type: "source",
566
+ source: value
567
+ });
568
+ execUpdate();
569
+ },
570
+ onToolCallStreamingStartPart(value) {
571
+ if (message.toolInvocations == null) {
572
+ message.toolInvocations = [];
573
+ }
574
+ partialToolCalls[value.toolCallId] = {
575
+ text: "",
576
+ step,
577
+ toolName: value.toolName,
578
+ index: message.toolInvocations.length
579
+ };
580
+ const invocation = {
581
+ state: "partial-call",
582
+ step,
583
+ toolCallId: value.toolCallId,
584
+ toolName: value.toolName,
585
+ args: void 0
586
+ };
587
+ message.toolInvocations.push(invocation);
588
+ updateToolInvocationPart(value.toolCallId, invocation);
589
+ execUpdate();
590
+ },
591
+ onToolCallDeltaPart(value) {
592
+ const partialToolCall = partialToolCalls[value.toolCallId];
593
+ partialToolCall.text += value.argsTextDelta;
594
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
595
+ const invocation = {
596
+ state: "partial-call",
597
+ step: partialToolCall.step,
598
+ toolCallId: value.toolCallId,
599
+ toolName: partialToolCall.toolName,
600
+ args: partialArgs
601
+ };
602
+ message.toolInvocations[partialToolCall.index] = invocation;
603
+ updateToolInvocationPart(value.toolCallId, invocation);
604
+ execUpdate();
605
+ },
606
+ async onToolCallPart(value) {
607
+ const invocation = {
608
+ state: "call",
609
+ step,
610
+ ...value
611
+ };
612
+ if (partialToolCalls[value.toolCallId] != null) {
613
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
614
+ } else {
615
+ if (message.toolInvocations == null) {
616
+ message.toolInvocations = [];
617
+ }
618
+ message.toolInvocations.push(invocation);
619
+ }
620
+ updateToolInvocationPart(value.toolCallId, invocation);
621
+ execUpdate();
622
+ if (onToolCall) {
623
+ const result = await onToolCall({ toolCall: value });
624
+ if (result != null) {
625
+ const invocation2 = {
626
+ state: "result",
627
+ step,
628
+ ...value,
629
+ result
630
+ };
631
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
632
+ updateToolInvocationPart(value.toolCallId, invocation2);
633
+ execUpdate();
634
+ }
635
+ }
636
+ },
637
+ onToolResultPart(value) {
638
+ const toolInvocations = message.toolInvocations;
639
+ if (toolInvocations == null) {
640
+ throw new Error("tool_result must be preceded by a tool_call");
641
+ }
642
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
643
+ if (toolInvocationIndex === -1) {
644
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
645
+ }
646
+ const invocation = {
647
+ ...toolInvocations[toolInvocationIndex],
648
+ state: "result",
649
+ ...value
650
+ };
651
+ toolInvocations[toolInvocationIndex] = invocation;
652
+ updateToolInvocationPart(value.toolCallId, invocation);
653
+ execUpdate();
654
+ },
655
+ onDataPart(value) {
656
+ data.push(...value);
657
+ execUpdate();
658
+ },
659
+ onMessageAnnotationsPart(value) {
660
+ if (messageAnnotations == null) {
661
+ messageAnnotations = [...value];
662
+ } else {
663
+ messageAnnotations.push(...value);
664
+ }
665
+ execUpdate();
666
+ },
667
+ onFinishStepPart(value) {
668
+ step += 1;
669
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
670
+ currentReasoningPart = void 0;
671
+ currentReasoningTextDetail = void 0;
672
+ },
673
+ onStartStepPart(value) {
674
+ if (!replaceLastMessage) {
675
+ message.id = value.messageId;
676
+ }
677
+ message.parts.push({ type: "step-start" });
678
+ execUpdate();
679
+ },
680
+ onFinishMessagePart(value) {
681
+ finishReason = value.finishReason;
682
+ if (value.usage != null) {
683
+ usage = value.usage;
684
+ }
685
+ },
686
+ onErrorPart(error) {
687
+ throw new Error(error);
688
+ }
376
689
  });
690
+ onFinish?.({ message, finishReason, usage });
377
691
  }
378
692
  /**
379
693
  * Streams a response from the agent
@@ -388,6 +702,25 @@ var Agent = class extends BaseResource {
388
702
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
389
703
  clientTools: processClientTools(params.clientTools)
390
704
  };
705
+ const { readable, writable } = new TransformStream();
706
+ const response = await this.processStreamResponse(processedParams, writable);
707
+ const streamResponse = new Response(readable, {
708
+ status: response.status,
709
+ statusText: response.statusText,
710
+ headers: response.headers
711
+ });
712
+ streamResponse.processDataStream = async (options = {}) => {
713
+ await processDataStream({
714
+ stream: streamResponse.body,
715
+ ...options
716
+ });
717
+ };
718
+ return streamResponse;
719
+ }
720
+ /**
721
+ * Processes the stream response and handles tool calls
722
+ */
723
+ async processStreamResponse(processedParams, writable) {
391
724
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
392
725
  method: "POST",
393
726
  body: processedParams,
@@ -396,12 +729,104 @@ var Agent = class extends BaseResource {
396
729
  if (!response.body) {
397
730
  throw new Error("No response body");
398
731
  }
399
- response.processDataStream = async (options = {}) => {
400
- await processDataStream({
401
- stream: response.body,
402
- ...options
732
+ try {
733
+ let toolCalls = [];
734
+ let messages = [];
735
+ const [streamForWritable, streamForProcessing] = response.body.tee();
736
+ streamForWritable.pipeTo(writable, {
737
+ preventClose: true
738
+ }).catch((error) => {
739
+ console.error("Error piping to writable stream:", error);
403
740
  });
404
- };
741
+ this.processChatResponse({
742
+ stream: streamForProcessing,
743
+ update: ({ message }) => {
744
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
745
+ if (existingIndex !== -1) {
746
+ messages[existingIndex] = message;
747
+ } else {
748
+ messages.push(message);
749
+ }
750
+ },
751
+ onFinish: async ({ finishReason, message }) => {
752
+ if (finishReason === "tool-calls") {
753
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
754
+ if (toolCall) {
755
+ toolCalls.push(toolCall);
756
+ }
757
+ for (const toolCall2 of toolCalls) {
758
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
759
+ if (clientTool && clientTool.execute) {
760
+ const result = await clientTool.execute(
761
+ {
762
+ context: toolCall2?.args,
763
+ runId: processedParams.runId,
764
+ resourceId: processedParams.resourceId,
765
+ threadId: processedParams.threadId,
766
+ runtimeContext: processedParams.runtimeContext
767
+ },
768
+ {
769
+ messages: response.messages,
770
+ toolCallId: toolCall2?.toolCallId
771
+ }
772
+ );
773
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
774
+ const toolInvocationPart = lastMessage?.parts?.find(
775
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
776
+ );
777
+ if (toolInvocationPart) {
778
+ toolInvocationPart.toolInvocation = {
779
+ ...toolInvocationPart.toolInvocation,
780
+ state: "result",
781
+ result
782
+ };
783
+ }
784
+ const toolInvocation = lastMessage?.toolInvocations?.find(
785
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
786
+ );
787
+ if (toolInvocation) {
788
+ toolInvocation.state = "result";
789
+ toolInvocation.result = result;
790
+ }
791
+ const writer = writable.getWriter();
792
+ try {
793
+ await writer.write(
794
+ new TextEncoder().encode(
795
+ "a:" + JSON.stringify({
796
+ toolCallId: toolCall2.toolCallId,
797
+ result
798
+ }) + "\n"
799
+ )
800
+ );
801
+ } finally {
802
+ writer.releaseLock();
803
+ }
804
+ const originalMessages = processedParams.messages;
805
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
806
+ this.processStreamResponse(
807
+ {
808
+ ...processedParams,
809
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
810
+ },
811
+ writable
812
+ ).catch((error) => {
813
+ console.error("Error processing stream response:", error);
814
+ });
815
+ }
816
+ }
817
+ } else {
818
+ setTimeout(() => {
819
+ writable.close();
820
+ }, 0);
821
+ }
822
+ },
823
+ lastMessage: void 0
824
+ }).catch((error) => {
825
+ console.error("Error processing stream response:", error);
826
+ });
827
+ } catch (error) {
828
+ console.error("Error processing stream response:", error);
829
+ }
405
830
  return response;
406
831
  }
407
832
  /**
@@ -546,6 +971,36 @@ var MemoryThread = class extends BaseResource {
546
971
  });
547
972
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
548
973
  }
974
+ /**
975
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
976
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
977
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
978
+ */
979
+ getMessagesPaginated({
980
+ selectBy,
981
+ ...rest
982
+ }) {
983
+ const query = new URLSearchParams({
984
+ ...rest,
985
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
986
+ });
987
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
988
+ }
989
+ /**
990
+ * Deletes one or more messages from the thread
991
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
992
+ * message object with id property, or array of message objects
993
+ * @returns Promise containing deletion result
994
+ */
995
+ deleteMessages(messageIds) {
996
+ const query = new URLSearchParams({
997
+ agentId: this.agentId
998
+ });
999
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1000
+ method: "POST",
1001
+ body: { messageIds }
1002
+ });
1003
+ }
549
1004
  };
550
1005
 
551
1006
  // src/resources/vector.ts
@@ -796,7 +1251,7 @@ var LegacyWorkflow = class extends BaseResource {
796
1251
  };
797
1252
 
798
1253
  // src/resources/tool.ts
799
- var Tool = class extends BaseResource {
1254
+ var Tool2 = class extends BaseResource {
800
1255
  constructor(options, toolId) {
801
1256
  super(options);
802
1257
  this.toolId = toolId;
@@ -901,10 +1356,10 @@ var Workflow = class extends BaseResource {
901
1356
  if (params?.toDate) {
902
1357
  searchParams.set("toDate", params.toDate.toISOString());
903
1358
  }
904
- if (params?.limit) {
1359
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
905
1360
  searchParams.set("limit", String(params.limit));
906
1361
  }
907
- if (params?.offset) {
1362
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
908
1363
  searchParams.set("offset", String(params.offset));
909
1364
  }
910
1365
  if (params?.resourceId) {
@@ -932,6 +1387,27 @@ var Workflow = class extends BaseResource {
932
1387
  runExecutionResult(runId) {
933
1388
  return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
934
1389
  }
1390
+ /**
1391
+ * Cancels a specific workflow run by its ID
1392
+ * @param runId - The ID of the workflow run to cancel
1393
+ * @returns Promise containing a success message
1394
+ */
1395
+ cancelRun(runId) {
1396
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1397
+ method: "POST"
1398
+ });
1399
+ }
1400
+ /**
1401
+ * Sends an event to a specific workflow run by its ID
1402
+ * @param params - Object containing the runId, event and data
1403
+ * @returns Promise containing a success message
1404
+ */
1405
+ sendRunEvent(params) {
1406
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1407
+ method: "POST",
1408
+ body: { event: params.event, data: params.data }
1409
+ });
1410
+ }
935
1411
  /**
936
1412
  * Creates a new workflow run
937
1413
  * @param params - Optional object containing the optional runId
@@ -946,6 +1422,14 @@ var Workflow = class extends BaseResource {
946
1422
  method: "POST"
947
1423
  });
948
1424
  }
1425
+ /**
1426
+ * Creates a new workflow run (alias for createRun)
1427
+ * @param params - Optional object containing the optional runId
1428
+ * @returns Promise containing the runId of the created run
1429
+ */
1430
+ createRunAsync(params) {
1431
+ return this.createRun(params);
1432
+ }
949
1433
  /**
950
1434
  * Starts a workflow run synchronously without waiting for the workflow to complete
951
1435
  * @param params - Object containing the runId, inputData and runtimeContext
@@ -997,9 +1481,9 @@ var Workflow = class extends BaseResource {
997
1481
  });
998
1482
  }
999
1483
  /**
1000
- * Starts a vNext workflow run and returns a stream
1484
+ * Starts a workflow run and returns a stream
1001
1485
  * @param params - Object containing the optional runId, inputData and runtimeContext
1002
- * @returns Promise containing the vNext workflow execution results
1486
+ * @returns Promise containing the workflow execution results
1003
1487
  */
1004
1488
  async stream(params) {
1005
1489
  const searchParams = new URLSearchParams();
@@ -1021,6 +1505,7 @@ var Workflow = class extends BaseResource {
1021
1505
  if (!response.body) {
1022
1506
  throw new Error("Response body is null");
1023
1507
  }
1508
+ let failedChunk = void 0;
1024
1509
  const transformStream = new TransformStream({
1025
1510
  start() {
1026
1511
  },
@@ -1030,10 +1515,13 @@ var Workflow = class extends BaseResource {
1030
1515
  const chunks = decoded.split(RECORD_SEPARATOR2);
1031
1516
  for (const chunk2 of chunks) {
1032
1517
  if (chunk2) {
1518
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1033
1519
  try {
1034
- const parsedChunk = JSON.parse(chunk2);
1520
+ const parsedChunk = JSON.parse(newChunk);
1035
1521
  controller.enqueue(parsedChunk);
1036
- } catch {
1522
+ failedChunk = void 0;
1523
+ } catch (error) {
1524
+ failedChunk = newChunk;
1037
1525
  }
1038
1526
  }
1039
1527
  }
@@ -1215,6 +1703,207 @@ var MCPTool = class extends BaseResource {
1215
1703
  }
1216
1704
  };
1217
1705
 
1706
+ // src/resources/network-memory-thread.ts
1707
+ var NetworkMemoryThread = class extends BaseResource {
1708
+ constructor(options, threadId, networkId) {
1709
+ super(options);
1710
+ this.threadId = threadId;
1711
+ this.networkId = networkId;
1712
+ }
1713
+ /**
1714
+ * Retrieves the memory thread details
1715
+ * @returns Promise containing thread details including title and metadata
1716
+ */
1717
+ get() {
1718
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1719
+ }
1720
+ /**
1721
+ * Updates the memory thread properties
1722
+ * @param params - Update parameters including title and metadata
1723
+ * @returns Promise containing updated thread details
1724
+ */
1725
+ update(params) {
1726
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1727
+ method: "PATCH",
1728
+ body: params
1729
+ });
1730
+ }
1731
+ /**
1732
+ * Deletes the memory thread
1733
+ * @returns Promise containing deletion result
1734
+ */
1735
+ delete() {
1736
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1737
+ method: "DELETE"
1738
+ });
1739
+ }
1740
+ /**
1741
+ * Retrieves messages associated with the thread
1742
+ * @param params - Optional parameters including limit for number of messages to retrieve
1743
+ * @returns Promise containing thread messages and UI messages
1744
+ */
1745
+ getMessages(params) {
1746
+ const query = new URLSearchParams({
1747
+ networkId: this.networkId,
1748
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1749
+ });
1750
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1751
+ }
1752
+ /**
1753
+ * Deletes one or more messages from the thread
1754
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1755
+ * message object with id property, or array of message objects
1756
+ * @returns Promise containing deletion result
1757
+ */
1758
+ deleteMessages(messageIds) {
1759
+ const query = new URLSearchParams({
1760
+ networkId: this.networkId
1761
+ });
1762
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
1763
+ method: "POST",
1764
+ body: { messageIds }
1765
+ });
1766
+ }
1767
+ };
1768
+
1769
+ // src/resources/vNextNetwork.ts
1770
+ var RECORD_SEPARATOR3 = "";
1771
+ var VNextNetwork = class extends BaseResource {
1772
+ constructor(options, networkId) {
1773
+ super(options);
1774
+ this.networkId = networkId;
1775
+ }
1776
+ /**
1777
+ * Retrieves details about the network
1778
+ * @returns Promise containing vNext network details
1779
+ */
1780
+ details() {
1781
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1782
+ }
1783
+ /**
1784
+ * Generates a response from the v-next network
1785
+ * @param params - Generation parameters including message
1786
+ * @returns Promise containing the generated response
1787
+ */
1788
+ generate(params) {
1789
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1790
+ method: "POST",
1791
+ body: {
1792
+ ...params,
1793
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1794
+ }
1795
+ });
1796
+ }
1797
+ /**
1798
+ * Generates a response from the v-next network using multiple primitives
1799
+ * @param params - Generation parameters including message
1800
+ * @returns Promise containing the generated response
1801
+ */
1802
+ loop(params) {
1803
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1804
+ method: "POST",
1805
+ body: {
1806
+ ...params,
1807
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1808
+ }
1809
+ });
1810
+ }
1811
+ async *streamProcessor(stream) {
1812
+ const reader = stream.getReader();
1813
+ let doneReading = false;
1814
+ let buffer = "";
1815
+ try {
1816
+ while (!doneReading) {
1817
+ const { done, value } = await reader.read();
1818
+ doneReading = done;
1819
+ if (done && !value) continue;
1820
+ try {
1821
+ const decoded = value ? new TextDecoder().decode(value) : "";
1822
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1823
+ buffer = chunks.pop() || "";
1824
+ for (const chunk of chunks) {
1825
+ if (chunk) {
1826
+ if (typeof chunk === "string") {
1827
+ try {
1828
+ const parsedChunk = JSON.parse(chunk);
1829
+ yield parsedChunk;
1830
+ } catch {
1831
+ }
1832
+ }
1833
+ }
1834
+ }
1835
+ } catch {
1836
+ }
1837
+ }
1838
+ if (buffer) {
1839
+ try {
1840
+ yield JSON.parse(buffer);
1841
+ } catch {
1842
+ }
1843
+ }
1844
+ } finally {
1845
+ reader.cancel().catch(() => {
1846
+ });
1847
+ }
1848
+ }
1849
+ /**
1850
+ * Streams a response from the v-next network
1851
+ * @param params - Stream parameters including message
1852
+ * @returns Promise containing the results
1853
+ */
1854
+ async stream(params, onRecord) {
1855
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1856
+ method: "POST",
1857
+ body: {
1858
+ ...params,
1859
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1860
+ },
1861
+ stream: true
1862
+ });
1863
+ if (!response.ok) {
1864
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1865
+ }
1866
+ if (!response.body) {
1867
+ throw new Error("Response body is null");
1868
+ }
1869
+ for await (const record of this.streamProcessor(response.body)) {
1870
+ if (typeof record === "string") {
1871
+ onRecord(JSON.parse(record));
1872
+ } else {
1873
+ onRecord(record);
1874
+ }
1875
+ }
1876
+ }
1877
+ /**
1878
+ * Streams a response from the v-next network loop
1879
+ * @param params - Stream parameters including message
1880
+ * @returns Promise containing the results
1881
+ */
1882
+ async loopStream(params, onRecord) {
1883
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1884
+ method: "POST",
1885
+ body: {
1886
+ ...params,
1887
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1888
+ },
1889
+ stream: true
1890
+ });
1891
+ if (!response.ok) {
1892
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1893
+ }
1894
+ if (!response.body) {
1895
+ throw new Error("Response body is null");
1896
+ }
1897
+ for await (const record of this.streamProcessor(response.body)) {
1898
+ if (typeof record === "string") {
1899
+ onRecord(JSON.parse(record));
1900
+ } else {
1901
+ onRecord(record);
1902
+ }
1903
+ }
1904
+ }
1905
+ };
1906
+
1218
1907
  // src/client.ts
1219
1908
  var MastraClient = class extends BaseResource {
1220
1909
  constructor(options) {
@@ -1292,6 +1981,48 @@ var MastraClient = class extends BaseResource {
1292
1981
  getMemoryStatus(agentId) {
1293
1982
  return this.request(`/api/memory/status?agentId=${agentId}`);
1294
1983
  }
1984
+ /**
1985
+ * Retrieves memory threads for a resource
1986
+ * @param params - Parameters containing the resource ID
1987
+ * @returns Promise containing array of memory threads
1988
+ */
1989
+ getNetworkMemoryThreads(params) {
1990
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1991
+ }
1992
+ /**
1993
+ * Creates a new memory thread
1994
+ * @param params - Parameters for creating the memory thread
1995
+ * @returns Promise containing the created memory thread
1996
+ */
1997
+ createNetworkMemoryThread(params) {
1998
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1999
+ }
2000
+ /**
2001
+ * Gets a memory thread instance by ID
2002
+ * @param threadId - ID of the memory thread to retrieve
2003
+ * @returns MemoryThread instance
2004
+ */
2005
+ getNetworkMemoryThread(threadId, networkId) {
2006
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2007
+ }
2008
+ /**
2009
+ * Saves messages to memory
2010
+ * @param params - Parameters containing messages to save
2011
+ * @returns Promise containing the saved messages
2012
+ */
2013
+ saveNetworkMessageToMemory(params) {
2014
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2015
+ method: "POST",
2016
+ body: params
2017
+ });
2018
+ }
2019
+ /**
2020
+ * Gets the status of the memory system
2021
+ * @returns Promise containing memory system status
2022
+ */
2023
+ getNetworkMemoryStatus(networkId) {
2024
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2025
+ }
1295
2026
  /**
1296
2027
  * Retrieves all available tools
1297
2028
  * @returns Promise containing map of tool IDs to tool details
@@ -1305,7 +2036,7 @@ var MastraClient = class extends BaseResource {
1305
2036
  * @returns Tool instance
1306
2037
  */
1307
2038
  getTool(toolId) {
1308
- return new Tool(this.options, toolId);
2039
+ return new Tool2(this.options, toolId);
1309
2040
  }
1310
2041
  /**
1311
2042
  * Retrieves all available legacy workflows
@@ -1488,6 +2219,13 @@ var MastraClient = class extends BaseResource {
1488
2219
  getNetworks() {
1489
2220
  return this.request("/api/networks");
1490
2221
  }
2222
+ /**
2223
+ * Retrieves all available vNext networks
2224
+ * @returns Promise containing map of vNext network IDs to vNext network details
2225
+ */
2226
+ getVNextNetworks() {
2227
+ return this.request("/api/networks/v-next");
2228
+ }
1491
2229
  /**
1492
2230
  * Gets a network instance by ID
1493
2231
  * @param networkId - ID of the network to retrieve
@@ -1496,6 +2234,14 @@ var MastraClient = class extends BaseResource {
1496
2234
  getNetwork(networkId) {
1497
2235
  return new Network(this.options, networkId);
1498
2236
  }
2237
+ /**
2238
+ * Gets a vNext network instance by ID
2239
+ * @param networkId - ID of the vNext network to retrieve
2240
+ * @returns vNext Network instance
2241
+ */
2242
+ getVNextNetwork(networkId) {
2243
+ return new VNextNetwork(this.options, networkId);
2244
+ }
1499
2245
  /**
1500
2246
  * Retrieves a list of available MCP servers.
1501
2247
  * @param params - Optional parameters for pagination (limit, offset).
@@ -1552,6 +2298,121 @@ var MastraClient = class extends BaseResource {
1552
2298
  getA2A(agentId) {
1553
2299
  return new A2A(this.options, agentId);
1554
2300
  }
2301
+ /**
2302
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2303
+ * @param agentId - ID of the agent.
2304
+ * @param threadId - ID of the thread.
2305
+ * @param resourceId - Optional ID of the resource.
2306
+ * @returns Working memory for the specified thread or resource.
2307
+ */
2308
+ getWorkingMemory({
2309
+ agentId,
2310
+ threadId,
2311
+ resourceId
2312
+ }) {
2313
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2314
+ }
2315
+ /**
2316
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2317
+ * @param agentId - ID of the agent.
2318
+ * @param threadId - ID of the thread.
2319
+ * @param workingMemory - The new working memory content.
2320
+ * @param resourceId - Optional ID of the resource.
2321
+ */
2322
+ updateWorkingMemory({
2323
+ agentId,
2324
+ threadId,
2325
+ workingMemory,
2326
+ resourceId
2327
+ }) {
2328
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2329
+ method: "POST",
2330
+ body: {
2331
+ workingMemory,
2332
+ resourceId
2333
+ }
2334
+ });
2335
+ }
2336
+ /**
2337
+ * Retrieves all available scorers
2338
+ * @returns Promise containing list of available scorers
2339
+ */
2340
+ getScorers() {
2341
+ return this.request("/api/scores/scorers");
2342
+ }
2343
+ /**
2344
+ * Retrieves a scorer by ID
2345
+ * @param scorerId - ID of the scorer to retrieve
2346
+ * @returns Promise containing the scorer
2347
+ */
2348
+ getScorer(scorerId) {
2349
+ return this.request(`/api/scores/scorers/${scorerId}`);
2350
+ }
2351
+ getScoresByScorerId(params) {
2352
+ const { page, perPage, scorerId, entityId, entityType } = params;
2353
+ const searchParams = new URLSearchParams();
2354
+ if (entityId) {
2355
+ searchParams.set("entityId", entityId);
2356
+ }
2357
+ if (entityType) {
2358
+ searchParams.set("entityType", entityType);
2359
+ }
2360
+ if (page !== void 0) {
2361
+ searchParams.set("page", String(page));
2362
+ }
2363
+ if (perPage !== void 0) {
2364
+ searchParams.set("perPage", String(perPage));
2365
+ }
2366
+ const queryString = searchParams.toString();
2367
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
2368
+ }
2369
+ /**
2370
+ * Retrieves scores by run ID
2371
+ * @param params - Parameters containing run ID and pagination options
2372
+ * @returns Promise containing scores and pagination info
2373
+ */
2374
+ getScoresByRunId(params) {
2375
+ const { runId, page, perPage } = params;
2376
+ const searchParams = new URLSearchParams();
2377
+ if (page !== void 0) {
2378
+ searchParams.set("page", String(page));
2379
+ }
2380
+ if (perPage !== void 0) {
2381
+ searchParams.set("perPage", String(perPage));
2382
+ }
2383
+ const queryString = searchParams.toString();
2384
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
2385
+ }
2386
+ /**
2387
+ * Retrieves scores by entity ID and type
2388
+ * @param params - Parameters containing entity ID, type, and pagination options
2389
+ * @returns Promise containing scores and pagination info
2390
+ */
2391
+ getScoresByEntityId(params) {
2392
+ const { entityId, entityType, page, perPage } = params;
2393
+ const searchParams = new URLSearchParams();
2394
+ if (page !== void 0) {
2395
+ searchParams.set("page", String(page));
2396
+ }
2397
+ if (perPage !== void 0) {
2398
+ searchParams.set("perPage", String(perPage));
2399
+ }
2400
+ const queryString = searchParams.toString();
2401
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
2402
+ }
2403
+ /**
2404
+ * Saves a score
2405
+ * @param params - Parameters containing the score data to save
2406
+ * @returns Promise containing the saved score
2407
+ */
2408
+ saveScore(params) {
2409
+ return this.request("/api/scores", {
2410
+ method: "POST",
2411
+ body: params
2412
+ });
2413
+ }
1555
2414
  };
1556
2415
 
1557
2416
  export { MastraClient };
2417
+ //# sourceMappingURL=index.js.map
2418
+ //# sourceMappingURL=index.js.map