@mastra/client-js 0.0.0-course-20250527170450 → 0.0.0-custom-instrumentation-20250708222033

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.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { AbstractAgent, EventType } from '@ag-ui/client';
2
2
  import { Observable } from 'rxjs';
3
- import { processDataStream } from '@ai-sdk/ui-utils';
3
+ import { processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
4
4
  import { ZodSchema } from 'zod';
5
5
  import originalZodToJsonSchema from 'zod-to-json-schema';
6
+ import { isVercelTool } from '@mastra/core/tools';
6
7
  import { RuntimeContext } from '@mastra/core/runtime-context';
7
8
 
8
9
  // src/adapters/agui.ts
@@ -196,6 +197,33 @@ function zodToJsonSchema(zodSchema) {
196
197
  }
197
198
  return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
198
199
  }
200
+ function processClientTools(clientTools) {
201
+ if (!clientTools) {
202
+ return void 0;
203
+ }
204
+ return Object.fromEntries(
205
+ Object.entries(clientTools).map(([key, value]) => {
206
+ if (isVercelTool(value)) {
207
+ return [
208
+ key,
209
+ {
210
+ ...value,
211
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
212
+ }
213
+ ];
214
+ } else {
215
+ return [
216
+ key,
217
+ {
218
+ ...value,
219
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
220
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
221
+ }
222
+ ];
223
+ }
224
+ })
225
+ );
226
+ }
199
227
 
200
228
  // src/resources/base.ts
201
229
  var BaseResource = class {
@@ -218,11 +246,13 @@ var BaseResource = class {
218
246
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
219
247
  ...options,
220
248
  headers: {
249
+ ...options.method === "POST" || options.method === "PUT" ? { "content-type": "application/json" } : {},
221
250
  ...headers,
222
251
  ...options.headers
223
252
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
224
253
  // 'x-mastra-client-type': 'js',
225
254
  },
255
+ signal: this.options.abortSignal,
226
256
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
227
257
  });
228
258
  if (!response.ok) {
@@ -264,8 +294,6 @@ function parseClientRuntimeContext(runtimeContext) {
264
294
  }
265
295
  return void 0;
266
296
  }
267
-
268
- // src/resources/agent.ts
269
297
  var AgentVoice = class extends BaseResource {
270
298
  constructor(options, agentId) {
271
299
  super(options);
@@ -312,6 +340,13 @@ var AgentVoice = class extends BaseResource {
312
340
  getSpeakers() {
313
341
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
314
342
  }
343
+ /**
344
+ * Get the listener configuration for the agent's voice provider
345
+ * @returns Promise containing a check if the agent has listening capabilities
346
+ */
347
+ getListener() {
348
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
349
+ }
315
350
  };
316
351
  var Agent = class extends BaseResource {
317
352
  constructor(options, agentId) {
@@ -327,22 +362,318 @@ var Agent = class extends BaseResource {
327
362
  details() {
328
363
  return this.request(`/api/agents/${this.agentId}`);
329
364
  }
330
- /**
331
- * Generates a response from the agent
332
- * @param params - Generation parameters including prompt
333
- * @returns Promise containing the generated response
334
- */
335
- generate(params) {
365
+ async generate(params) {
336
366
  const processedParams = {
337
367
  ...params,
338
368
  output: params.output ? zodToJsonSchema(params.output) : void 0,
339
369
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
340
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
370
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
371
+ clientTools: processClientTools(params.clientTools)
341
372
  };
342
- return this.request(`/api/agents/${this.agentId}/generate`, {
373
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
374
+ const response = await this.request(`/api/agents/${this.agentId}/generate`, {
343
375
  method: "POST",
344
376
  body: processedParams
345
377
  });
378
+ if (response.finishReason === "tool-calls") {
379
+ for (const toolCall of response.toolCalls) {
380
+ const clientTool = params.clientTools?.[toolCall.toolName];
381
+ if (clientTool && clientTool.execute) {
382
+ const result = await clientTool.execute(
383
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
384
+ {
385
+ messages: response.messages,
386
+ toolCallId: toolCall?.toolCallId
387
+ }
388
+ );
389
+ const updatedMessages = [
390
+ {
391
+ role: "user",
392
+ content: params.messages
393
+ },
394
+ ...response.response.messages,
395
+ {
396
+ role: "tool",
397
+ content: [
398
+ {
399
+ type: "tool-result",
400
+ toolCallId: toolCall.toolCallId,
401
+ toolName: toolCall.toolName,
402
+ result
403
+ }
404
+ ]
405
+ }
406
+ ];
407
+ return this.generate({
408
+ ...params,
409
+ messages: updatedMessages
410
+ });
411
+ }
412
+ }
413
+ }
414
+ return response;
415
+ }
416
+ async processChatResponse({
417
+ stream,
418
+ update,
419
+ onToolCall,
420
+ onFinish,
421
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
422
+ lastMessage
423
+ }) {
424
+ const replaceLastMessage = lastMessage?.role === "assistant";
425
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
426
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
427
+ return Math.max(max, toolInvocation.step ?? 0);
428
+ }, 0) ?? 0) : 0;
429
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
430
+ id: crypto.randomUUID(),
431
+ createdAt: getCurrentDate(),
432
+ role: "assistant",
433
+ content: "",
434
+ parts: []
435
+ };
436
+ let currentTextPart = void 0;
437
+ let currentReasoningPart = void 0;
438
+ let currentReasoningTextDetail = void 0;
439
+ function updateToolInvocationPart(toolCallId, invocation) {
440
+ const part = message.parts.find(
441
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
442
+ );
443
+ if (part != null) {
444
+ part.toolInvocation = invocation;
445
+ } else {
446
+ message.parts.push({
447
+ type: "tool-invocation",
448
+ toolInvocation: invocation
449
+ });
450
+ }
451
+ }
452
+ const data = [];
453
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
454
+ const partialToolCalls = {};
455
+ let usage = {
456
+ completionTokens: NaN,
457
+ promptTokens: NaN,
458
+ totalTokens: NaN
459
+ };
460
+ let finishReason = "unknown";
461
+ function execUpdate() {
462
+ const copiedData = [...data];
463
+ if (messageAnnotations?.length) {
464
+ message.annotations = messageAnnotations;
465
+ }
466
+ const copiedMessage = {
467
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
468
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
469
+ ...structuredClone(message),
470
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
471
+ // hashing approach by default to detect changes, but it only works for shallow
472
+ // changes. This is why we need to add a revision id to ensure that the message
473
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
474
+ // forwarded to rendering):
475
+ revisionId: crypto.randomUUID()
476
+ };
477
+ update({
478
+ message: copiedMessage,
479
+ data: copiedData,
480
+ replaceLastMessage
481
+ });
482
+ }
483
+ await processDataStream({
484
+ stream,
485
+ onTextPart(value) {
486
+ if (currentTextPart == null) {
487
+ currentTextPart = {
488
+ type: "text",
489
+ text: value
490
+ };
491
+ message.parts.push(currentTextPart);
492
+ } else {
493
+ currentTextPart.text += value;
494
+ }
495
+ message.content += value;
496
+ execUpdate();
497
+ },
498
+ onReasoningPart(value) {
499
+ if (currentReasoningTextDetail == null) {
500
+ currentReasoningTextDetail = { type: "text", text: value };
501
+ if (currentReasoningPart != null) {
502
+ currentReasoningPart.details.push(currentReasoningTextDetail);
503
+ }
504
+ } else {
505
+ currentReasoningTextDetail.text += value;
506
+ }
507
+ if (currentReasoningPart == null) {
508
+ currentReasoningPart = {
509
+ type: "reasoning",
510
+ reasoning: value,
511
+ details: [currentReasoningTextDetail]
512
+ };
513
+ message.parts.push(currentReasoningPart);
514
+ } else {
515
+ currentReasoningPart.reasoning += value;
516
+ }
517
+ message.reasoning = (message.reasoning ?? "") + value;
518
+ execUpdate();
519
+ },
520
+ onReasoningSignaturePart(value) {
521
+ if (currentReasoningTextDetail != null) {
522
+ currentReasoningTextDetail.signature = value.signature;
523
+ }
524
+ },
525
+ onRedactedReasoningPart(value) {
526
+ if (currentReasoningPart == null) {
527
+ currentReasoningPart = {
528
+ type: "reasoning",
529
+ reasoning: "",
530
+ details: []
531
+ };
532
+ message.parts.push(currentReasoningPart);
533
+ }
534
+ currentReasoningPart.details.push({
535
+ type: "redacted",
536
+ data: value.data
537
+ });
538
+ currentReasoningTextDetail = void 0;
539
+ execUpdate();
540
+ },
541
+ onFilePart(value) {
542
+ message.parts.push({
543
+ type: "file",
544
+ mimeType: value.mimeType,
545
+ data: value.data
546
+ });
547
+ execUpdate();
548
+ },
549
+ onSourcePart(value) {
550
+ message.parts.push({
551
+ type: "source",
552
+ source: value
553
+ });
554
+ execUpdate();
555
+ },
556
+ onToolCallStreamingStartPart(value) {
557
+ if (message.toolInvocations == null) {
558
+ message.toolInvocations = [];
559
+ }
560
+ partialToolCalls[value.toolCallId] = {
561
+ text: "",
562
+ step,
563
+ toolName: value.toolName,
564
+ index: message.toolInvocations.length
565
+ };
566
+ const invocation = {
567
+ state: "partial-call",
568
+ step,
569
+ toolCallId: value.toolCallId,
570
+ toolName: value.toolName,
571
+ args: void 0
572
+ };
573
+ message.toolInvocations.push(invocation);
574
+ updateToolInvocationPart(value.toolCallId, invocation);
575
+ execUpdate();
576
+ },
577
+ onToolCallDeltaPart(value) {
578
+ const partialToolCall = partialToolCalls[value.toolCallId];
579
+ partialToolCall.text += value.argsTextDelta;
580
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
581
+ const invocation = {
582
+ state: "partial-call",
583
+ step: partialToolCall.step,
584
+ toolCallId: value.toolCallId,
585
+ toolName: partialToolCall.toolName,
586
+ args: partialArgs
587
+ };
588
+ message.toolInvocations[partialToolCall.index] = invocation;
589
+ updateToolInvocationPart(value.toolCallId, invocation);
590
+ execUpdate();
591
+ },
592
+ async onToolCallPart(value) {
593
+ const invocation = {
594
+ state: "call",
595
+ step,
596
+ ...value
597
+ };
598
+ if (partialToolCalls[value.toolCallId] != null) {
599
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
600
+ } else {
601
+ if (message.toolInvocations == null) {
602
+ message.toolInvocations = [];
603
+ }
604
+ message.toolInvocations.push(invocation);
605
+ }
606
+ updateToolInvocationPart(value.toolCallId, invocation);
607
+ execUpdate();
608
+ if (onToolCall) {
609
+ const result = await onToolCall({ toolCall: value });
610
+ if (result != null) {
611
+ const invocation2 = {
612
+ state: "result",
613
+ step,
614
+ ...value,
615
+ result
616
+ };
617
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
618
+ updateToolInvocationPart(value.toolCallId, invocation2);
619
+ execUpdate();
620
+ }
621
+ }
622
+ },
623
+ onToolResultPart(value) {
624
+ const toolInvocations = message.toolInvocations;
625
+ if (toolInvocations == null) {
626
+ throw new Error("tool_result must be preceded by a tool_call");
627
+ }
628
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
629
+ if (toolInvocationIndex === -1) {
630
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
631
+ }
632
+ const invocation = {
633
+ ...toolInvocations[toolInvocationIndex],
634
+ state: "result",
635
+ ...value
636
+ };
637
+ toolInvocations[toolInvocationIndex] = invocation;
638
+ updateToolInvocationPart(value.toolCallId, invocation);
639
+ execUpdate();
640
+ },
641
+ onDataPart(value) {
642
+ data.push(...value);
643
+ execUpdate();
644
+ },
645
+ onMessageAnnotationsPart(value) {
646
+ if (messageAnnotations == null) {
647
+ messageAnnotations = [...value];
648
+ } else {
649
+ messageAnnotations.push(...value);
650
+ }
651
+ execUpdate();
652
+ },
653
+ onFinishStepPart(value) {
654
+ step += 1;
655
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
656
+ currentReasoningPart = void 0;
657
+ currentReasoningTextDetail = void 0;
658
+ },
659
+ onStartStepPart(value) {
660
+ if (!replaceLastMessage) {
661
+ message.id = value.messageId;
662
+ }
663
+ message.parts.push({ type: "step-start" });
664
+ execUpdate();
665
+ },
666
+ onFinishMessagePart(value) {
667
+ finishReason = value.finishReason;
668
+ if (value.usage != null) {
669
+ usage = value.usage;
670
+ }
671
+ },
672
+ onErrorPart(error) {
673
+ throw new Error(error);
674
+ }
675
+ });
676
+ onFinish?.({ message, finishReason, usage });
346
677
  }
347
678
  /**
348
679
  * Streams a response from the agent
@@ -354,8 +685,28 @@ var Agent = class extends BaseResource {
354
685
  ...params,
355
686
  output: params.output ? zodToJsonSchema(params.output) : void 0,
356
687
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
357
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
688
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
689
+ clientTools: processClientTools(params.clientTools)
358
690
  };
691
+ const { readable, writable } = new TransformStream();
692
+ const response = await this.processStreamResponse(processedParams, writable);
693
+ const streamResponse = new Response(readable, {
694
+ status: response.status,
695
+ statusText: response.statusText,
696
+ headers: response.headers
697
+ });
698
+ streamResponse.processDataStream = async (options = {}) => {
699
+ await processDataStream({
700
+ stream: streamResponse.body,
701
+ ...options
702
+ });
703
+ };
704
+ return streamResponse;
705
+ }
706
+ /**
707
+ * Processes the stream response and handles tool calls
708
+ */
709
+ async processStreamResponse(processedParams, writable) {
359
710
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
360
711
  method: "POST",
361
712
  body: processedParams,
@@ -364,12 +715,95 @@ var Agent = class extends BaseResource {
364
715
  if (!response.body) {
365
716
  throw new Error("No response body");
366
717
  }
367
- response.processDataStream = async (options = {}) => {
368
- await processDataStream({
369
- stream: response.body,
370
- ...options
718
+ try {
719
+ let toolCalls = [];
720
+ let messages = [];
721
+ const [streamForWritable, streamForProcessing] = response.body.tee();
722
+ streamForWritable.pipeTo(writable, {
723
+ preventClose: true
724
+ }).catch((error) => {
725
+ console.error("Error piping to writable stream:", error);
371
726
  });
372
- };
727
+ this.processChatResponse({
728
+ stream: streamForProcessing,
729
+ update: ({ message }) => {
730
+ messages.push(message);
731
+ },
732
+ onFinish: async ({ finishReason, message }) => {
733
+ if (finishReason === "tool-calls") {
734
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
735
+ if (toolCall) {
736
+ toolCalls.push(toolCall);
737
+ }
738
+ for (const toolCall2 of toolCalls) {
739
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
740
+ if (clientTool && clientTool.execute) {
741
+ const result = await clientTool.execute(
742
+ {
743
+ context: toolCall2?.args,
744
+ runId: processedParams.runId,
745
+ resourceId: processedParams.resourceId,
746
+ threadId: processedParams.threadId,
747
+ runtimeContext: processedParams.runtimeContext
748
+ },
749
+ {
750
+ messages: response.messages,
751
+ toolCallId: toolCall2?.toolCallId
752
+ }
753
+ );
754
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
755
+ const toolInvocationPart = lastMessage?.parts?.find(
756
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
757
+ );
758
+ if (toolInvocationPart) {
759
+ toolInvocationPart.toolInvocation = {
760
+ ...toolInvocationPart.toolInvocation,
761
+ state: "result",
762
+ result
763
+ };
764
+ }
765
+ const toolInvocation = lastMessage?.toolInvocations?.find(
766
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
767
+ );
768
+ if (toolInvocation) {
769
+ toolInvocation.state = "result";
770
+ toolInvocation.result = result;
771
+ }
772
+ const writer = writable.getWriter();
773
+ try {
774
+ await writer.write(
775
+ new TextEncoder().encode(
776
+ "a:" + JSON.stringify({
777
+ toolCallId: toolCall2.toolCallId,
778
+ result
779
+ }) + "\n"
780
+ )
781
+ );
782
+ } finally {
783
+ writer.releaseLock();
784
+ }
785
+ const originalMessages = processedParams.messages;
786
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
787
+ this.processStreamResponse(
788
+ {
789
+ ...processedParams,
790
+ messages: [...messageArray, ...messages, lastMessage]
791
+ },
792
+ writable
793
+ );
794
+ }
795
+ }
796
+ } else {
797
+ setTimeout(() => {
798
+ writable.close();
799
+ }, 0);
800
+ }
801
+ },
802
+ lastMessage: void 0
803
+ });
804
+ } catch (error) {
805
+ console.error("Error processing stream response:", error);
806
+ }
373
807
  return response;
374
808
  }
375
809
  /**
@@ -764,7 +1198,7 @@ var LegacyWorkflow = class extends BaseResource {
764
1198
  };
765
1199
 
766
1200
  // src/resources/tool.ts
767
- var Tool = class extends BaseResource {
1201
+ var Tool2 = class extends BaseResource {
768
1202
  constructor(options, toolId) {
769
1203
  super(options);
770
1204
  this.toolId = toolId;
@@ -869,10 +1303,10 @@ var Workflow = class extends BaseResource {
869
1303
  if (params?.toDate) {
870
1304
  searchParams.set("toDate", params.toDate.toISOString());
871
1305
  }
872
- if (params?.limit) {
1306
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
873
1307
  searchParams.set("limit", String(params.limit));
874
1308
  }
875
- if (params?.offset) {
1309
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
876
1310
  searchParams.set("offset", String(params.offset));
877
1311
  }
878
1312
  if (params?.resourceId) {
@@ -884,6 +1318,43 @@ var Workflow = class extends BaseResource {
884
1318
  return this.request(`/api/workflows/${this.workflowId}/runs`);
885
1319
  }
886
1320
  }
1321
+ /**
1322
+ * Retrieves a specific workflow run by its ID
1323
+ * @param runId - The ID of the workflow run to retrieve
1324
+ * @returns Promise containing the workflow run details
1325
+ */
1326
+ runById(runId) {
1327
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1328
+ }
1329
+ /**
1330
+ * Retrieves the execution result for a specific workflow run by its ID
1331
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1332
+ * @returns Promise containing the workflow run execution result
1333
+ */
1334
+ runExecutionResult(runId) {
1335
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1336
+ }
1337
+ /**
1338
+ * Cancels a specific workflow run by its ID
1339
+ * @param runId - The ID of the workflow run to cancel
1340
+ * @returns Promise containing a success message
1341
+ */
1342
+ cancelRun(runId) {
1343
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1344
+ method: "POST"
1345
+ });
1346
+ }
1347
+ /**
1348
+ * Sends an event to a specific workflow run by its ID
1349
+ * @param params - Object containing the runId, event and data
1350
+ * @returns Promise containing a success message
1351
+ */
1352
+ sendRunEvent(params) {
1353
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1354
+ method: "POST",
1355
+ body: { event: params.event, data: params.data }
1356
+ });
1357
+ }
887
1358
  /**
888
1359
  * Creates a new workflow run
889
1360
  * @param params - Optional object containing the optional runId
@@ -949,16 +1420,16 @@ var Workflow = class extends BaseResource {
949
1420
  });
950
1421
  }
951
1422
  /**
952
- * Starts a vNext workflow run and returns a stream
1423
+ * Starts a workflow run and returns a stream
953
1424
  * @param params - Object containing the optional runId, inputData and runtimeContext
954
- * @returns Promise containing the vNext workflow execution results
1425
+ * @returns Promise containing the workflow execution results
955
1426
  */
956
1427
  async stream(params) {
957
1428
  const searchParams = new URLSearchParams();
958
1429
  if (!!params?.runId) {
959
1430
  searchParams.set("runId", params.runId);
960
1431
  }
961
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
1432
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
962
1433
  const response = await this.request(
963
1434
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
964
1435
  {
@@ -1027,7 +1498,11 @@ var Workflow = class extends BaseResource {
1027
1498
  throw new Error("Response body is null");
1028
1499
  }
1029
1500
  for await (const record of this.streamProcessor(response.body)) {
1030
- onRecord(record);
1501
+ if (typeof record === "string") {
1502
+ onRecord(JSON.parse(record));
1503
+ } else {
1504
+ onRecord(record);
1505
+ }
1031
1506
  }
1032
1507
  }
1033
1508
  /**
@@ -1163,6 +1638,180 @@ var MCPTool = class extends BaseResource {
1163
1638
  }
1164
1639
  };
1165
1640
 
1641
+ // src/resources/vNextNetwork.ts
1642
+ var RECORD_SEPARATOR3 = "";
1643
+ var VNextNetwork = class extends BaseResource {
1644
+ constructor(options, networkId) {
1645
+ super(options);
1646
+ this.networkId = networkId;
1647
+ }
1648
+ /**
1649
+ * Retrieves details about the network
1650
+ * @returns Promise containing vNext network details
1651
+ */
1652
+ details() {
1653
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1654
+ }
1655
+ /**
1656
+ * Generates a response from the v-next network
1657
+ * @param params - Generation parameters including message
1658
+ * @returns Promise containing the generated response
1659
+ */
1660
+ generate(params) {
1661
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1662
+ method: "POST",
1663
+ body: params
1664
+ });
1665
+ }
1666
+ /**
1667
+ * Generates a response from the v-next network using multiple primitives
1668
+ * @param params - Generation parameters including message
1669
+ * @returns Promise containing the generated response
1670
+ */
1671
+ loop(params) {
1672
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1673
+ method: "POST",
1674
+ body: params
1675
+ });
1676
+ }
1677
+ async *streamProcessor(stream) {
1678
+ const reader = stream.getReader();
1679
+ let doneReading = false;
1680
+ let buffer = "";
1681
+ try {
1682
+ while (!doneReading) {
1683
+ const { done, value } = await reader.read();
1684
+ doneReading = done;
1685
+ if (done && !value) continue;
1686
+ try {
1687
+ const decoded = value ? new TextDecoder().decode(value) : "";
1688
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1689
+ buffer = chunks.pop() || "";
1690
+ for (const chunk of chunks) {
1691
+ if (chunk) {
1692
+ if (typeof chunk === "string") {
1693
+ try {
1694
+ const parsedChunk = JSON.parse(chunk);
1695
+ yield parsedChunk;
1696
+ } catch {
1697
+ }
1698
+ }
1699
+ }
1700
+ }
1701
+ } catch {
1702
+ }
1703
+ }
1704
+ if (buffer) {
1705
+ try {
1706
+ yield JSON.parse(buffer);
1707
+ } catch {
1708
+ }
1709
+ }
1710
+ } finally {
1711
+ reader.cancel().catch(() => {
1712
+ });
1713
+ }
1714
+ }
1715
+ /**
1716
+ * Streams a response from the v-next network
1717
+ * @param params - Stream parameters including message
1718
+ * @returns Promise containing the results
1719
+ */
1720
+ async stream(params, onRecord) {
1721
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1722
+ method: "POST",
1723
+ body: params,
1724
+ stream: true
1725
+ });
1726
+ if (!response.ok) {
1727
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1728
+ }
1729
+ if (!response.body) {
1730
+ throw new Error("Response body is null");
1731
+ }
1732
+ for await (const record of this.streamProcessor(response.body)) {
1733
+ if (typeof record === "string") {
1734
+ onRecord(JSON.parse(record));
1735
+ } else {
1736
+ onRecord(record);
1737
+ }
1738
+ }
1739
+ }
1740
+ /**
1741
+ * Streams a response from the v-next network loop
1742
+ * @param params - Stream parameters including message
1743
+ * @returns Promise containing the results
1744
+ */
1745
+ async loopStream(params, onRecord) {
1746
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1747
+ method: "POST",
1748
+ body: params,
1749
+ stream: true
1750
+ });
1751
+ if (!response.ok) {
1752
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1753
+ }
1754
+ if (!response.body) {
1755
+ throw new Error("Response body is null");
1756
+ }
1757
+ for await (const record of this.streamProcessor(response.body)) {
1758
+ if (typeof record === "string") {
1759
+ onRecord(JSON.parse(record));
1760
+ } else {
1761
+ onRecord(record);
1762
+ }
1763
+ }
1764
+ }
1765
+ };
1766
+
1767
+ // src/resources/network-memory-thread.ts
1768
+ var NetworkMemoryThread = class extends BaseResource {
1769
+ constructor(options, threadId, networkId) {
1770
+ super(options);
1771
+ this.threadId = threadId;
1772
+ this.networkId = networkId;
1773
+ }
1774
+ /**
1775
+ * Retrieves the memory thread details
1776
+ * @returns Promise containing thread details including title and metadata
1777
+ */
1778
+ get() {
1779
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1780
+ }
1781
+ /**
1782
+ * Updates the memory thread properties
1783
+ * @param params - Update parameters including title and metadata
1784
+ * @returns Promise containing updated thread details
1785
+ */
1786
+ update(params) {
1787
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1788
+ method: "PATCH",
1789
+ body: params
1790
+ });
1791
+ }
1792
+ /**
1793
+ * Deletes the memory thread
1794
+ * @returns Promise containing deletion result
1795
+ */
1796
+ delete() {
1797
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1798
+ method: "DELETE"
1799
+ });
1800
+ }
1801
+ /**
1802
+ * Retrieves messages associated with the thread
1803
+ * @param params - Optional parameters including limit for number of messages to retrieve
1804
+ * @returns Promise containing thread messages and UI messages
1805
+ */
1806
+ getMessages(params) {
1807
+ const query = new URLSearchParams({
1808
+ networkId: this.networkId,
1809
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1810
+ });
1811
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1812
+ }
1813
+ };
1814
+
1166
1815
  // src/client.ts
1167
1816
  var MastraClient = class extends BaseResource {
1168
1817
  constructor(options) {
@@ -1240,6 +1889,48 @@ var MastraClient = class extends BaseResource {
1240
1889
  getMemoryStatus(agentId) {
1241
1890
  return this.request(`/api/memory/status?agentId=${agentId}`);
1242
1891
  }
1892
+ /**
1893
+ * Retrieves memory threads for a resource
1894
+ * @param params - Parameters containing the resource ID
1895
+ * @returns Promise containing array of memory threads
1896
+ */
1897
+ getNetworkMemoryThreads(params) {
1898
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1899
+ }
1900
+ /**
1901
+ * Creates a new memory thread
1902
+ * @param params - Parameters for creating the memory thread
1903
+ * @returns Promise containing the created memory thread
1904
+ */
1905
+ createNetworkMemoryThread(params) {
1906
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1907
+ }
1908
+ /**
1909
+ * Gets a memory thread instance by ID
1910
+ * @param threadId - ID of the memory thread to retrieve
1911
+ * @returns MemoryThread instance
1912
+ */
1913
+ getNetworkMemoryThread(threadId, networkId) {
1914
+ return new NetworkMemoryThread(this.options, threadId, networkId);
1915
+ }
1916
+ /**
1917
+ * Saves messages to memory
1918
+ * @param params - Parameters containing messages to save
1919
+ * @returns Promise containing the saved messages
1920
+ */
1921
+ saveNetworkMessageToMemory(params) {
1922
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
1923
+ method: "POST",
1924
+ body: params
1925
+ });
1926
+ }
1927
+ /**
1928
+ * Gets the status of the memory system
1929
+ * @returns Promise containing memory system status
1930
+ */
1931
+ getNetworkMemoryStatus(networkId) {
1932
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
1933
+ }
1243
1934
  /**
1244
1935
  * Retrieves all available tools
1245
1936
  * @returns Promise containing map of tool IDs to tool details
@@ -1253,7 +1944,7 @@ var MastraClient = class extends BaseResource {
1253
1944
  * @returns Tool instance
1254
1945
  */
1255
1946
  getTool(toolId) {
1256
- return new Tool(this.options, toolId);
1947
+ return new Tool2(this.options, toolId);
1257
1948
  }
1258
1949
  /**
1259
1950
  * Retrieves all available legacy workflows
@@ -1299,7 +1990,41 @@ var MastraClient = class extends BaseResource {
1299
1990
  * @returns Promise containing array of log messages
1300
1991
  */
1301
1992
  getLogs(params) {
1302
- return this.request(`/api/logs?transportId=${params.transportId}`);
1993
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
1994
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
1995
+ const searchParams = new URLSearchParams();
1996
+ if (transportId) {
1997
+ searchParams.set("transportId", transportId);
1998
+ }
1999
+ if (fromDate) {
2000
+ searchParams.set("fromDate", fromDate.toISOString());
2001
+ }
2002
+ if (toDate) {
2003
+ searchParams.set("toDate", toDate.toISOString());
2004
+ }
2005
+ if (logLevel) {
2006
+ searchParams.set("logLevel", logLevel);
2007
+ }
2008
+ if (page) {
2009
+ searchParams.set("page", String(page));
2010
+ }
2011
+ if (perPage) {
2012
+ searchParams.set("perPage", String(perPage));
2013
+ }
2014
+ if (_filters) {
2015
+ if (Array.isArray(_filters)) {
2016
+ for (const filter of _filters) {
2017
+ searchParams.append("filters", filter);
2018
+ }
2019
+ } else {
2020
+ searchParams.set("filters", _filters);
2021
+ }
2022
+ }
2023
+ if (searchParams.size) {
2024
+ return this.request(`/api/logs?${searchParams}`);
2025
+ } else {
2026
+ return this.request(`/api/logs`);
2027
+ }
1303
2028
  }
1304
2029
  /**
1305
2030
  * Gets logs for a specific run
@@ -1307,7 +2032,44 @@ var MastraClient = class extends BaseResource {
1307
2032
  * @returns Promise containing array of log messages
1308
2033
  */
1309
2034
  getLogForRun(params) {
1310
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2035
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2036
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2037
+ const searchParams = new URLSearchParams();
2038
+ if (runId) {
2039
+ searchParams.set("runId", runId);
2040
+ }
2041
+ if (transportId) {
2042
+ searchParams.set("transportId", transportId);
2043
+ }
2044
+ if (fromDate) {
2045
+ searchParams.set("fromDate", fromDate.toISOString());
2046
+ }
2047
+ if (toDate) {
2048
+ searchParams.set("toDate", toDate.toISOString());
2049
+ }
2050
+ if (logLevel) {
2051
+ searchParams.set("logLevel", logLevel);
2052
+ }
2053
+ if (page) {
2054
+ searchParams.set("page", String(page));
2055
+ }
2056
+ if (perPage) {
2057
+ searchParams.set("perPage", String(perPage));
2058
+ }
2059
+ if (_filters) {
2060
+ if (Array.isArray(_filters)) {
2061
+ for (const filter of _filters) {
2062
+ searchParams.append("filters", filter);
2063
+ }
2064
+ } else {
2065
+ searchParams.set("filters", _filters);
2066
+ }
2067
+ }
2068
+ if (searchParams.size) {
2069
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2070
+ } else {
2071
+ return this.request(`/api/logs/${runId}`);
2072
+ }
1311
2073
  }
1312
2074
  /**
1313
2075
  * List of all log transports
@@ -1365,6 +2127,13 @@ var MastraClient = class extends BaseResource {
1365
2127
  getNetworks() {
1366
2128
  return this.request("/api/networks");
1367
2129
  }
2130
+ /**
2131
+ * Retrieves all available vNext networks
2132
+ * @returns Promise containing map of vNext network IDs to vNext network details
2133
+ */
2134
+ getVNextNetworks() {
2135
+ return this.request("/api/networks/v-next");
2136
+ }
1368
2137
  /**
1369
2138
  * Gets a network instance by ID
1370
2139
  * @param networkId - ID of the network to retrieve
@@ -1373,6 +2142,14 @@ var MastraClient = class extends BaseResource {
1373
2142
  getNetwork(networkId) {
1374
2143
  return new Network(this.options, networkId);
1375
2144
  }
2145
+ /**
2146
+ * Gets a vNext network instance by ID
2147
+ * @param networkId - ID of the vNext network to retrieve
2148
+ * @returns vNext Network instance
2149
+ */
2150
+ getVNextNetwork(networkId) {
2151
+ return new VNextNetwork(this.options, networkId);
2152
+ }
1376
2153
  /**
1377
2154
  * Retrieves a list of available MCP servers.
1378
2155
  * @param params - Optional parameters for pagination (limit, offset).