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

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,6 +246,7 @@ 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
@@ -264,8 +293,6 @@ function parseClientRuntimeContext(runtimeContext) {
264
293
  }
265
294
  return void 0;
266
295
  }
267
-
268
- // src/resources/agent.ts
269
296
  var AgentVoice = class extends BaseResource {
270
297
  constructor(options, agentId) {
271
298
  super(options);
@@ -312,6 +339,13 @@ var AgentVoice = class extends BaseResource {
312
339
  getSpeakers() {
313
340
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
314
341
  }
342
+ /**
343
+ * Get the listener configuration for the agent's voice provider
344
+ * @returns Promise containing a check if the agent has listening capabilities
345
+ */
346
+ getListener() {
347
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
348
+ }
315
349
  };
316
350
  var Agent = class extends BaseResource {
317
351
  constructor(options, agentId) {
@@ -327,22 +361,318 @@ var Agent = class extends BaseResource {
327
361
  details() {
328
362
  return this.request(`/api/agents/${this.agentId}`);
329
363
  }
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) {
364
+ async generate(params) {
336
365
  const processedParams = {
337
366
  ...params,
338
367
  output: params.output ? zodToJsonSchema(params.output) : void 0,
339
368
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
340
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
369
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
370
+ clientTools: processClientTools(params.clientTools)
341
371
  };
342
- return this.request(`/api/agents/${this.agentId}/generate`, {
372
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
373
+ const response = await this.request(`/api/agents/${this.agentId}/generate`, {
343
374
  method: "POST",
344
375
  body: processedParams
345
376
  });
377
+ if (response.finishReason === "tool-calls") {
378
+ for (const toolCall of response.toolCalls) {
379
+ const clientTool = params.clientTools?.[toolCall.toolName];
380
+ if (clientTool && clientTool.execute) {
381
+ const result = await clientTool.execute(
382
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
383
+ {
384
+ messages: response.messages,
385
+ toolCallId: toolCall?.toolCallId
386
+ }
387
+ );
388
+ const updatedMessages = [
389
+ {
390
+ role: "user",
391
+ content: params.messages
392
+ },
393
+ ...response.response.messages,
394
+ {
395
+ role: "tool",
396
+ content: [
397
+ {
398
+ type: "tool-result",
399
+ toolCallId: toolCall.toolCallId,
400
+ toolName: toolCall.toolName,
401
+ result
402
+ }
403
+ ]
404
+ }
405
+ ];
406
+ return this.generate({
407
+ ...params,
408
+ messages: updatedMessages
409
+ });
410
+ }
411
+ }
412
+ }
413
+ return response;
414
+ }
415
+ async processChatResponse({
416
+ stream,
417
+ update,
418
+ onToolCall,
419
+ onFinish,
420
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
421
+ lastMessage
422
+ }) {
423
+ const replaceLastMessage = lastMessage?.role === "assistant";
424
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
425
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
426
+ return Math.max(max, toolInvocation.step ?? 0);
427
+ }, 0) ?? 0) : 0;
428
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
429
+ id: crypto.randomUUID(),
430
+ createdAt: getCurrentDate(),
431
+ role: "assistant",
432
+ content: "",
433
+ parts: []
434
+ };
435
+ let currentTextPart = void 0;
436
+ let currentReasoningPart = void 0;
437
+ let currentReasoningTextDetail = void 0;
438
+ function updateToolInvocationPart(toolCallId, invocation) {
439
+ const part = message.parts.find(
440
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
441
+ );
442
+ if (part != null) {
443
+ part.toolInvocation = invocation;
444
+ } else {
445
+ message.parts.push({
446
+ type: "tool-invocation",
447
+ toolInvocation: invocation
448
+ });
449
+ }
450
+ }
451
+ const data = [];
452
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
453
+ const partialToolCalls = {};
454
+ let usage = {
455
+ completionTokens: NaN,
456
+ promptTokens: NaN,
457
+ totalTokens: NaN
458
+ };
459
+ let finishReason = "unknown";
460
+ function execUpdate() {
461
+ const copiedData = [...data];
462
+ if (messageAnnotations?.length) {
463
+ message.annotations = messageAnnotations;
464
+ }
465
+ const copiedMessage = {
466
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
467
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
468
+ ...structuredClone(message),
469
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
470
+ // hashing approach by default to detect changes, but it only works for shallow
471
+ // changes. This is why we need to add a revision id to ensure that the message
472
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
473
+ // forwarded to rendering):
474
+ revisionId: crypto.randomUUID()
475
+ };
476
+ update({
477
+ message: copiedMessage,
478
+ data: copiedData,
479
+ replaceLastMessage
480
+ });
481
+ }
482
+ await processDataStream({
483
+ stream,
484
+ onTextPart(value) {
485
+ if (currentTextPart == null) {
486
+ currentTextPart = {
487
+ type: "text",
488
+ text: value
489
+ };
490
+ message.parts.push(currentTextPart);
491
+ } else {
492
+ currentTextPart.text += value;
493
+ }
494
+ message.content += value;
495
+ execUpdate();
496
+ },
497
+ onReasoningPart(value) {
498
+ if (currentReasoningTextDetail == null) {
499
+ currentReasoningTextDetail = { type: "text", text: value };
500
+ if (currentReasoningPart != null) {
501
+ currentReasoningPart.details.push(currentReasoningTextDetail);
502
+ }
503
+ } else {
504
+ currentReasoningTextDetail.text += value;
505
+ }
506
+ if (currentReasoningPart == null) {
507
+ currentReasoningPart = {
508
+ type: "reasoning",
509
+ reasoning: value,
510
+ details: [currentReasoningTextDetail]
511
+ };
512
+ message.parts.push(currentReasoningPart);
513
+ } else {
514
+ currentReasoningPart.reasoning += value;
515
+ }
516
+ message.reasoning = (message.reasoning ?? "") + value;
517
+ execUpdate();
518
+ },
519
+ onReasoningSignaturePart(value) {
520
+ if (currentReasoningTextDetail != null) {
521
+ currentReasoningTextDetail.signature = value.signature;
522
+ }
523
+ },
524
+ onRedactedReasoningPart(value) {
525
+ if (currentReasoningPart == null) {
526
+ currentReasoningPart = {
527
+ type: "reasoning",
528
+ reasoning: "",
529
+ details: []
530
+ };
531
+ message.parts.push(currentReasoningPart);
532
+ }
533
+ currentReasoningPart.details.push({
534
+ type: "redacted",
535
+ data: value.data
536
+ });
537
+ currentReasoningTextDetail = void 0;
538
+ execUpdate();
539
+ },
540
+ onFilePart(value) {
541
+ message.parts.push({
542
+ type: "file",
543
+ mimeType: value.mimeType,
544
+ data: value.data
545
+ });
546
+ execUpdate();
547
+ },
548
+ onSourcePart(value) {
549
+ message.parts.push({
550
+ type: "source",
551
+ source: value
552
+ });
553
+ execUpdate();
554
+ },
555
+ onToolCallStreamingStartPart(value) {
556
+ if (message.toolInvocations == null) {
557
+ message.toolInvocations = [];
558
+ }
559
+ partialToolCalls[value.toolCallId] = {
560
+ text: "",
561
+ step,
562
+ toolName: value.toolName,
563
+ index: message.toolInvocations.length
564
+ };
565
+ const invocation = {
566
+ state: "partial-call",
567
+ step,
568
+ toolCallId: value.toolCallId,
569
+ toolName: value.toolName,
570
+ args: void 0
571
+ };
572
+ message.toolInvocations.push(invocation);
573
+ updateToolInvocationPart(value.toolCallId, invocation);
574
+ execUpdate();
575
+ },
576
+ onToolCallDeltaPart(value) {
577
+ const partialToolCall = partialToolCalls[value.toolCallId];
578
+ partialToolCall.text += value.argsTextDelta;
579
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
580
+ const invocation = {
581
+ state: "partial-call",
582
+ step: partialToolCall.step,
583
+ toolCallId: value.toolCallId,
584
+ toolName: partialToolCall.toolName,
585
+ args: partialArgs
586
+ };
587
+ message.toolInvocations[partialToolCall.index] = invocation;
588
+ updateToolInvocationPart(value.toolCallId, invocation);
589
+ execUpdate();
590
+ },
591
+ async onToolCallPart(value) {
592
+ const invocation = {
593
+ state: "call",
594
+ step,
595
+ ...value
596
+ };
597
+ if (partialToolCalls[value.toolCallId] != null) {
598
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
599
+ } else {
600
+ if (message.toolInvocations == null) {
601
+ message.toolInvocations = [];
602
+ }
603
+ message.toolInvocations.push(invocation);
604
+ }
605
+ updateToolInvocationPart(value.toolCallId, invocation);
606
+ execUpdate();
607
+ if (onToolCall) {
608
+ const result = await onToolCall({ toolCall: value });
609
+ if (result != null) {
610
+ const invocation2 = {
611
+ state: "result",
612
+ step,
613
+ ...value,
614
+ result
615
+ };
616
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
617
+ updateToolInvocationPart(value.toolCallId, invocation2);
618
+ execUpdate();
619
+ }
620
+ }
621
+ },
622
+ onToolResultPart(value) {
623
+ const toolInvocations = message.toolInvocations;
624
+ if (toolInvocations == null) {
625
+ throw new Error("tool_result must be preceded by a tool_call");
626
+ }
627
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
628
+ if (toolInvocationIndex === -1) {
629
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
630
+ }
631
+ const invocation = {
632
+ ...toolInvocations[toolInvocationIndex],
633
+ state: "result",
634
+ ...value
635
+ };
636
+ toolInvocations[toolInvocationIndex] = invocation;
637
+ updateToolInvocationPart(value.toolCallId, invocation);
638
+ execUpdate();
639
+ },
640
+ onDataPart(value) {
641
+ data.push(...value);
642
+ execUpdate();
643
+ },
644
+ onMessageAnnotationsPart(value) {
645
+ if (messageAnnotations == null) {
646
+ messageAnnotations = [...value];
647
+ } else {
648
+ messageAnnotations.push(...value);
649
+ }
650
+ execUpdate();
651
+ },
652
+ onFinishStepPart(value) {
653
+ step += 1;
654
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
655
+ currentReasoningPart = void 0;
656
+ currentReasoningTextDetail = void 0;
657
+ },
658
+ onStartStepPart(value) {
659
+ if (!replaceLastMessage) {
660
+ message.id = value.messageId;
661
+ }
662
+ message.parts.push({ type: "step-start" });
663
+ execUpdate();
664
+ },
665
+ onFinishMessagePart(value) {
666
+ finishReason = value.finishReason;
667
+ if (value.usage != null) {
668
+ usage = value.usage;
669
+ }
670
+ },
671
+ onErrorPart(error) {
672
+ throw new Error(error);
673
+ }
674
+ });
675
+ onFinish?.({ message, finishReason, usage });
346
676
  }
347
677
  /**
348
678
  * Streams a response from the agent
@@ -354,8 +684,28 @@ var Agent = class extends BaseResource {
354
684
  ...params,
355
685
  output: params.output ? zodToJsonSchema(params.output) : void 0,
356
686
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
357
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
687
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
688
+ clientTools: processClientTools(params.clientTools)
689
+ };
690
+ const { readable, writable } = new TransformStream();
691
+ const response = await this.processStreamResponse(processedParams, writable);
692
+ const streamResponse = new Response(readable, {
693
+ status: response.status,
694
+ statusText: response.statusText,
695
+ headers: response.headers
696
+ });
697
+ streamResponse.processDataStream = async (options = {}) => {
698
+ await processDataStream({
699
+ stream: streamResponse.body,
700
+ ...options
701
+ });
358
702
  };
703
+ return streamResponse;
704
+ }
705
+ /**
706
+ * Processes the stream response and handles tool calls
707
+ */
708
+ async processStreamResponse(processedParams, writable) {
359
709
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
360
710
  method: "POST",
361
711
  body: processedParams,
@@ -364,12 +714,82 @@ var Agent = class extends BaseResource {
364
714
  if (!response.body) {
365
715
  throw new Error("No response body");
366
716
  }
367
- response.processDataStream = async (options = {}) => {
368
- await processDataStream({
369
- stream: response.body,
370
- ...options
717
+ try {
718
+ let toolCalls = [];
719
+ let messages = [];
720
+ const [streamForWritable, streamForProcessing] = response.body.tee();
721
+ streamForWritable.pipeTo(writable, {
722
+ preventClose: true
723
+ }).catch((error) => {
724
+ console.error("Error piping to writable stream:", error);
371
725
  });
372
- };
726
+ this.processChatResponse({
727
+ stream: streamForProcessing,
728
+ update: ({ message }) => {
729
+ messages.push(message);
730
+ },
731
+ onFinish: async ({ finishReason, message }) => {
732
+ if (finishReason === "tool-calls") {
733
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
734
+ if (toolCall) {
735
+ toolCalls.push(toolCall);
736
+ }
737
+ for (const toolCall2 of toolCalls) {
738
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
739
+ if (clientTool && clientTool.execute) {
740
+ const result = await clientTool.execute(
741
+ {
742
+ context: toolCall2?.args,
743
+ runId: processedParams.runId,
744
+ resourceId: processedParams.resourceId,
745
+ threadId: processedParams.threadId,
746
+ runtimeContext: processedParams.runtimeContext
747
+ },
748
+ {
749
+ messages: response.messages,
750
+ toolCallId: toolCall2?.toolCallId
751
+ }
752
+ );
753
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
754
+ const toolInvocationPart = lastMessage?.parts?.find(
755
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
756
+ );
757
+ if (toolInvocationPart) {
758
+ toolInvocationPart.toolInvocation = {
759
+ ...toolInvocationPart.toolInvocation,
760
+ state: "result",
761
+ result
762
+ };
763
+ }
764
+ const toolInvocation = lastMessage?.toolInvocations?.find(
765
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
766
+ );
767
+ if (toolInvocation) {
768
+ toolInvocation.state = "result";
769
+ toolInvocation.result = result;
770
+ }
771
+ const originalMessages = processedParams.messages;
772
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
773
+ this.processStreamResponse(
774
+ {
775
+ ...processedParams,
776
+ messages: [...messageArray, ...messages, lastMessage]
777
+ },
778
+ writable
779
+ );
780
+ }
781
+ }
782
+ } else {
783
+ setTimeout(() => {
784
+ writable.close();
785
+ }, 0);
786
+ }
787
+ },
788
+ lastMessage: void 0
789
+ });
790
+ } catch (error) {
791
+ console.error("Error processing stream response:", error);
792
+ }
373
793
  return response;
374
794
  }
375
795
  /**
@@ -764,7 +1184,7 @@ var LegacyWorkflow = class extends BaseResource {
764
1184
  };
765
1185
 
766
1186
  // src/resources/tool.ts
767
- var Tool = class extends BaseResource {
1187
+ var Tool2 = class extends BaseResource {
768
1188
  constructor(options, toolId) {
769
1189
  super(options);
770
1190
  this.toolId = toolId;
@@ -884,6 +1304,22 @@ var Workflow = class extends BaseResource {
884
1304
  return this.request(`/api/workflows/${this.workflowId}/runs`);
885
1305
  }
886
1306
  }
1307
+ /**
1308
+ * Retrieves a specific workflow run by its ID
1309
+ * @param runId - The ID of the workflow run to retrieve
1310
+ * @returns Promise containing the workflow run details
1311
+ */
1312
+ runById(runId) {
1313
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1314
+ }
1315
+ /**
1316
+ * Retrieves the execution result for a specific workflow run by its ID
1317
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1318
+ * @returns Promise containing the workflow run execution result
1319
+ */
1320
+ runExecutionResult(runId) {
1321
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1322
+ }
887
1323
  /**
888
1324
  * Creates a new workflow run
889
1325
  * @param params - Optional object containing the optional runId
@@ -949,16 +1385,16 @@ var Workflow = class extends BaseResource {
949
1385
  });
950
1386
  }
951
1387
  /**
952
- * Starts a vNext workflow run and returns a stream
1388
+ * Starts a workflow run and returns a stream
953
1389
  * @param params - Object containing the optional runId, inputData and runtimeContext
954
- * @returns Promise containing the vNext workflow execution results
1390
+ * @returns Promise containing the workflow execution results
955
1391
  */
956
1392
  async stream(params) {
957
1393
  const searchParams = new URLSearchParams();
958
1394
  if (!!params?.runId) {
959
1395
  searchParams.set("runId", params.runId);
960
1396
  }
961
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
1397
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
962
1398
  const response = await this.request(
963
1399
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
964
1400
  {
@@ -1027,7 +1463,11 @@ var Workflow = class extends BaseResource {
1027
1463
  throw new Error("Response body is null");
1028
1464
  }
1029
1465
  for await (const record of this.streamProcessor(response.body)) {
1030
- onRecord(record);
1466
+ if (typeof record === "string") {
1467
+ onRecord(JSON.parse(record));
1468
+ } else {
1469
+ onRecord(record);
1470
+ }
1031
1471
  }
1032
1472
  }
1033
1473
  /**
@@ -1163,6 +1603,180 @@ var MCPTool = class extends BaseResource {
1163
1603
  }
1164
1604
  };
1165
1605
 
1606
+ // src/resources/vNextNetwork.ts
1607
+ var RECORD_SEPARATOR3 = "";
1608
+ var VNextNetwork = class extends BaseResource {
1609
+ constructor(options, networkId) {
1610
+ super(options);
1611
+ this.networkId = networkId;
1612
+ }
1613
+ /**
1614
+ * Retrieves details about the network
1615
+ * @returns Promise containing vNext network details
1616
+ */
1617
+ details() {
1618
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1619
+ }
1620
+ /**
1621
+ * Generates a response from the v-next network
1622
+ * @param params - Generation parameters including message
1623
+ * @returns Promise containing the generated response
1624
+ */
1625
+ generate(params) {
1626
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1627
+ method: "POST",
1628
+ body: params
1629
+ });
1630
+ }
1631
+ /**
1632
+ * Generates a response from the v-next network using multiple primitives
1633
+ * @param params - Generation parameters including message
1634
+ * @returns Promise containing the generated response
1635
+ */
1636
+ loop(params) {
1637
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1638
+ method: "POST",
1639
+ body: params
1640
+ });
1641
+ }
1642
+ async *streamProcessor(stream) {
1643
+ const reader = stream.getReader();
1644
+ let doneReading = false;
1645
+ let buffer = "";
1646
+ try {
1647
+ while (!doneReading) {
1648
+ const { done, value } = await reader.read();
1649
+ doneReading = done;
1650
+ if (done && !value) continue;
1651
+ try {
1652
+ const decoded = value ? new TextDecoder().decode(value) : "";
1653
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1654
+ buffer = chunks.pop() || "";
1655
+ for (const chunk of chunks) {
1656
+ if (chunk) {
1657
+ if (typeof chunk === "string") {
1658
+ try {
1659
+ const parsedChunk = JSON.parse(chunk);
1660
+ yield parsedChunk;
1661
+ } catch {
1662
+ }
1663
+ }
1664
+ }
1665
+ }
1666
+ } catch {
1667
+ }
1668
+ }
1669
+ if (buffer) {
1670
+ try {
1671
+ yield JSON.parse(buffer);
1672
+ } catch {
1673
+ }
1674
+ }
1675
+ } finally {
1676
+ reader.cancel().catch(() => {
1677
+ });
1678
+ }
1679
+ }
1680
+ /**
1681
+ * Streams a response from the v-next network
1682
+ * @param params - Stream parameters including message
1683
+ * @returns Promise containing the results
1684
+ */
1685
+ async stream(params, onRecord) {
1686
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1687
+ method: "POST",
1688
+ body: params,
1689
+ stream: true
1690
+ });
1691
+ if (!response.ok) {
1692
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1693
+ }
1694
+ if (!response.body) {
1695
+ throw new Error("Response body is null");
1696
+ }
1697
+ for await (const record of this.streamProcessor(response.body)) {
1698
+ if (typeof record === "string") {
1699
+ onRecord(JSON.parse(record));
1700
+ } else {
1701
+ onRecord(record);
1702
+ }
1703
+ }
1704
+ }
1705
+ /**
1706
+ * Streams a response from the v-next network loop
1707
+ * @param params - Stream parameters including message
1708
+ * @returns Promise containing the results
1709
+ */
1710
+ async loopStream(params, onRecord) {
1711
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1712
+ method: "POST",
1713
+ body: params,
1714
+ stream: true
1715
+ });
1716
+ if (!response.ok) {
1717
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1718
+ }
1719
+ if (!response.body) {
1720
+ throw new Error("Response body is null");
1721
+ }
1722
+ for await (const record of this.streamProcessor(response.body)) {
1723
+ if (typeof record === "string") {
1724
+ onRecord(JSON.parse(record));
1725
+ } else {
1726
+ onRecord(record);
1727
+ }
1728
+ }
1729
+ }
1730
+ };
1731
+
1732
+ // src/resources/network-memory-thread.ts
1733
+ var NetworkMemoryThread = class extends BaseResource {
1734
+ constructor(options, threadId, networkId) {
1735
+ super(options);
1736
+ this.threadId = threadId;
1737
+ this.networkId = networkId;
1738
+ }
1739
+ /**
1740
+ * Retrieves the memory thread details
1741
+ * @returns Promise containing thread details including title and metadata
1742
+ */
1743
+ get() {
1744
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1745
+ }
1746
+ /**
1747
+ * Updates the memory thread properties
1748
+ * @param params - Update parameters including title and metadata
1749
+ * @returns Promise containing updated thread details
1750
+ */
1751
+ update(params) {
1752
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1753
+ method: "PATCH",
1754
+ body: params
1755
+ });
1756
+ }
1757
+ /**
1758
+ * Deletes the memory thread
1759
+ * @returns Promise containing deletion result
1760
+ */
1761
+ delete() {
1762
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1763
+ method: "DELETE"
1764
+ });
1765
+ }
1766
+ /**
1767
+ * Retrieves messages associated with the thread
1768
+ * @param params - Optional parameters including limit for number of messages to retrieve
1769
+ * @returns Promise containing thread messages and UI messages
1770
+ */
1771
+ getMessages(params) {
1772
+ const query = new URLSearchParams({
1773
+ networkId: this.networkId,
1774
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1775
+ });
1776
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1777
+ }
1778
+ };
1779
+
1166
1780
  // src/client.ts
1167
1781
  var MastraClient = class extends BaseResource {
1168
1782
  constructor(options) {
@@ -1240,6 +1854,48 @@ var MastraClient = class extends BaseResource {
1240
1854
  getMemoryStatus(agentId) {
1241
1855
  return this.request(`/api/memory/status?agentId=${agentId}`);
1242
1856
  }
1857
+ /**
1858
+ * Retrieves memory threads for a resource
1859
+ * @param params - Parameters containing the resource ID
1860
+ * @returns Promise containing array of memory threads
1861
+ */
1862
+ getNetworkMemoryThreads(params) {
1863
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1864
+ }
1865
+ /**
1866
+ * Creates a new memory thread
1867
+ * @param params - Parameters for creating the memory thread
1868
+ * @returns Promise containing the created memory thread
1869
+ */
1870
+ createNetworkMemoryThread(params) {
1871
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1872
+ }
1873
+ /**
1874
+ * Gets a memory thread instance by ID
1875
+ * @param threadId - ID of the memory thread to retrieve
1876
+ * @returns MemoryThread instance
1877
+ */
1878
+ getNetworkMemoryThread(threadId, networkId) {
1879
+ return new NetworkMemoryThread(this.options, threadId, networkId);
1880
+ }
1881
+ /**
1882
+ * Saves messages to memory
1883
+ * @param params - Parameters containing messages to save
1884
+ * @returns Promise containing the saved messages
1885
+ */
1886
+ saveNetworkMessageToMemory(params) {
1887
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
1888
+ method: "POST",
1889
+ body: params
1890
+ });
1891
+ }
1892
+ /**
1893
+ * Gets the status of the memory system
1894
+ * @returns Promise containing memory system status
1895
+ */
1896
+ getNetworkMemoryStatus(networkId) {
1897
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
1898
+ }
1243
1899
  /**
1244
1900
  * Retrieves all available tools
1245
1901
  * @returns Promise containing map of tool IDs to tool details
@@ -1253,7 +1909,7 @@ var MastraClient = class extends BaseResource {
1253
1909
  * @returns Tool instance
1254
1910
  */
1255
1911
  getTool(toolId) {
1256
- return new Tool(this.options, toolId);
1912
+ return new Tool2(this.options, toolId);
1257
1913
  }
1258
1914
  /**
1259
1915
  * Retrieves all available legacy workflows
@@ -1299,7 +1955,41 @@ var MastraClient = class extends BaseResource {
1299
1955
  * @returns Promise containing array of log messages
1300
1956
  */
1301
1957
  getLogs(params) {
1302
- return this.request(`/api/logs?transportId=${params.transportId}`);
1958
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
1959
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
1960
+ const searchParams = new URLSearchParams();
1961
+ if (transportId) {
1962
+ searchParams.set("transportId", transportId);
1963
+ }
1964
+ if (fromDate) {
1965
+ searchParams.set("fromDate", fromDate.toISOString());
1966
+ }
1967
+ if (toDate) {
1968
+ searchParams.set("toDate", toDate.toISOString());
1969
+ }
1970
+ if (logLevel) {
1971
+ searchParams.set("logLevel", logLevel);
1972
+ }
1973
+ if (page) {
1974
+ searchParams.set("page", String(page));
1975
+ }
1976
+ if (perPage) {
1977
+ searchParams.set("perPage", String(perPage));
1978
+ }
1979
+ if (_filters) {
1980
+ if (Array.isArray(_filters)) {
1981
+ for (const filter of _filters) {
1982
+ searchParams.append("filters", filter);
1983
+ }
1984
+ } else {
1985
+ searchParams.set("filters", _filters);
1986
+ }
1987
+ }
1988
+ if (searchParams.size) {
1989
+ return this.request(`/api/logs?${searchParams}`);
1990
+ } else {
1991
+ return this.request(`/api/logs`);
1992
+ }
1303
1993
  }
1304
1994
  /**
1305
1995
  * Gets logs for a specific run
@@ -1307,7 +1997,44 @@ var MastraClient = class extends BaseResource {
1307
1997
  * @returns Promise containing array of log messages
1308
1998
  */
1309
1999
  getLogForRun(params) {
1310
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2000
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2001
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2002
+ const searchParams = new URLSearchParams();
2003
+ if (runId) {
2004
+ searchParams.set("runId", runId);
2005
+ }
2006
+ if (transportId) {
2007
+ searchParams.set("transportId", transportId);
2008
+ }
2009
+ if (fromDate) {
2010
+ searchParams.set("fromDate", fromDate.toISOString());
2011
+ }
2012
+ if (toDate) {
2013
+ searchParams.set("toDate", toDate.toISOString());
2014
+ }
2015
+ if (logLevel) {
2016
+ searchParams.set("logLevel", logLevel);
2017
+ }
2018
+ if (page) {
2019
+ searchParams.set("page", String(page));
2020
+ }
2021
+ if (perPage) {
2022
+ searchParams.set("perPage", String(perPage));
2023
+ }
2024
+ if (_filters) {
2025
+ if (Array.isArray(_filters)) {
2026
+ for (const filter of _filters) {
2027
+ searchParams.append("filters", filter);
2028
+ }
2029
+ } else {
2030
+ searchParams.set("filters", _filters);
2031
+ }
2032
+ }
2033
+ if (searchParams.size) {
2034
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2035
+ } else {
2036
+ return this.request(`/api/logs/${runId}`);
2037
+ }
1311
2038
  }
1312
2039
  /**
1313
2040
  * List of all log transports
@@ -1365,6 +2092,13 @@ var MastraClient = class extends BaseResource {
1365
2092
  getNetworks() {
1366
2093
  return this.request("/api/networks");
1367
2094
  }
2095
+ /**
2096
+ * Retrieves all available vNext networks
2097
+ * @returns Promise containing map of vNext network IDs to vNext network details
2098
+ */
2099
+ getVNextNetworks() {
2100
+ return this.request("/api/networks/v-next");
2101
+ }
1368
2102
  /**
1369
2103
  * Gets a network instance by ID
1370
2104
  * @param networkId - ID of the network to retrieve
@@ -1373,6 +2107,14 @@ var MastraClient = class extends BaseResource {
1373
2107
  getNetwork(networkId) {
1374
2108
  return new Network(this.options, networkId);
1375
2109
  }
2110
+ /**
2111
+ * Gets a vNext network instance by ID
2112
+ * @param networkId - ID of the vNext network to retrieve
2113
+ * @returns vNext Network instance
2114
+ */
2115
+ getVNextNetwork(networkId) {
2116
+ return new VNextNetwork(this.options, networkId);
2117
+ }
1376
2118
  /**
1377
2119
  * Retrieves a list of available MCP servers.
1378
2120
  * @param params - Optional parameters for pagination (limit, offset).