@mastra/client-js 0.0.0-cloud-transporter-20250513033346 → 0.0.0-cloudflare-deployer-dont-install-deps-20250714111754

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,9 @@ 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');
10
+ var runtimeContext = require('@mastra/core/runtime-context');
8
11
 
9
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
13
 
@@ -201,6 +204,33 @@ function zodToJsonSchema(zodSchema) {
201
204
  }
202
205
  return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
203
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
+ }
204
234
 
205
235
  // src/resources/base.ts
206
236
  var BaseResource = class {
@@ -220,14 +250,16 @@ var BaseResource = class {
220
250
  let delay = backoffMs;
221
251
  for (let attempt = 0; attempt <= retries; attempt++) {
222
252
  try {
223
- const response = await fetch(`${baseUrl}${path}`, {
253
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
224
254
  ...options,
225
255
  headers: {
256
+ ...options.method === "POST" || options.method === "PUT" ? { "content-type": "application/json" } : {},
226
257
  ...headers,
227
258
  ...options.headers
228
259
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
229
260
  // 'x-mastra-client-type': 'js',
230
261
  },
262
+ signal: this.options.abortSignal,
231
263
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
232
264
  });
233
265
  if (!response.ok) {
@@ -260,8 +292,15 @@ var BaseResource = class {
260
292
  throw lastError || new Error("Request failed");
261
293
  }
262
294
  };
263
-
264
- // src/resources/agent.ts
295
+ function parseClientRuntimeContext(runtimeContext$1) {
296
+ if (runtimeContext$1) {
297
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
298
+ return Object.fromEntries(runtimeContext$1.entries());
299
+ }
300
+ return runtimeContext$1;
301
+ }
302
+ return void 0;
303
+ }
265
304
  var AgentVoice = class extends BaseResource {
266
305
  constructor(options, agentId) {
267
306
  super(options);
@@ -308,6 +347,13 @@ var AgentVoice = class extends BaseResource {
308
347
  getSpeakers() {
309
348
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
310
349
  }
350
+ /**
351
+ * Get the listener configuration for the agent's voice provider
352
+ * @returns Promise containing a check if the agent has listening capabilities
353
+ */
354
+ getListener() {
355
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
356
+ }
311
357
  };
312
358
  var Agent = class extends BaseResource {
313
359
  constructor(options, agentId) {
@@ -323,35 +369,341 @@ var Agent = class extends BaseResource {
323
369
  details() {
324
370
  return this.request(`/api/agents/${this.agentId}`);
325
371
  }
326
- /**
327
- * Generates a response from the agent
328
- * @param params - Generation parameters including prompt
329
- * @returns Promise containing the generated response
330
- */
331
- generate(params) {
372
+ async generate(params) {
332
373
  const processedParams = {
333
374
  ...params,
334
- output: zodToJsonSchema(params.output),
335
- experimental_output: zodToJsonSchema(params.experimental_output),
336
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
375
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
376
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
377
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
378
+ clientTools: processClientTools(params.clientTools)
337
379
  };
338
- 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`, {
339
382
  method: "POST",
340
383
  body: processedParams
341
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
+ }
342
702
  }
343
703
  /**
344
- * Streams a response from the agent
345
- * @param params - Stream parameters including prompt
346
- * @returns Promise containing the enhanced Response object with processDataStream method
704
+ * Processes the stream response and handles tool calls
347
705
  */
348
- async stream(params) {
349
- const processedParams = {
350
- ...params,
351
- output: zodToJsonSchema(params.output),
352
- experimental_output: zodToJsonSchema(params.experimental_output),
353
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
354
- };
706
+ async processStreamResponse(processedParams, writable) {
355
707
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
356
708
  method: "POST",
357
709
  body: processedParams,
@@ -360,13 +712,135 @@ var Agent = class extends BaseResource {
360
712
  if (!response.body) {
361
713
  throw new Error("No response body");
362
714
  }
363
- response.processDataStream = async (options = {}) => {
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;
809
+ }
810
+ /**
811
+ * Streams a response from the agent
812
+ * @param params - Stream parameters including prompt
813
+ * @returns Promise containing the enhanced Response object with processDataStream and processTextStream methods
814
+ */
815
+ async stream(params) {
816
+ const processedParams = {
817
+ ...params,
818
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
819
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
820
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
821
+ clientTools: processClientTools(params.clientTools)
822
+ };
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
829
+ });
830
+ streamResponse.processDataStream = async (options = {}) => {
364
831
  await uiUtils.processDataStream({
365
- stream: response.body,
832
+ stream: streamResponse.body,
366
833
  ...options
367
834
  });
368
835
  };
369
- 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;
370
844
  }
371
845
  /**
372
846
  * Gets details about a specific tool available to the agent
@@ -578,24 +1052,24 @@ var Vector = class extends BaseResource {
578
1052
  }
579
1053
  };
580
1054
 
581
- // src/resources/workflow.ts
1055
+ // src/resources/legacy-workflow.ts
582
1056
  var RECORD_SEPARATOR = "";
583
- var Workflow = class extends BaseResource {
1057
+ var LegacyWorkflow = class extends BaseResource {
584
1058
  constructor(options, workflowId) {
585
1059
  super(options);
586
1060
  this.workflowId = workflowId;
587
1061
  }
588
1062
  /**
589
- * Retrieves details about the workflow
590
- * @returns Promise containing workflow details including steps and graphs
1063
+ * Retrieves details about the legacy workflow
1064
+ * @returns Promise containing legacy workflow details including steps and graphs
591
1065
  */
592
1066
  details() {
593
- return this.request(`/api/workflows/${this.workflowId}`);
1067
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
594
1068
  }
595
1069
  /**
596
- * Retrieves all runs for a workflow
1070
+ * Retrieves all runs for a legacy workflow
597
1071
  * @param params - Parameters for filtering runs
598
- * @returns Promise containing workflow runs array
1072
+ * @returns Promise containing legacy workflow runs array
599
1073
  */
600
1074
  runs(params) {
601
1075
  const searchParams = new URLSearchParams();
@@ -615,25 +1089,13 @@ var Workflow = class extends BaseResource {
615
1089
  searchParams.set("resourceId", params.resourceId);
616
1090
  }
617
1091
  if (searchParams.size) {
618
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1092
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
619
1093
  } else {
620
- return this.request(`/api/workflows/${this.workflowId}/runs`);
1094
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
621
1095
  }
622
1096
  }
623
1097
  /**
624
- * @deprecated Use `startAsync` instead
625
- * Executes the workflow with the provided parameters
626
- * @param params - Parameters required for workflow execution
627
- * @returns Promise containing the workflow execution results
628
- */
629
- execute(params) {
630
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
631
- method: "POST",
632
- body: params
633
- });
634
- }
635
- /**
636
- * Creates a new workflow run
1098
+ * Creates a new legacy workflow run
637
1099
  * @returns Promise containing the generated run ID
638
1100
  */
639
1101
  createRun(params) {
@@ -641,34 +1103,34 @@ var Workflow = class extends BaseResource {
641
1103
  if (!!params?.runId) {
642
1104
  searchParams.set("runId", params.runId);
643
1105
  }
644
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
1106
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
645
1107
  method: "POST"
646
1108
  });
647
1109
  }
648
1110
  /**
649
- * Starts a workflow run synchronously without waiting for the workflow to complete
1111
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
650
1112
  * @param params - Object containing the runId and triggerData
651
1113
  * @returns Promise containing success message
652
1114
  */
653
1115
  start(params) {
654
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1116
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
655
1117
  method: "POST",
656
1118
  body: params?.triggerData
657
1119
  });
658
1120
  }
659
1121
  /**
660
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1122
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
661
1123
  * @param stepId - ID of the step to resume
662
- * @param runId - ID of the workflow run
663
- * @param context - Context to resume the workflow with
664
- * @returns Promise containing the workflow resume results
1124
+ * @param runId - ID of the legacy workflow run
1125
+ * @param context - Context to resume the legacy workflow with
1126
+ * @returns Promise containing the legacy workflow resume results
665
1127
  */
666
1128
  resume({
667
1129
  stepId,
668
1130
  runId,
669
1131
  context
670
1132
  }) {
671
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1133
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
672
1134
  method: "POST",
673
1135
  body: {
674
1136
  stepId,
@@ -686,18 +1148,18 @@ var Workflow = class extends BaseResource {
686
1148
  if (!!params?.runId) {
687
1149
  searchParams.set("runId", params.runId);
688
1150
  }
689
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1151
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
690
1152
  method: "POST",
691
1153
  body: params?.triggerData
692
1154
  });
693
1155
  }
694
1156
  /**
695
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1157
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
696
1158
  * @param params - Object containing the runId, stepId, and context
697
1159
  * @returns Promise containing the workflow resume results
698
1160
  */
699
1161
  resumeAsync(params) {
700
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1162
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
701
1163
  method: "POST",
702
1164
  body: {
703
1165
  stepId: params.stepId,
@@ -751,16 +1213,16 @@ var Workflow = class extends BaseResource {
751
1213
  }
752
1214
  }
753
1215
  /**
754
- * Watches workflow transitions in real-time
1216
+ * Watches legacy workflow transitions in real-time
755
1217
  * @param runId - Optional run ID to filter the watch stream
756
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1218
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
757
1219
  */
758
1220
  async watch({ runId }, onRecord) {
759
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1221
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
760
1222
  stream: true
761
1223
  });
762
1224
  if (!response.ok) {
763
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
1225
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
764
1226
  }
765
1227
  if (!response.body) {
766
1228
  throw new Error("Response body is null");
@@ -772,7 +1234,7 @@ var Workflow = class extends BaseResource {
772
1234
  };
773
1235
 
774
1236
  // src/resources/tool.ts
775
- var Tool = class extends BaseResource {
1237
+ var Tool2 = class extends BaseResource {
776
1238
  constructor(options, toolId) {
777
1239
  super(options);
778
1240
  this.toolId = toolId;
@@ -796,7 +1258,7 @@ var Tool = class extends BaseResource {
796
1258
  }
797
1259
  const body = {
798
1260
  data: params.data,
799
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1261
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
800
1262
  };
801
1263
  return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
802
1264
  method: "POST",
@@ -804,14 +1266,16 @@ var Tool = class extends BaseResource {
804
1266
  });
805
1267
  }
806
1268
  };
1269
+
1270
+ // src/resources/workflow.ts
807
1271
  var RECORD_SEPARATOR2 = "";
808
- var VNextWorkflow = class extends BaseResource {
1272
+ var Workflow = class extends BaseResource {
809
1273
  constructor(options, workflowId) {
810
1274
  super(options);
811
1275
  this.workflowId = workflowId;
812
1276
  }
813
1277
  /**
814
- * Creates an async generator that processes a readable stream and yields vNext workflow records
1278
+ * Creates an async generator that processes a readable stream and yields workflow records
815
1279
  * separated by the Record Separator character (\x1E)
816
1280
  *
817
1281
  * @param stream - The readable stream to process
@@ -856,16 +1320,16 @@ var VNextWorkflow = class extends BaseResource {
856
1320
  }
857
1321
  }
858
1322
  /**
859
- * Retrieves details about the vNext workflow
860
- * @returns Promise containing vNext workflow details including steps and graphs
1323
+ * Retrieves details about the workflow
1324
+ * @returns Promise containing workflow details including steps and graphs
861
1325
  */
862
1326
  details() {
863
- return this.request(`/api/workflows/v-next/${this.workflowId}`);
1327
+ return this.request(`/api/workflows/${this.workflowId}`);
864
1328
  }
865
1329
  /**
866
- * Retrieves all runs for a vNext workflow
1330
+ * Retrieves all runs for a workflow
867
1331
  * @param params - Parameters for filtering runs
868
- * @returns Promise containing vNext workflow runs array
1332
+ * @returns Promise containing workflow runs array
869
1333
  */
870
1334
  runs(params) {
871
1335
  const searchParams = new URLSearchParams();
@@ -875,23 +1339,60 @@ var VNextWorkflow = class extends BaseResource {
875
1339
  if (params?.toDate) {
876
1340
  searchParams.set("toDate", params.toDate.toISOString());
877
1341
  }
878
- if (params?.limit) {
1342
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
879
1343
  searchParams.set("limit", String(params.limit));
880
1344
  }
881
- if (params?.offset) {
1345
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
882
1346
  searchParams.set("offset", String(params.offset));
883
1347
  }
884
1348
  if (params?.resourceId) {
885
1349
  searchParams.set("resourceId", params.resourceId);
886
1350
  }
887
1351
  if (searchParams.size) {
888
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs?${searchParams}`);
1352
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
889
1353
  } else {
890
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
1354
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
891
1355
  }
892
1356
  }
893
1357
  /**
894
- * Creates a new vNext workflow run
1358
+ * Retrieves a specific workflow run by its ID
1359
+ * @param runId - The ID of the workflow run to retrieve
1360
+ * @returns Promise containing the workflow run details
1361
+ */
1362
+ runById(runId) {
1363
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1364
+ }
1365
+ /**
1366
+ * Retrieves the execution result for a specific workflow run by its ID
1367
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1368
+ * @returns Promise containing the workflow run execution result
1369
+ */
1370
+ runExecutionResult(runId) {
1371
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1372
+ }
1373
+ /**
1374
+ * Cancels a specific workflow run by its ID
1375
+ * @param runId - The ID of the workflow run to cancel
1376
+ * @returns Promise containing a success message
1377
+ */
1378
+ cancelRun(runId) {
1379
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1380
+ method: "POST"
1381
+ });
1382
+ }
1383
+ /**
1384
+ * Sends an event to a specific workflow run by its ID
1385
+ * @param params - Object containing the runId, event and data
1386
+ * @returns Promise containing a success message
1387
+ */
1388
+ sendRunEvent(params) {
1389
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1390
+ method: "POST",
1391
+ body: { event: params.event, data: params.data }
1392
+ });
1393
+ }
1394
+ /**
1395
+ * Creates a new workflow run
895
1396
  * @param params - Optional object containing the optional runId
896
1397
  * @returns Promise containing the runId of the created run
897
1398
  */
@@ -900,24 +1401,24 @@ var VNextWorkflow = class extends BaseResource {
900
1401
  if (!!params?.runId) {
901
1402
  searchParams.set("runId", params.runId);
902
1403
  }
903
- return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
1404
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
904
1405
  method: "POST"
905
1406
  });
906
1407
  }
907
1408
  /**
908
- * Starts a vNext workflow run synchronously without waiting for the workflow to complete
1409
+ * Starts a workflow run synchronously without waiting for the workflow to complete
909
1410
  * @param params - Object containing the runId, inputData and runtimeContext
910
1411
  * @returns Promise containing success message
911
1412
  */
912
1413
  start(params) {
913
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
914
- return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
1414
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1415
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
915
1416
  method: "POST",
916
1417
  body: { inputData: params?.inputData, runtimeContext }
917
1418
  });
918
1419
  }
919
1420
  /**
920
- * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
1421
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
921
1422
  * @param params - Object containing the runId, step, resumeData and runtimeContext
922
1423
  * @returns Promise containing success message
923
1424
  */
@@ -927,8 +1428,8 @@ var VNextWorkflow = class extends BaseResource {
927
1428
  resumeData,
928
1429
  ...rest
929
1430
  }) {
930
- const runtimeContext = rest.runtimeContext ? Object.fromEntries(rest.runtimeContext.entries()) : void 0;
931
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
1431
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1432
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
932
1433
  method: "POST",
933
1434
  stream: true,
934
1435
  body: {
@@ -939,29 +1440,76 @@ var VNextWorkflow = class extends BaseResource {
939
1440
  });
940
1441
  }
941
1442
  /**
942
- * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
1443
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
943
1444
  * @param params - Object containing the optional runId, inputData and runtimeContext
944
- * @returns Promise containing the vNext workflow execution results
1445
+ * @returns Promise containing the workflow execution results
945
1446
  */
946
1447
  startAsync(params) {
947
1448
  const searchParams = new URLSearchParams();
948
1449
  if (!!params?.runId) {
949
1450
  searchParams.set("runId", params.runId);
950
1451
  }
951
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
952
- return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
1452
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1453
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
953
1454
  method: "POST",
954
1455
  body: { inputData: params.inputData, runtimeContext }
955
1456
  });
956
1457
  }
957
1458
  /**
958
- * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
1459
+ * Starts a workflow run and returns a stream
1460
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1461
+ * @returns Promise containing the workflow execution results
1462
+ */
1463
+ async stream(params) {
1464
+ const searchParams = new URLSearchParams();
1465
+ if (!!params?.runId) {
1466
+ searchParams.set("runId", params.runId);
1467
+ }
1468
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1469
+ const response = await this.request(
1470
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1471
+ {
1472
+ method: "POST",
1473
+ body: { inputData: params.inputData, runtimeContext },
1474
+ stream: true
1475
+ }
1476
+ );
1477
+ if (!response.ok) {
1478
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1479
+ }
1480
+ if (!response.body) {
1481
+ throw new Error("Response body is null");
1482
+ }
1483
+ const transformStream = new TransformStream({
1484
+ start() {
1485
+ },
1486
+ async transform(chunk, controller) {
1487
+ try {
1488
+ const decoded = new TextDecoder().decode(chunk);
1489
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1490
+ for (const chunk2 of chunks) {
1491
+ if (chunk2) {
1492
+ try {
1493
+ const parsedChunk = JSON.parse(chunk2);
1494
+ controller.enqueue(parsedChunk);
1495
+ } catch {
1496
+ }
1497
+ }
1498
+ }
1499
+ } catch {
1500
+ }
1501
+ }
1502
+ });
1503
+ return response.body.pipeThrough(transformStream);
1504
+ }
1505
+ /**
1506
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
959
1507
  * @param params - Object containing the runId, step, resumeData and runtimeContext
960
- * @returns Promise containing the vNext workflow resume results
1508
+ * @returns Promise containing the workflow resume results
961
1509
  */
962
1510
  resumeAsync(params) {
963
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
964
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
1511
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1512
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
965
1513
  method: "POST",
966
1514
  body: {
967
1515
  step: params.step,
@@ -971,24 +1519,51 @@ var VNextWorkflow = class extends BaseResource {
971
1519
  });
972
1520
  }
973
1521
  /**
974
- * Watches vNext workflow transitions in real-time
1522
+ * Watches workflow transitions in real-time
975
1523
  * @param runId - Optional run ID to filter the watch stream
976
- * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
1524
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
977
1525
  */
978
1526
  async watch({ runId }, onRecord) {
979
- const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
1527
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
980
1528
  stream: true
981
1529
  });
982
1530
  if (!response.ok) {
983
- throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
1531
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
984
1532
  }
985
1533
  if (!response.body) {
986
1534
  throw new Error("Response body is null");
987
1535
  }
988
1536
  for await (const record of this.streamProcessor(response.body)) {
989
- onRecord(record);
1537
+ if (typeof record === "string") {
1538
+ onRecord(JSON.parse(record));
1539
+ } else {
1540
+ onRecord(record);
1541
+ }
990
1542
  }
991
1543
  }
1544
+ /**
1545
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1546
+ * serializing each as JSON and separating them with the record separator (\x1E).
1547
+ *
1548
+ * @param records - An iterable or async iterable of objects to stream
1549
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1550
+ */
1551
+ static createRecordStream(records) {
1552
+ const encoder = new TextEncoder();
1553
+ return new ReadableStream({
1554
+ async start(controller) {
1555
+ try {
1556
+ for await (const record of records) {
1557
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1558
+ controller.enqueue(encoder.encode(json));
1559
+ }
1560
+ controller.close();
1561
+ } catch (err) {
1562
+ controller.error(err);
1563
+ }
1564
+ }
1565
+ });
1566
+ }
992
1567
  };
993
1568
 
994
1569
  // src/resources/a2a.ts
@@ -1065,6 +1640,226 @@ var A2A = class extends BaseResource {
1065
1640
  }
1066
1641
  };
1067
1642
 
1643
+ // src/resources/mcp-tool.ts
1644
+ var MCPTool = class extends BaseResource {
1645
+ serverId;
1646
+ toolId;
1647
+ constructor(options, serverId, toolId) {
1648
+ super(options);
1649
+ this.serverId = serverId;
1650
+ this.toolId = toolId;
1651
+ }
1652
+ /**
1653
+ * Retrieves details about this specific tool from the MCP server.
1654
+ * @returns Promise containing the tool's information (name, description, schema).
1655
+ */
1656
+ details() {
1657
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1658
+ }
1659
+ /**
1660
+ * Executes this specific tool on the MCP server.
1661
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1662
+ * @returns Promise containing the result of the tool execution.
1663
+ */
1664
+ execute(params) {
1665
+ const body = {};
1666
+ if (params.data !== void 0) body.data = params.data;
1667
+ if (params.runtimeContext !== void 0) {
1668
+ body.runtimeContext = params.runtimeContext;
1669
+ }
1670
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1671
+ method: "POST",
1672
+ body: Object.keys(body).length > 0 ? body : void 0
1673
+ });
1674
+ }
1675
+ };
1676
+
1677
+ // src/resources/network-memory-thread.ts
1678
+ var NetworkMemoryThread = class extends BaseResource {
1679
+ constructor(options, threadId, networkId) {
1680
+ super(options);
1681
+ this.threadId = threadId;
1682
+ this.networkId = networkId;
1683
+ }
1684
+ /**
1685
+ * Retrieves the memory thread details
1686
+ * @returns Promise containing thread details including title and metadata
1687
+ */
1688
+ get() {
1689
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1690
+ }
1691
+ /**
1692
+ * Updates the memory thread properties
1693
+ * @param params - Update parameters including title and metadata
1694
+ * @returns Promise containing updated thread details
1695
+ */
1696
+ update(params) {
1697
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1698
+ method: "PATCH",
1699
+ body: params
1700
+ });
1701
+ }
1702
+ /**
1703
+ * Deletes the memory thread
1704
+ * @returns Promise containing deletion result
1705
+ */
1706
+ delete() {
1707
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1708
+ method: "DELETE"
1709
+ });
1710
+ }
1711
+ /**
1712
+ * Retrieves messages associated with the thread
1713
+ * @param params - Optional parameters including limit for number of messages to retrieve
1714
+ * @returns Promise containing thread messages and UI messages
1715
+ */
1716
+ getMessages(params) {
1717
+ const query = new URLSearchParams({
1718
+ networkId: this.networkId,
1719
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1720
+ });
1721
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1722
+ }
1723
+ };
1724
+
1725
+ // src/resources/vNextNetwork.ts
1726
+ var RECORD_SEPARATOR3 = "";
1727
+ var VNextNetwork = class extends BaseResource {
1728
+ constructor(options, networkId) {
1729
+ super(options);
1730
+ this.networkId = networkId;
1731
+ }
1732
+ /**
1733
+ * Retrieves details about the network
1734
+ * @returns Promise containing vNext network details
1735
+ */
1736
+ details() {
1737
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1738
+ }
1739
+ /**
1740
+ * Generates a response from the v-next network
1741
+ * @param params - Generation parameters including message
1742
+ * @returns Promise containing the generated response
1743
+ */
1744
+ generate(params) {
1745
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1746
+ method: "POST",
1747
+ body: {
1748
+ ...params,
1749
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1750
+ }
1751
+ });
1752
+ }
1753
+ /**
1754
+ * Generates a response from the v-next network using multiple primitives
1755
+ * @param params - Generation parameters including message
1756
+ * @returns Promise containing the generated response
1757
+ */
1758
+ loop(params) {
1759
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1760
+ method: "POST",
1761
+ body: {
1762
+ ...params,
1763
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1764
+ }
1765
+ });
1766
+ }
1767
+ async *streamProcessor(stream) {
1768
+ const reader = stream.getReader();
1769
+ let doneReading = false;
1770
+ let buffer = "";
1771
+ try {
1772
+ while (!doneReading) {
1773
+ const { done, value } = await reader.read();
1774
+ doneReading = done;
1775
+ if (done && !value) continue;
1776
+ try {
1777
+ const decoded = value ? new TextDecoder().decode(value) : "";
1778
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1779
+ buffer = chunks.pop() || "";
1780
+ for (const chunk of chunks) {
1781
+ if (chunk) {
1782
+ if (typeof chunk === "string") {
1783
+ try {
1784
+ const parsedChunk = JSON.parse(chunk);
1785
+ yield parsedChunk;
1786
+ } catch {
1787
+ }
1788
+ }
1789
+ }
1790
+ }
1791
+ } catch {
1792
+ }
1793
+ }
1794
+ if (buffer) {
1795
+ try {
1796
+ yield JSON.parse(buffer);
1797
+ } catch {
1798
+ }
1799
+ }
1800
+ } finally {
1801
+ reader.cancel().catch(() => {
1802
+ });
1803
+ }
1804
+ }
1805
+ /**
1806
+ * Streams a response from the v-next network
1807
+ * @param params - Stream parameters including message
1808
+ * @returns Promise containing the results
1809
+ */
1810
+ async stream(params, onRecord) {
1811
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1812
+ method: "POST",
1813
+ body: {
1814
+ ...params,
1815
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1816
+ },
1817
+ stream: true
1818
+ });
1819
+ if (!response.ok) {
1820
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1821
+ }
1822
+ if (!response.body) {
1823
+ throw new Error("Response body is null");
1824
+ }
1825
+ for await (const record of this.streamProcessor(response.body)) {
1826
+ if (typeof record === "string") {
1827
+ onRecord(JSON.parse(record));
1828
+ } else {
1829
+ onRecord(record);
1830
+ }
1831
+ }
1832
+ }
1833
+ /**
1834
+ * Streams a response from the v-next network loop
1835
+ * @param params - Stream parameters including message
1836
+ * @returns Promise containing the results
1837
+ */
1838
+ async loopStream(params, onRecord) {
1839
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1840
+ method: "POST",
1841
+ body: {
1842
+ ...params,
1843
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1844
+ },
1845
+ stream: true
1846
+ });
1847
+ if (!response.ok) {
1848
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1849
+ }
1850
+ if (!response.body) {
1851
+ throw new Error("Response body is null");
1852
+ }
1853
+ for await (const record of this.streamProcessor(response.body)) {
1854
+ if (typeof record === "string") {
1855
+ onRecord(JSON.parse(record));
1856
+ } else {
1857
+ onRecord(record);
1858
+ }
1859
+ }
1860
+ }
1861
+ };
1862
+
1068
1863
  // src/client.ts
1069
1864
  var MastraClient = class extends BaseResource {
1070
1865
  constructor(options) {
@@ -1142,6 +1937,48 @@ var MastraClient = class extends BaseResource {
1142
1937
  getMemoryStatus(agentId) {
1143
1938
  return this.request(`/api/memory/status?agentId=${agentId}`);
1144
1939
  }
1940
+ /**
1941
+ * Retrieves memory threads for a resource
1942
+ * @param params - Parameters containing the resource ID
1943
+ * @returns Promise containing array of memory threads
1944
+ */
1945
+ getNetworkMemoryThreads(params) {
1946
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1947
+ }
1948
+ /**
1949
+ * Creates a new memory thread
1950
+ * @param params - Parameters for creating the memory thread
1951
+ * @returns Promise containing the created memory thread
1952
+ */
1953
+ createNetworkMemoryThread(params) {
1954
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1955
+ }
1956
+ /**
1957
+ * Gets a memory thread instance by ID
1958
+ * @param threadId - ID of the memory thread to retrieve
1959
+ * @returns MemoryThread instance
1960
+ */
1961
+ getNetworkMemoryThread(threadId, networkId) {
1962
+ return new NetworkMemoryThread(this.options, threadId, networkId);
1963
+ }
1964
+ /**
1965
+ * Saves messages to memory
1966
+ * @param params - Parameters containing messages to save
1967
+ * @returns Promise containing the saved messages
1968
+ */
1969
+ saveNetworkMessageToMemory(params) {
1970
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
1971
+ method: "POST",
1972
+ body: params
1973
+ });
1974
+ }
1975
+ /**
1976
+ * Gets the status of the memory system
1977
+ * @returns Promise containing memory system status
1978
+ */
1979
+ getNetworkMemoryStatus(networkId) {
1980
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
1981
+ }
1145
1982
  /**
1146
1983
  * Retrieves all available tools
1147
1984
  * @returns Promise containing map of tool IDs to tool details
@@ -1155,7 +1992,22 @@ var MastraClient = class extends BaseResource {
1155
1992
  * @returns Tool instance
1156
1993
  */
1157
1994
  getTool(toolId) {
1158
- return new Tool(this.options, toolId);
1995
+ return new Tool2(this.options, toolId);
1996
+ }
1997
+ /**
1998
+ * Retrieves all available legacy workflows
1999
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2000
+ */
2001
+ getLegacyWorkflows() {
2002
+ return this.request("/api/workflows/legacy");
2003
+ }
2004
+ /**
2005
+ * Gets a legacy workflow instance by ID
2006
+ * @param workflowId - ID of the legacy workflow to retrieve
2007
+ * @returns Legacy Workflow instance
2008
+ */
2009
+ getLegacyWorkflow(workflowId) {
2010
+ return new LegacyWorkflow(this.options, workflowId);
1159
2011
  }
1160
2012
  /**
1161
2013
  * Retrieves all available workflows
@@ -1172,21 +2024,6 @@ var MastraClient = class extends BaseResource {
1172
2024
  getWorkflow(workflowId) {
1173
2025
  return new Workflow(this.options, workflowId);
1174
2026
  }
1175
- /**
1176
- * Retrieves all available vNext workflows
1177
- * @returns Promise containing map of vNext workflow IDs to vNext workflow details
1178
- */
1179
- getVNextWorkflows() {
1180
- return this.request("/api/workflows/v-next");
1181
- }
1182
- /**
1183
- * Gets a vNext workflow instance by ID
1184
- * @param workflowId - ID of the vNext workflow to retrieve
1185
- * @returns vNext Workflow instance
1186
- */
1187
- getVNextWorkflow(workflowId) {
1188
- return new VNextWorkflow(this.options, workflowId);
1189
- }
1190
2027
  /**
1191
2028
  * Gets a vector instance by name
1192
2029
  * @param vectorName - Name of the vector to retrieve
@@ -1201,7 +2038,41 @@ var MastraClient = class extends BaseResource {
1201
2038
  * @returns Promise containing array of log messages
1202
2039
  */
1203
2040
  getLogs(params) {
1204
- return this.request(`/api/logs?transportId=${params.transportId}`);
2041
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2042
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2043
+ const searchParams = new URLSearchParams();
2044
+ if (transportId) {
2045
+ searchParams.set("transportId", transportId);
2046
+ }
2047
+ if (fromDate) {
2048
+ searchParams.set("fromDate", fromDate.toISOString());
2049
+ }
2050
+ if (toDate) {
2051
+ searchParams.set("toDate", toDate.toISOString());
2052
+ }
2053
+ if (logLevel) {
2054
+ searchParams.set("logLevel", logLevel);
2055
+ }
2056
+ if (page) {
2057
+ searchParams.set("page", String(page));
2058
+ }
2059
+ if (perPage) {
2060
+ searchParams.set("perPage", String(perPage));
2061
+ }
2062
+ if (_filters) {
2063
+ if (Array.isArray(_filters)) {
2064
+ for (const filter of _filters) {
2065
+ searchParams.append("filters", filter);
2066
+ }
2067
+ } else {
2068
+ searchParams.set("filters", _filters);
2069
+ }
2070
+ }
2071
+ if (searchParams.size) {
2072
+ return this.request(`/api/logs?${searchParams}`);
2073
+ } else {
2074
+ return this.request(`/api/logs`);
2075
+ }
1205
2076
  }
1206
2077
  /**
1207
2078
  * Gets logs for a specific run
@@ -1209,7 +2080,44 @@ var MastraClient = class extends BaseResource {
1209
2080
  * @returns Promise containing array of log messages
1210
2081
  */
1211
2082
  getLogForRun(params) {
1212
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2083
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2084
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2085
+ const searchParams = new URLSearchParams();
2086
+ if (runId) {
2087
+ searchParams.set("runId", runId);
2088
+ }
2089
+ if (transportId) {
2090
+ searchParams.set("transportId", transportId);
2091
+ }
2092
+ if (fromDate) {
2093
+ searchParams.set("fromDate", fromDate.toISOString());
2094
+ }
2095
+ if (toDate) {
2096
+ searchParams.set("toDate", toDate.toISOString());
2097
+ }
2098
+ if (logLevel) {
2099
+ searchParams.set("logLevel", logLevel);
2100
+ }
2101
+ if (page) {
2102
+ searchParams.set("page", String(page));
2103
+ }
2104
+ if (perPage) {
2105
+ searchParams.set("perPage", String(perPage));
2106
+ }
2107
+ if (_filters) {
2108
+ if (Array.isArray(_filters)) {
2109
+ for (const filter of _filters) {
2110
+ searchParams.append("filters", filter);
2111
+ }
2112
+ } else {
2113
+ searchParams.set("filters", _filters);
2114
+ }
2115
+ }
2116
+ if (searchParams.size) {
2117
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2118
+ } else {
2119
+ return this.request(`/api/logs/${runId}`);
2120
+ }
1213
2121
  }
1214
2122
  /**
1215
2123
  * List of all log transports
@@ -1267,6 +2175,13 @@ var MastraClient = class extends BaseResource {
1267
2175
  getNetworks() {
1268
2176
  return this.request("/api/networks");
1269
2177
  }
2178
+ /**
2179
+ * Retrieves all available vNext networks
2180
+ * @returns Promise containing map of vNext network IDs to vNext network details
2181
+ */
2182
+ getVNextNetworks() {
2183
+ return this.request("/api/networks/v-next");
2184
+ }
1270
2185
  /**
1271
2186
  * Gets a network instance by ID
1272
2187
  * @param networkId - ID of the network to retrieve
@@ -1275,6 +2190,62 @@ var MastraClient = class extends BaseResource {
1275
2190
  getNetwork(networkId) {
1276
2191
  return new Network(this.options, networkId);
1277
2192
  }
2193
+ /**
2194
+ * Gets a vNext network instance by ID
2195
+ * @param networkId - ID of the vNext network to retrieve
2196
+ * @returns vNext Network instance
2197
+ */
2198
+ getVNextNetwork(networkId) {
2199
+ return new VNextNetwork(this.options, networkId);
2200
+ }
2201
+ /**
2202
+ * Retrieves a list of available MCP servers.
2203
+ * @param params - Optional parameters for pagination (limit, offset).
2204
+ * @returns Promise containing the list of MCP servers and pagination info.
2205
+ */
2206
+ getMcpServers(params) {
2207
+ const searchParams = new URLSearchParams();
2208
+ if (params?.limit !== void 0) {
2209
+ searchParams.set("limit", String(params.limit));
2210
+ }
2211
+ if (params?.offset !== void 0) {
2212
+ searchParams.set("offset", String(params.offset));
2213
+ }
2214
+ const queryString = searchParams.toString();
2215
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
2216
+ }
2217
+ /**
2218
+ * Retrieves detailed information for a specific MCP server.
2219
+ * @param serverId - The ID of the MCP server to retrieve.
2220
+ * @param params - Optional parameters, e.g., specific version.
2221
+ * @returns Promise containing the detailed MCP server information.
2222
+ */
2223
+ getMcpServerDetails(serverId, params) {
2224
+ const searchParams = new URLSearchParams();
2225
+ if (params?.version) {
2226
+ searchParams.set("version", params.version);
2227
+ }
2228
+ const queryString = searchParams.toString();
2229
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
2230
+ }
2231
+ /**
2232
+ * Retrieves a list of tools for a specific MCP server.
2233
+ * @param serverId - The ID of the MCP server.
2234
+ * @returns Promise containing the list of tools.
2235
+ */
2236
+ getMcpServerTools(serverId) {
2237
+ return this.request(`/api/mcp/${serverId}/tools`);
2238
+ }
2239
+ /**
2240
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
2241
+ * This instance can then be used to fetch details or execute the tool.
2242
+ * @param serverId - The ID of the MCP server.
2243
+ * @param toolId - The ID of the tool.
2244
+ * @returns MCPTool instance.
2245
+ */
2246
+ getMcpServerTool(serverId, toolId) {
2247
+ return new MCPTool(this.options, serverId, toolId);
2248
+ }
1278
2249
  /**
1279
2250
  * Gets an A2A client for interacting with an agent via the A2A protocol
1280
2251
  * @param agentId - ID of the agent to interact with
@@ -1283,6 +2254,41 @@ var MastraClient = class extends BaseResource {
1283
2254
  getA2A(agentId) {
1284
2255
  return new A2A(this.options, agentId);
1285
2256
  }
2257
+ /**
2258
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2259
+ * @param agentId - ID of the agent.
2260
+ * @param threadId - ID of the thread.
2261
+ * @param resourceId - Optional ID of the resource.
2262
+ * @returns Working memory for the specified thread or resource.
2263
+ */
2264
+ getWorkingMemory({
2265
+ agentId,
2266
+ threadId,
2267
+ resourceId
2268
+ }) {
2269
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2270
+ }
2271
+ /**
2272
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2273
+ * @param agentId - ID of the agent.
2274
+ * @param threadId - ID of the thread.
2275
+ * @param workingMemory - The new working memory content.
2276
+ * @param resourceId - Optional ID of the resource.
2277
+ */
2278
+ updateWorkingMemory({
2279
+ agentId,
2280
+ threadId,
2281
+ workingMemory,
2282
+ resourceId
2283
+ }) {
2284
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2285
+ method: "POST",
2286
+ body: {
2287
+ workingMemory,
2288
+ resourceId
2289
+ }
2290
+ });
2291
+ }
1286
2292
  };
1287
2293
 
1288
2294
  exports.MastraClient = MastraClient;