@mastra/client-js 0.0.0-taofeeqInngest-20250603090617 → 0.0.0-transpile-packages-20250724123433

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.
package/dist/index.cjs CHANGED
@@ -5,6 +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');
9
+ var uuid = require('@lukeed/uuid');
8
10
  var runtimeContext = require('@mastra/core/runtime-context');
9
11
 
10
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -202,6 +204,33 @@ function zodToJsonSchema(zodSchema) {
202
204
  }
203
205
  return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
204
206
  }
207
+ function processClientTools(clientTools) {
208
+ if (!clientTools) {
209
+ return void 0;
210
+ }
211
+ return Object.fromEntries(
212
+ Object.entries(clientTools).map(([key, value]) => {
213
+ if (tools.isVercelTool(value)) {
214
+ return [
215
+ key,
216
+ {
217
+ ...value,
218
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
219
+ }
220
+ ];
221
+ } else {
222
+ return [
223
+ key,
224
+ {
225
+ ...value,
226
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
227
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
228
+ }
229
+ ];
230
+ }
231
+ })
232
+ );
233
+ }
205
234
 
206
235
  // src/resources/base.ts
207
236
  var BaseResource = class {
@@ -224,11 +253,13 @@ var BaseResource = class {
224
253
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
225
254
  ...options,
226
255
  headers: {
256
+ ...options.body && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
227
257
  ...headers,
228
258
  ...options.headers
229
259
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
230
260
  // 'x-mastra-client-type': 'js',
231
261
  },
262
+ signal: this.options.abortSignal,
232
263
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
233
264
  });
234
265
  if (!response.ok) {
@@ -270,8 +301,6 @@ function parseClientRuntimeContext(runtimeContext$1) {
270
301
  }
271
302
  return void 0;
272
303
  }
273
-
274
- // src/resources/agent.ts
275
304
  var AgentVoice = class extends BaseResource {
276
305
  constructor(options, agentId) {
277
306
  super(options);
@@ -340,50 +369,478 @@ var Agent = class extends BaseResource {
340
369
  details() {
341
370
  return this.request(`/api/agents/${this.agentId}`);
342
371
  }
343
- /**
344
- * Generates a response from the agent
345
- * @param params - Generation parameters including prompt
346
- * @returns Promise containing the generated response
347
- */
348
- generate(params) {
372
+ async generate(params) {
349
373
  const processedParams = {
350
374
  ...params,
351
375
  output: params.output ? zodToJsonSchema(params.output) : void 0,
352
376
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
353
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
377
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
378
+ clientTools: processClientTools(params.clientTools)
354
379
  };
355
- return this.request(`/api/agents/${this.agentId}/generate`, {
380
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
381
+ const response = await this.request(`/api/agents/${this.agentId}/generate`, {
356
382
  method: "POST",
357
383
  body: processedParams
358
384
  });
385
+ if (response.finishReason === "tool-calls") {
386
+ const toolCalls = response.toolCalls;
387
+ if (!toolCalls || !Array.isArray(toolCalls)) {
388
+ return response;
389
+ }
390
+ for (const toolCall of toolCalls) {
391
+ const clientTool = params.clientTools?.[toolCall.toolName];
392
+ if (clientTool && clientTool.execute) {
393
+ const result = await clientTool.execute(
394
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
395
+ {
396
+ messages: response.messages,
397
+ toolCallId: toolCall?.toolCallId
398
+ }
399
+ );
400
+ const updatedMessages = [
401
+ {
402
+ role: "user",
403
+ content: params.messages
404
+ },
405
+ ...response.response.messages,
406
+ {
407
+ role: "tool",
408
+ content: [
409
+ {
410
+ type: "tool-result",
411
+ toolCallId: toolCall.toolCallId,
412
+ toolName: toolCall.toolName,
413
+ result
414
+ }
415
+ ]
416
+ }
417
+ ];
418
+ return this.generate({
419
+ ...params,
420
+ messages: updatedMessages
421
+ });
422
+ }
423
+ }
424
+ }
425
+ return response;
426
+ }
427
+ async processChatResponse({
428
+ stream,
429
+ update,
430
+ onToolCall,
431
+ onFinish,
432
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
433
+ lastMessage,
434
+ streamProtocol
435
+ }) {
436
+ const replaceLastMessage = lastMessage?.role === "assistant";
437
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
438
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
439
+ return Math.max(max, toolInvocation.step ?? 0);
440
+ }, 0) ?? 0) : 0;
441
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
442
+ id: uuid.v4(),
443
+ createdAt: getCurrentDate(),
444
+ role: "assistant",
445
+ content: "",
446
+ parts: []
447
+ };
448
+ let currentTextPart = void 0;
449
+ let currentReasoningPart = void 0;
450
+ let currentReasoningTextDetail = void 0;
451
+ function updateToolInvocationPart(toolCallId, invocation) {
452
+ const part = message.parts.find(
453
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
454
+ );
455
+ if (part != null) {
456
+ part.toolInvocation = invocation;
457
+ } else {
458
+ message.parts.push({
459
+ type: "tool-invocation",
460
+ toolInvocation: invocation
461
+ });
462
+ }
463
+ }
464
+ const data = [];
465
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
466
+ const partialToolCalls = {};
467
+ let usage = {
468
+ completionTokens: NaN,
469
+ promptTokens: NaN,
470
+ totalTokens: NaN
471
+ };
472
+ let finishReason = "unknown";
473
+ function execUpdate() {
474
+ const copiedData = [...data];
475
+ if (messageAnnotations?.length) {
476
+ message.annotations = messageAnnotations;
477
+ }
478
+ const copiedMessage = {
479
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
480
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
481
+ ...structuredClone(message),
482
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
483
+ // hashing approach by default to detect changes, but it only works for shallow
484
+ // changes. This is why we need to add a revision id to ensure that the message
485
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
486
+ // forwarded to rendering):
487
+ revisionId: uuid.v4()
488
+ };
489
+ update({
490
+ message: copiedMessage,
491
+ data: copiedData,
492
+ replaceLastMessage
493
+ });
494
+ }
495
+ if (streamProtocol === "text") {
496
+ await uiUtils.processTextStream({
497
+ stream,
498
+ onTextPart(value) {
499
+ message.content += value;
500
+ execUpdate();
501
+ }
502
+ });
503
+ onFinish?.({ message, finishReason, usage });
504
+ } else {
505
+ await uiUtils.processDataStream({
506
+ stream,
507
+ onTextPart(value) {
508
+ if (currentTextPart == null) {
509
+ currentTextPart = {
510
+ type: "text",
511
+ text: value
512
+ };
513
+ message.parts.push(currentTextPart);
514
+ } else {
515
+ currentTextPart.text += value;
516
+ }
517
+ message.content += value;
518
+ execUpdate();
519
+ },
520
+ onReasoningPart(value) {
521
+ if (currentReasoningTextDetail == null) {
522
+ currentReasoningTextDetail = { type: "text", text: value };
523
+ if (currentReasoningPart != null) {
524
+ currentReasoningPart.details.push(currentReasoningTextDetail);
525
+ }
526
+ } else {
527
+ currentReasoningTextDetail.text += value;
528
+ }
529
+ if (currentReasoningPart == null) {
530
+ currentReasoningPart = {
531
+ type: "reasoning",
532
+ reasoning: value,
533
+ details: [currentReasoningTextDetail]
534
+ };
535
+ message.parts.push(currentReasoningPart);
536
+ } else {
537
+ currentReasoningPart.reasoning += value;
538
+ }
539
+ message.reasoning = (message.reasoning ?? "") + value;
540
+ execUpdate();
541
+ },
542
+ onReasoningSignaturePart(value) {
543
+ if (currentReasoningTextDetail != null) {
544
+ currentReasoningTextDetail.signature = value.signature;
545
+ }
546
+ },
547
+ onRedactedReasoningPart(value) {
548
+ if (currentReasoningPart == null) {
549
+ currentReasoningPart = {
550
+ type: "reasoning",
551
+ reasoning: "",
552
+ details: []
553
+ };
554
+ message.parts.push(currentReasoningPart);
555
+ }
556
+ currentReasoningPart.details.push({
557
+ type: "redacted",
558
+ data: value.data
559
+ });
560
+ currentReasoningTextDetail = void 0;
561
+ execUpdate();
562
+ },
563
+ onFilePart(value) {
564
+ message.parts.push({
565
+ type: "file",
566
+ mimeType: value.mimeType,
567
+ data: value.data
568
+ });
569
+ execUpdate();
570
+ },
571
+ onSourcePart(value) {
572
+ message.parts.push({
573
+ type: "source",
574
+ source: value
575
+ });
576
+ execUpdate();
577
+ },
578
+ onToolCallStreamingStartPart(value) {
579
+ if (message.toolInvocations == null) {
580
+ message.toolInvocations = [];
581
+ }
582
+ partialToolCalls[value.toolCallId] = {
583
+ text: "",
584
+ step,
585
+ toolName: value.toolName,
586
+ index: message.toolInvocations.length
587
+ };
588
+ const invocation = {
589
+ state: "partial-call",
590
+ step,
591
+ toolCallId: value.toolCallId,
592
+ toolName: value.toolName,
593
+ args: void 0
594
+ };
595
+ message.toolInvocations.push(invocation);
596
+ updateToolInvocationPart(value.toolCallId, invocation);
597
+ execUpdate();
598
+ },
599
+ onToolCallDeltaPart(value) {
600
+ const partialToolCall = partialToolCalls[value.toolCallId];
601
+ partialToolCall.text += value.argsTextDelta;
602
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
603
+ const invocation = {
604
+ state: "partial-call",
605
+ step: partialToolCall.step,
606
+ toolCallId: value.toolCallId,
607
+ toolName: partialToolCall.toolName,
608
+ args: partialArgs
609
+ };
610
+ message.toolInvocations[partialToolCall.index] = invocation;
611
+ updateToolInvocationPart(value.toolCallId, invocation);
612
+ execUpdate();
613
+ },
614
+ async onToolCallPart(value) {
615
+ const invocation = {
616
+ state: "call",
617
+ step,
618
+ ...value
619
+ };
620
+ if (partialToolCalls[value.toolCallId] != null) {
621
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
622
+ } else {
623
+ if (message.toolInvocations == null) {
624
+ message.toolInvocations = [];
625
+ }
626
+ message.toolInvocations.push(invocation);
627
+ }
628
+ updateToolInvocationPart(value.toolCallId, invocation);
629
+ execUpdate();
630
+ if (onToolCall) {
631
+ const result = await onToolCall({ toolCall: value });
632
+ if (result != null) {
633
+ const invocation2 = {
634
+ state: "result",
635
+ step,
636
+ ...value,
637
+ result
638
+ };
639
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
640
+ updateToolInvocationPart(value.toolCallId, invocation2);
641
+ execUpdate();
642
+ }
643
+ }
644
+ },
645
+ onToolResultPart(value) {
646
+ const toolInvocations = message.toolInvocations;
647
+ if (toolInvocations == null) {
648
+ throw new Error("tool_result must be preceded by a tool_call");
649
+ }
650
+ const toolInvocationIndex = toolInvocations.findIndex(
651
+ (invocation2) => invocation2.toolCallId === value.toolCallId
652
+ );
653
+ if (toolInvocationIndex === -1) {
654
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
655
+ }
656
+ const invocation = {
657
+ ...toolInvocations[toolInvocationIndex],
658
+ state: "result",
659
+ ...value
660
+ };
661
+ toolInvocations[toolInvocationIndex] = invocation;
662
+ updateToolInvocationPart(value.toolCallId, invocation);
663
+ execUpdate();
664
+ },
665
+ onDataPart(value) {
666
+ data.push(...value);
667
+ execUpdate();
668
+ },
669
+ onMessageAnnotationsPart(value) {
670
+ if (messageAnnotations == null) {
671
+ messageAnnotations = [...value];
672
+ } else {
673
+ messageAnnotations.push(...value);
674
+ }
675
+ execUpdate();
676
+ },
677
+ onFinishStepPart(value) {
678
+ step += 1;
679
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
680
+ currentReasoningPart = void 0;
681
+ currentReasoningTextDetail = void 0;
682
+ },
683
+ onStartStepPart(value) {
684
+ if (!replaceLastMessage) {
685
+ message.id = value.messageId;
686
+ }
687
+ message.parts.push({ type: "step-start" });
688
+ execUpdate();
689
+ },
690
+ onFinishMessagePart(value) {
691
+ finishReason = value.finishReason;
692
+ if (value.usage != null) {
693
+ usage = value.usage;
694
+ }
695
+ },
696
+ onErrorPart(error) {
697
+ throw new Error(error);
698
+ }
699
+ });
700
+ onFinish?.({ message, finishReason, usage });
701
+ }
702
+ }
703
+ /**
704
+ * Processes the stream response and handles tool calls
705
+ */
706
+ async processStreamResponse(processedParams, writable) {
707
+ const response = await this.request(`/api/agents/${this.agentId}/stream`, {
708
+ method: "POST",
709
+ body: processedParams,
710
+ stream: true
711
+ });
712
+ if (!response.body) {
713
+ throw new Error("No response body");
714
+ }
715
+ try {
716
+ const streamProtocol = processedParams.output ? "text" : "data";
717
+ let toolCalls = [];
718
+ let messages = [];
719
+ const [streamForWritable, streamForProcessing] = response.body.tee();
720
+ streamForWritable.pipeTo(writable, {
721
+ preventClose: true
722
+ }).catch((error) => {
723
+ console.error("Error piping to writable stream:", error);
724
+ });
725
+ this.processChatResponse({
726
+ stream: streamForProcessing,
727
+ update: ({ message }) => {
728
+ messages.push(message);
729
+ },
730
+ onFinish: async ({ finishReason, message }) => {
731
+ if (finishReason === "tool-calls") {
732
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
733
+ if (toolCall) {
734
+ toolCalls.push(toolCall);
735
+ }
736
+ for (const toolCall2 of toolCalls) {
737
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
738
+ if (clientTool && clientTool.execute) {
739
+ const result = await clientTool.execute(
740
+ {
741
+ context: toolCall2?.args,
742
+ runId: processedParams.runId,
743
+ resourceId: processedParams.resourceId,
744
+ threadId: processedParams.threadId,
745
+ runtimeContext: processedParams.runtimeContext
746
+ },
747
+ {
748
+ messages: response.messages,
749
+ toolCallId: toolCall2?.toolCallId
750
+ }
751
+ );
752
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
753
+ const toolInvocationPart = lastMessage?.parts?.find(
754
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
755
+ );
756
+ if (toolInvocationPart) {
757
+ toolInvocationPart.toolInvocation = {
758
+ ...toolInvocationPart.toolInvocation,
759
+ state: "result",
760
+ result
761
+ };
762
+ }
763
+ const toolInvocation = lastMessage?.toolInvocations?.find(
764
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
765
+ );
766
+ if (toolInvocation) {
767
+ toolInvocation.state = "result";
768
+ toolInvocation.result = result;
769
+ }
770
+ const writer = writable.getWriter();
771
+ try {
772
+ await writer.write(
773
+ new TextEncoder().encode(
774
+ "a:" + JSON.stringify({
775
+ toolCallId: toolCall2.toolCallId,
776
+ result
777
+ }) + "\n"
778
+ )
779
+ );
780
+ } finally {
781
+ writer.releaseLock();
782
+ }
783
+ const originalMessages = processedParams.messages;
784
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
785
+ this.processStreamResponse(
786
+ {
787
+ ...processedParams,
788
+ messages: [...messageArray, ...messages, lastMessage]
789
+ },
790
+ writable
791
+ );
792
+ }
793
+ }
794
+ } else {
795
+ setTimeout(() => {
796
+ if (!writable.locked) {
797
+ writable.close();
798
+ }
799
+ }, 0);
800
+ }
801
+ },
802
+ lastMessage: void 0,
803
+ streamProtocol
804
+ });
805
+ } catch (error) {
806
+ console.error("Error processing stream response:", error);
807
+ }
808
+ return response;
359
809
  }
360
810
  /**
361
811
  * Streams a response from the agent
362
812
  * @param params - Stream parameters including prompt
363
- * @returns Promise containing the enhanced Response object with processDataStream method
813
+ * @returns Promise containing the enhanced Response object with processDataStream and processTextStream methods
364
814
  */
365
815
  async stream(params) {
366
816
  const processedParams = {
367
817
  ...params,
368
818
  output: params.output ? zodToJsonSchema(params.output) : void 0,
369
819
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
370
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
820
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
821
+ clientTools: processClientTools(params.clientTools)
371
822
  };
372
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
373
- method: "POST",
374
- body: processedParams,
375
- stream: true
823
+ const { readable, writable } = new TransformStream();
824
+ const response = await this.processStreamResponse(processedParams, writable);
825
+ const streamResponse = new Response(readable, {
826
+ status: response.status,
827
+ statusText: response.statusText,
828
+ headers: response.headers
376
829
  });
377
- if (!response.body) {
378
- throw new Error("No response body");
379
- }
380
- response.processDataStream = async (options = {}) => {
830
+ streamResponse.processDataStream = async (options = {}) => {
381
831
  await uiUtils.processDataStream({
382
- stream: response.body,
832
+ stream: streamResponse.body,
383
833
  ...options
384
834
  });
385
835
  };
386
- return response;
836
+ streamResponse.processTextStream = async (options) => {
837
+ await uiUtils.processTextStream({
838
+ stream: streamResponse.body,
839
+ onTextPart: options?.onTextPart ?? (() => {
840
+ })
841
+ });
842
+ };
843
+ return streamResponse;
387
844
  }
388
845
  /**
389
846
  * Gets details about a specific tool available to the agent
@@ -527,6 +984,21 @@ var MemoryThread = class extends BaseResource {
527
984
  });
528
985
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
529
986
  }
987
+ /**
988
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
989
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
990
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
991
+ */
992
+ getMessagesPaginated({
993
+ selectBy,
994
+ ...rest
995
+ }) {
996
+ const query = new URLSearchParams({
997
+ ...rest,
998
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
999
+ });
1000
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1001
+ }
530
1002
  };
531
1003
 
532
1004
  // src/resources/vector.ts
@@ -777,7 +1249,7 @@ var LegacyWorkflow = class extends BaseResource {
777
1249
  };
778
1250
 
779
1251
  // src/resources/tool.ts
780
- var Tool = class extends BaseResource {
1252
+ var Tool2 = class extends BaseResource {
781
1253
  constructor(options, toolId) {
782
1254
  super(options);
783
1255
  this.toolId = toolId;
@@ -882,10 +1354,10 @@ var Workflow = class extends BaseResource {
882
1354
  if (params?.toDate) {
883
1355
  searchParams.set("toDate", params.toDate.toISOString());
884
1356
  }
885
- if (params?.limit) {
1357
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
886
1358
  searchParams.set("limit", String(params.limit));
887
1359
  }
888
- if (params?.offset) {
1360
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
889
1361
  searchParams.set("offset", String(params.offset));
890
1362
  }
891
1363
  if (params?.resourceId) {
@@ -897,6 +1369,43 @@ var Workflow = class extends BaseResource {
897
1369
  return this.request(`/api/workflows/${this.workflowId}/runs`);
898
1370
  }
899
1371
  }
1372
+ /**
1373
+ * Retrieves a specific workflow run by its ID
1374
+ * @param runId - The ID of the workflow run to retrieve
1375
+ * @returns Promise containing the workflow run details
1376
+ */
1377
+ runById(runId) {
1378
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1379
+ }
1380
+ /**
1381
+ * Retrieves the execution result for a specific workflow run by its ID
1382
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1383
+ * @returns Promise containing the workflow run execution result
1384
+ */
1385
+ runExecutionResult(runId) {
1386
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1387
+ }
1388
+ /**
1389
+ * Cancels a specific workflow run by its ID
1390
+ * @param runId - The ID of the workflow run to cancel
1391
+ * @returns Promise containing a success message
1392
+ */
1393
+ cancelRun(runId) {
1394
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1395
+ method: "POST"
1396
+ });
1397
+ }
1398
+ /**
1399
+ * Sends an event to a specific workflow run by its ID
1400
+ * @param params - Object containing the runId, event and data
1401
+ * @returns Promise containing a success message
1402
+ */
1403
+ sendRunEvent(params) {
1404
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1405
+ method: "POST",
1406
+ body: { event: params.event, data: params.data }
1407
+ });
1408
+ }
900
1409
  /**
901
1410
  * Creates a new workflow run
902
1411
  * @param params - Optional object containing the optional runId
@@ -911,6 +1420,14 @@ var Workflow = class extends BaseResource {
911
1420
  method: "POST"
912
1421
  });
913
1422
  }
1423
+ /**
1424
+ * Creates a new workflow run (alias for createRun)
1425
+ * @param params - Optional object containing the optional runId
1426
+ * @returns Promise containing the runId of the created run
1427
+ */
1428
+ createRunAsync(params) {
1429
+ return this.createRun(params);
1430
+ }
914
1431
  /**
915
1432
  * Starts a workflow run synchronously without waiting for the workflow to complete
916
1433
  * @param params - Object containing the runId, inputData and runtimeContext
@@ -962,16 +1479,16 @@ var Workflow = class extends BaseResource {
962
1479
  });
963
1480
  }
964
1481
  /**
965
- * Starts a vNext workflow run and returns a stream
1482
+ * Starts a workflow run and returns a stream
966
1483
  * @param params - Object containing the optional runId, inputData and runtimeContext
967
- * @returns Promise containing the vNext workflow execution results
1484
+ * @returns Promise containing the workflow execution results
968
1485
  */
969
1486
  async stream(params) {
970
1487
  const searchParams = new URLSearchParams();
971
1488
  if (!!params?.runId) {
972
1489
  searchParams.set("runId", params.runId);
973
1490
  }
974
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
1491
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
975
1492
  const response = await this.request(
976
1493
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
977
1494
  {
@@ -986,6 +1503,7 @@ var Workflow = class extends BaseResource {
986
1503
  if (!response.body) {
987
1504
  throw new Error("Response body is null");
988
1505
  }
1506
+ let failedChunk = void 0;
989
1507
  const transformStream = new TransformStream({
990
1508
  start() {
991
1509
  },
@@ -995,10 +1513,13 @@ var Workflow = class extends BaseResource {
995
1513
  const chunks = decoded.split(RECORD_SEPARATOR2);
996
1514
  for (const chunk2 of chunks) {
997
1515
  if (chunk2) {
1516
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
998
1517
  try {
999
- const parsedChunk = JSON.parse(chunk2);
1518
+ const parsedChunk = JSON.parse(newChunk);
1000
1519
  controller.enqueue(parsedChunk);
1001
- } catch {
1520
+ failedChunk = void 0;
1521
+ } catch (error) {
1522
+ failedChunk = newChunk;
1002
1523
  }
1003
1524
  }
1004
1525
  }
@@ -1180,6 +1701,192 @@ var MCPTool = class extends BaseResource {
1180
1701
  }
1181
1702
  };
1182
1703
 
1704
+ // src/resources/network-memory-thread.ts
1705
+ var NetworkMemoryThread = class extends BaseResource {
1706
+ constructor(options, threadId, networkId) {
1707
+ super(options);
1708
+ this.threadId = threadId;
1709
+ this.networkId = networkId;
1710
+ }
1711
+ /**
1712
+ * Retrieves the memory thread details
1713
+ * @returns Promise containing thread details including title and metadata
1714
+ */
1715
+ get() {
1716
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1717
+ }
1718
+ /**
1719
+ * Updates the memory thread properties
1720
+ * @param params - Update parameters including title and metadata
1721
+ * @returns Promise containing updated thread details
1722
+ */
1723
+ update(params) {
1724
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1725
+ method: "PATCH",
1726
+ body: params
1727
+ });
1728
+ }
1729
+ /**
1730
+ * Deletes the memory thread
1731
+ * @returns Promise containing deletion result
1732
+ */
1733
+ delete() {
1734
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1735
+ method: "DELETE"
1736
+ });
1737
+ }
1738
+ /**
1739
+ * Retrieves messages associated with the thread
1740
+ * @param params - Optional parameters including limit for number of messages to retrieve
1741
+ * @returns Promise containing thread messages and UI messages
1742
+ */
1743
+ getMessages(params) {
1744
+ const query = new URLSearchParams({
1745
+ networkId: this.networkId,
1746
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1747
+ });
1748
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1749
+ }
1750
+ };
1751
+
1752
+ // src/resources/vNextNetwork.ts
1753
+ var RECORD_SEPARATOR3 = "";
1754
+ var VNextNetwork = class extends BaseResource {
1755
+ constructor(options, networkId) {
1756
+ super(options);
1757
+ this.networkId = networkId;
1758
+ }
1759
+ /**
1760
+ * Retrieves details about the network
1761
+ * @returns Promise containing vNext network details
1762
+ */
1763
+ details() {
1764
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1765
+ }
1766
+ /**
1767
+ * Generates a response from the v-next network
1768
+ * @param params - Generation parameters including message
1769
+ * @returns Promise containing the generated response
1770
+ */
1771
+ generate(params) {
1772
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1773
+ method: "POST",
1774
+ body: {
1775
+ ...params,
1776
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1777
+ }
1778
+ });
1779
+ }
1780
+ /**
1781
+ * Generates a response from the v-next network using multiple primitives
1782
+ * @param params - Generation parameters including message
1783
+ * @returns Promise containing the generated response
1784
+ */
1785
+ loop(params) {
1786
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1787
+ method: "POST",
1788
+ body: {
1789
+ ...params,
1790
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1791
+ }
1792
+ });
1793
+ }
1794
+ async *streamProcessor(stream) {
1795
+ const reader = stream.getReader();
1796
+ let doneReading = false;
1797
+ let buffer = "";
1798
+ try {
1799
+ while (!doneReading) {
1800
+ const { done, value } = await reader.read();
1801
+ doneReading = done;
1802
+ if (done && !value) continue;
1803
+ try {
1804
+ const decoded = value ? new TextDecoder().decode(value) : "";
1805
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1806
+ buffer = chunks.pop() || "";
1807
+ for (const chunk of chunks) {
1808
+ if (chunk) {
1809
+ if (typeof chunk === "string") {
1810
+ try {
1811
+ const parsedChunk = JSON.parse(chunk);
1812
+ yield parsedChunk;
1813
+ } catch {
1814
+ }
1815
+ }
1816
+ }
1817
+ }
1818
+ } catch {
1819
+ }
1820
+ }
1821
+ if (buffer) {
1822
+ try {
1823
+ yield JSON.parse(buffer);
1824
+ } catch {
1825
+ }
1826
+ }
1827
+ } finally {
1828
+ reader.cancel().catch(() => {
1829
+ });
1830
+ }
1831
+ }
1832
+ /**
1833
+ * Streams a response from the v-next network
1834
+ * @param params - Stream parameters including message
1835
+ * @returns Promise containing the results
1836
+ */
1837
+ async stream(params, onRecord) {
1838
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1839
+ method: "POST",
1840
+ body: {
1841
+ ...params,
1842
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1843
+ },
1844
+ stream: true
1845
+ });
1846
+ if (!response.ok) {
1847
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1848
+ }
1849
+ if (!response.body) {
1850
+ throw new Error("Response body is null");
1851
+ }
1852
+ for await (const record of this.streamProcessor(response.body)) {
1853
+ if (typeof record === "string") {
1854
+ onRecord(JSON.parse(record));
1855
+ } else {
1856
+ onRecord(record);
1857
+ }
1858
+ }
1859
+ }
1860
+ /**
1861
+ * Streams a response from the v-next network loop
1862
+ * @param params - Stream parameters including message
1863
+ * @returns Promise containing the results
1864
+ */
1865
+ async loopStream(params, onRecord) {
1866
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1867
+ method: "POST",
1868
+ body: {
1869
+ ...params,
1870
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1871
+ },
1872
+ stream: true
1873
+ });
1874
+ if (!response.ok) {
1875
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1876
+ }
1877
+ if (!response.body) {
1878
+ throw new Error("Response body is null");
1879
+ }
1880
+ for await (const record of this.streamProcessor(response.body)) {
1881
+ if (typeof record === "string") {
1882
+ onRecord(JSON.parse(record));
1883
+ } else {
1884
+ onRecord(record);
1885
+ }
1886
+ }
1887
+ }
1888
+ };
1889
+
1183
1890
  // src/client.ts
1184
1891
  var MastraClient = class extends BaseResource {
1185
1892
  constructor(options) {
@@ -1257,6 +1964,48 @@ var MastraClient = class extends BaseResource {
1257
1964
  getMemoryStatus(agentId) {
1258
1965
  return this.request(`/api/memory/status?agentId=${agentId}`);
1259
1966
  }
1967
+ /**
1968
+ * Retrieves memory threads for a resource
1969
+ * @param params - Parameters containing the resource ID
1970
+ * @returns Promise containing array of memory threads
1971
+ */
1972
+ getNetworkMemoryThreads(params) {
1973
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1974
+ }
1975
+ /**
1976
+ * Creates a new memory thread
1977
+ * @param params - Parameters for creating the memory thread
1978
+ * @returns Promise containing the created memory thread
1979
+ */
1980
+ createNetworkMemoryThread(params) {
1981
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1982
+ }
1983
+ /**
1984
+ * Gets a memory thread instance by ID
1985
+ * @param threadId - ID of the memory thread to retrieve
1986
+ * @returns MemoryThread instance
1987
+ */
1988
+ getNetworkMemoryThread(threadId, networkId) {
1989
+ return new NetworkMemoryThread(this.options, threadId, networkId);
1990
+ }
1991
+ /**
1992
+ * Saves messages to memory
1993
+ * @param params - Parameters containing messages to save
1994
+ * @returns Promise containing the saved messages
1995
+ */
1996
+ saveNetworkMessageToMemory(params) {
1997
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
1998
+ method: "POST",
1999
+ body: params
2000
+ });
2001
+ }
2002
+ /**
2003
+ * Gets the status of the memory system
2004
+ * @returns Promise containing memory system status
2005
+ */
2006
+ getNetworkMemoryStatus(networkId) {
2007
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2008
+ }
1260
2009
  /**
1261
2010
  * Retrieves all available tools
1262
2011
  * @returns Promise containing map of tool IDs to tool details
@@ -1270,7 +2019,7 @@ var MastraClient = class extends BaseResource {
1270
2019
  * @returns Tool instance
1271
2020
  */
1272
2021
  getTool(toolId) {
1273
- return new Tool(this.options, toolId);
2022
+ return new Tool2(this.options, toolId);
1274
2023
  }
1275
2024
  /**
1276
2025
  * Retrieves all available legacy workflows
@@ -1316,7 +2065,41 @@ var MastraClient = class extends BaseResource {
1316
2065
  * @returns Promise containing array of log messages
1317
2066
  */
1318
2067
  getLogs(params) {
1319
- return this.request(`/api/logs?transportId=${params.transportId}`);
2068
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2069
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2070
+ const searchParams = new URLSearchParams();
2071
+ if (transportId) {
2072
+ searchParams.set("transportId", transportId);
2073
+ }
2074
+ if (fromDate) {
2075
+ searchParams.set("fromDate", fromDate.toISOString());
2076
+ }
2077
+ if (toDate) {
2078
+ searchParams.set("toDate", toDate.toISOString());
2079
+ }
2080
+ if (logLevel) {
2081
+ searchParams.set("logLevel", logLevel);
2082
+ }
2083
+ if (page) {
2084
+ searchParams.set("page", String(page));
2085
+ }
2086
+ if (perPage) {
2087
+ searchParams.set("perPage", String(perPage));
2088
+ }
2089
+ if (_filters) {
2090
+ if (Array.isArray(_filters)) {
2091
+ for (const filter of _filters) {
2092
+ searchParams.append("filters", filter);
2093
+ }
2094
+ } else {
2095
+ searchParams.set("filters", _filters);
2096
+ }
2097
+ }
2098
+ if (searchParams.size) {
2099
+ return this.request(`/api/logs?${searchParams}`);
2100
+ } else {
2101
+ return this.request(`/api/logs`);
2102
+ }
1320
2103
  }
1321
2104
  /**
1322
2105
  * Gets logs for a specific run
@@ -1324,7 +2107,44 @@ var MastraClient = class extends BaseResource {
1324
2107
  * @returns Promise containing array of log messages
1325
2108
  */
1326
2109
  getLogForRun(params) {
1327
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2110
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2111
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2112
+ const searchParams = new URLSearchParams();
2113
+ if (runId) {
2114
+ searchParams.set("runId", runId);
2115
+ }
2116
+ if (transportId) {
2117
+ searchParams.set("transportId", transportId);
2118
+ }
2119
+ if (fromDate) {
2120
+ searchParams.set("fromDate", fromDate.toISOString());
2121
+ }
2122
+ if (toDate) {
2123
+ searchParams.set("toDate", toDate.toISOString());
2124
+ }
2125
+ if (logLevel) {
2126
+ searchParams.set("logLevel", logLevel);
2127
+ }
2128
+ if (page) {
2129
+ searchParams.set("page", String(page));
2130
+ }
2131
+ if (perPage) {
2132
+ searchParams.set("perPage", String(perPage));
2133
+ }
2134
+ if (_filters) {
2135
+ if (Array.isArray(_filters)) {
2136
+ for (const filter of _filters) {
2137
+ searchParams.append("filters", filter);
2138
+ }
2139
+ } else {
2140
+ searchParams.set("filters", _filters);
2141
+ }
2142
+ }
2143
+ if (searchParams.size) {
2144
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2145
+ } else {
2146
+ return this.request(`/api/logs/${runId}`);
2147
+ }
1328
2148
  }
1329
2149
  /**
1330
2150
  * List of all log transports
@@ -1382,6 +2202,13 @@ var MastraClient = class extends BaseResource {
1382
2202
  getNetworks() {
1383
2203
  return this.request("/api/networks");
1384
2204
  }
2205
+ /**
2206
+ * Retrieves all available vNext networks
2207
+ * @returns Promise containing map of vNext network IDs to vNext network details
2208
+ */
2209
+ getVNextNetworks() {
2210
+ return this.request("/api/networks/v-next");
2211
+ }
1385
2212
  /**
1386
2213
  * Gets a network instance by ID
1387
2214
  * @param networkId - ID of the network to retrieve
@@ -1390,6 +2217,14 @@ var MastraClient = class extends BaseResource {
1390
2217
  getNetwork(networkId) {
1391
2218
  return new Network(this.options, networkId);
1392
2219
  }
2220
+ /**
2221
+ * Gets a vNext network instance by ID
2222
+ * @param networkId - ID of the vNext network to retrieve
2223
+ * @returns vNext Network instance
2224
+ */
2225
+ getVNextNetwork(networkId) {
2226
+ return new VNextNetwork(this.options, networkId);
2227
+ }
1393
2228
  /**
1394
2229
  * Retrieves a list of available MCP servers.
1395
2230
  * @param params - Optional parameters for pagination (limit, offset).
@@ -1446,6 +2281,41 @@ var MastraClient = class extends BaseResource {
1446
2281
  getA2A(agentId) {
1447
2282
  return new A2A(this.options, agentId);
1448
2283
  }
2284
+ /**
2285
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2286
+ * @param agentId - ID of the agent.
2287
+ * @param threadId - ID of the thread.
2288
+ * @param resourceId - Optional ID of the resource.
2289
+ * @returns Working memory for the specified thread or resource.
2290
+ */
2291
+ getWorkingMemory({
2292
+ agentId,
2293
+ threadId,
2294
+ resourceId
2295
+ }) {
2296
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2297
+ }
2298
+ /**
2299
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2300
+ * @param agentId - ID of the agent.
2301
+ * @param threadId - ID of the thread.
2302
+ * @param workingMemory - The new working memory content.
2303
+ * @param resourceId - Optional ID of the resource.
2304
+ */
2305
+ updateWorkingMemory({
2306
+ agentId,
2307
+ threadId,
2308
+ workingMemory,
2309
+ resourceId
2310
+ }) {
2311
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2312
+ method: "POST",
2313
+ body: {
2314
+ workingMemory,
2315
+ resourceId
2316
+ }
2317
+ });
2318
+ }
1449
2319
  };
1450
2320
 
1451
2321
  exports.MastraClient = MastraClient;