@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.js CHANGED
@@ -1,8 +1,11 @@
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 { processTextStream, 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';
7
+ import { v4 } from '@lukeed/uuid';
8
+ import { RuntimeContext } from '@mastra/core/runtime-context';
6
9
 
7
10
  // src/adapters/agui.ts
8
11
  var AGUIAdapter = class extends AbstractAgent {
@@ -195,6 +198,33 @@ function zodToJsonSchema(zodSchema) {
195
198
  }
196
199
  return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
197
200
  }
201
+ function processClientTools(clientTools) {
202
+ if (!clientTools) {
203
+ return void 0;
204
+ }
205
+ return Object.fromEntries(
206
+ Object.entries(clientTools).map(([key, value]) => {
207
+ if (isVercelTool(value)) {
208
+ return [
209
+ key,
210
+ {
211
+ ...value,
212
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
213
+ }
214
+ ];
215
+ } else {
216
+ return [
217
+ key,
218
+ {
219
+ ...value,
220
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
221
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
222
+ }
223
+ ];
224
+ }
225
+ })
226
+ );
227
+ }
198
228
 
199
229
  // src/resources/base.ts
200
230
  var BaseResource = class {
@@ -214,14 +244,16 @@ var BaseResource = class {
214
244
  let delay = backoffMs;
215
245
  for (let attempt = 0; attempt <= retries; attempt++) {
216
246
  try {
217
- const response = await fetch(`${baseUrl}${path}`, {
247
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
218
248
  ...options,
219
249
  headers: {
250
+ ...options.method === "POST" || options.method === "PUT" ? { "content-type": "application/json" } : {},
220
251
  ...headers,
221
252
  ...options.headers
222
253
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
223
254
  // 'x-mastra-client-type': 'js',
224
255
  },
256
+ signal: this.options.abortSignal,
225
257
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
226
258
  });
227
259
  if (!response.ok) {
@@ -254,8 +286,15 @@ var BaseResource = class {
254
286
  throw lastError || new Error("Request failed");
255
287
  }
256
288
  };
257
-
258
- // src/resources/agent.ts
289
+ function parseClientRuntimeContext(runtimeContext) {
290
+ if (runtimeContext) {
291
+ if (runtimeContext instanceof RuntimeContext) {
292
+ return Object.fromEntries(runtimeContext.entries());
293
+ }
294
+ return runtimeContext;
295
+ }
296
+ return void 0;
297
+ }
259
298
  var AgentVoice = class extends BaseResource {
260
299
  constructor(options, agentId) {
261
300
  super(options);
@@ -302,6 +341,13 @@ var AgentVoice = class extends BaseResource {
302
341
  getSpeakers() {
303
342
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
304
343
  }
344
+ /**
345
+ * Get the listener configuration for the agent's voice provider
346
+ * @returns Promise containing a check if the agent has listening capabilities
347
+ */
348
+ getListener() {
349
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
350
+ }
305
351
  };
306
352
  var Agent = class extends BaseResource {
307
353
  constructor(options, agentId) {
@@ -317,35 +363,341 @@ var Agent = class extends BaseResource {
317
363
  details() {
318
364
  return this.request(`/api/agents/${this.agentId}`);
319
365
  }
320
- /**
321
- * Generates a response from the agent
322
- * @param params - Generation parameters including prompt
323
- * @returns Promise containing the generated response
324
- */
325
- generate(params) {
366
+ async generate(params) {
326
367
  const processedParams = {
327
368
  ...params,
328
- output: zodToJsonSchema(params.output),
329
- experimental_output: zodToJsonSchema(params.experimental_output),
330
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
369
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
370
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
371
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
372
+ clientTools: processClientTools(params.clientTools)
331
373
  };
332
- return this.request(`/api/agents/${this.agentId}/generate`, {
374
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
375
+ const response = await this.request(`/api/agents/${this.agentId}/generate`, {
333
376
  method: "POST",
334
377
  body: processedParams
335
378
  });
379
+ if (response.finishReason === "tool-calls") {
380
+ const toolCalls = response.toolCalls;
381
+ if (!toolCalls || !Array.isArray(toolCalls)) {
382
+ return response;
383
+ }
384
+ for (const toolCall of toolCalls) {
385
+ const clientTool = params.clientTools?.[toolCall.toolName];
386
+ if (clientTool && clientTool.execute) {
387
+ const result = await clientTool.execute(
388
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
389
+ {
390
+ messages: response.messages,
391
+ toolCallId: toolCall?.toolCallId
392
+ }
393
+ );
394
+ const updatedMessages = [
395
+ {
396
+ role: "user",
397
+ content: params.messages
398
+ },
399
+ ...response.response.messages,
400
+ {
401
+ role: "tool",
402
+ content: [
403
+ {
404
+ type: "tool-result",
405
+ toolCallId: toolCall.toolCallId,
406
+ toolName: toolCall.toolName,
407
+ result
408
+ }
409
+ ]
410
+ }
411
+ ];
412
+ return this.generate({
413
+ ...params,
414
+ messages: updatedMessages
415
+ });
416
+ }
417
+ }
418
+ }
419
+ return response;
420
+ }
421
+ async processChatResponse({
422
+ stream,
423
+ update,
424
+ onToolCall,
425
+ onFinish,
426
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
427
+ lastMessage,
428
+ streamProtocol
429
+ }) {
430
+ const replaceLastMessage = lastMessage?.role === "assistant";
431
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
432
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
433
+ return Math.max(max, toolInvocation.step ?? 0);
434
+ }, 0) ?? 0) : 0;
435
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
436
+ id: v4(),
437
+ createdAt: getCurrentDate(),
438
+ role: "assistant",
439
+ content: "",
440
+ parts: []
441
+ };
442
+ let currentTextPart = void 0;
443
+ let currentReasoningPart = void 0;
444
+ let currentReasoningTextDetail = void 0;
445
+ function updateToolInvocationPart(toolCallId, invocation) {
446
+ const part = message.parts.find(
447
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
448
+ );
449
+ if (part != null) {
450
+ part.toolInvocation = invocation;
451
+ } else {
452
+ message.parts.push({
453
+ type: "tool-invocation",
454
+ toolInvocation: invocation
455
+ });
456
+ }
457
+ }
458
+ const data = [];
459
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
460
+ const partialToolCalls = {};
461
+ let usage = {
462
+ completionTokens: NaN,
463
+ promptTokens: NaN,
464
+ totalTokens: NaN
465
+ };
466
+ let finishReason = "unknown";
467
+ function execUpdate() {
468
+ const copiedData = [...data];
469
+ if (messageAnnotations?.length) {
470
+ message.annotations = messageAnnotations;
471
+ }
472
+ const copiedMessage = {
473
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
474
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
475
+ ...structuredClone(message),
476
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
477
+ // hashing approach by default to detect changes, but it only works for shallow
478
+ // changes. This is why we need to add a revision id to ensure that the message
479
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
480
+ // forwarded to rendering):
481
+ revisionId: v4()
482
+ };
483
+ update({
484
+ message: copiedMessage,
485
+ data: copiedData,
486
+ replaceLastMessage
487
+ });
488
+ }
489
+ if (streamProtocol === "text") {
490
+ await processTextStream({
491
+ stream,
492
+ onTextPart(value) {
493
+ message.content += value;
494
+ execUpdate();
495
+ }
496
+ });
497
+ onFinish?.({ message, finishReason, usage });
498
+ } else {
499
+ await processDataStream({
500
+ stream,
501
+ onTextPart(value) {
502
+ if (currentTextPart == null) {
503
+ currentTextPart = {
504
+ type: "text",
505
+ text: value
506
+ };
507
+ message.parts.push(currentTextPart);
508
+ } else {
509
+ currentTextPart.text += value;
510
+ }
511
+ message.content += value;
512
+ execUpdate();
513
+ },
514
+ onReasoningPart(value) {
515
+ if (currentReasoningTextDetail == null) {
516
+ currentReasoningTextDetail = { type: "text", text: value };
517
+ if (currentReasoningPart != null) {
518
+ currentReasoningPart.details.push(currentReasoningTextDetail);
519
+ }
520
+ } else {
521
+ currentReasoningTextDetail.text += value;
522
+ }
523
+ if (currentReasoningPart == null) {
524
+ currentReasoningPart = {
525
+ type: "reasoning",
526
+ reasoning: value,
527
+ details: [currentReasoningTextDetail]
528
+ };
529
+ message.parts.push(currentReasoningPart);
530
+ } else {
531
+ currentReasoningPart.reasoning += value;
532
+ }
533
+ message.reasoning = (message.reasoning ?? "") + value;
534
+ execUpdate();
535
+ },
536
+ onReasoningSignaturePart(value) {
537
+ if (currentReasoningTextDetail != null) {
538
+ currentReasoningTextDetail.signature = value.signature;
539
+ }
540
+ },
541
+ onRedactedReasoningPart(value) {
542
+ if (currentReasoningPart == null) {
543
+ currentReasoningPart = {
544
+ type: "reasoning",
545
+ reasoning: "",
546
+ details: []
547
+ };
548
+ message.parts.push(currentReasoningPart);
549
+ }
550
+ currentReasoningPart.details.push({
551
+ type: "redacted",
552
+ data: value.data
553
+ });
554
+ currentReasoningTextDetail = void 0;
555
+ execUpdate();
556
+ },
557
+ onFilePart(value) {
558
+ message.parts.push({
559
+ type: "file",
560
+ mimeType: value.mimeType,
561
+ data: value.data
562
+ });
563
+ execUpdate();
564
+ },
565
+ onSourcePart(value) {
566
+ message.parts.push({
567
+ type: "source",
568
+ source: value
569
+ });
570
+ execUpdate();
571
+ },
572
+ onToolCallStreamingStartPart(value) {
573
+ if (message.toolInvocations == null) {
574
+ message.toolInvocations = [];
575
+ }
576
+ partialToolCalls[value.toolCallId] = {
577
+ text: "",
578
+ step,
579
+ toolName: value.toolName,
580
+ index: message.toolInvocations.length
581
+ };
582
+ const invocation = {
583
+ state: "partial-call",
584
+ step,
585
+ toolCallId: value.toolCallId,
586
+ toolName: value.toolName,
587
+ args: void 0
588
+ };
589
+ message.toolInvocations.push(invocation);
590
+ updateToolInvocationPart(value.toolCallId, invocation);
591
+ execUpdate();
592
+ },
593
+ onToolCallDeltaPart(value) {
594
+ const partialToolCall = partialToolCalls[value.toolCallId];
595
+ partialToolCall.text += value.argsTextDelta;
596
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
597
+ const invocation = {
598
+ state: "partial-call",
599
+ step: partialToolCall.step,
600
+ toolCallId: value.toolCallId,
601
+ toolName: partialToolCall.toolName,
602
+ args: partialArgs
603
+ };
604
+ message.toolInvocations[partialToolCall.index] = invocation;
605
+ updateToolInvocationPart(value.toolCallId, invocation);
606
+ execUpdate();
607
+ },
608
+ async onToolCallPart(value) {
609
+ const invocation = {
610
+ state: "call",
611
+ step,
612
+ ...value
613
+ };
614
+ if (partialToolCalls[value.toolCallId] != null) {
615
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
616
+ } else {
617
+ if (message.toolInvocations == null) {
618
+ message.toolInvocations = [];
619
+ }
620
+ message.toolInvocations.push(invocation);
621
+ }
622
+ updateToolInvocationPart(value.toolCallId, invocation);
623
+ execUpdate();
624
+ if (onToolCall) {
625
+ const result = await onToolCall({ toolCall: value });
626
+ if (result != null) {
627
+ const invocation2 = {
628
+ state: "result",
629
+ step,
630
+ ...value,
631
+ result
632
+ };
633
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
634
+ updateToolInvocationPart(value.toolCallId, invocation2);
635
+ execUpdate();
636
+ }
637
+ }
638
+ },
639
+ onToolResultPart(value) {
640
+ const toolInvocations = message.toolInvocations;
641
+ if (toolInvocations == null) {
642
+ throw new Error("tool_result must be preceded by a tool_call");
643
+ }
644
+ const toolInvocationIndex = toolInvocations.findIndex(
645
+ (invocation2) => invocation2.toolCallId === value.toolCallId
646
+ );
647
+ if (toolInvocationIndex === -1) {
648
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
649
+ }
650
+ const invocation = {
651
+ ...toolInvocations[toolInvocationIndex],
652
+ state: "result",
653
+ ...value
654
+ };
655
+ toolInvocations[toolInvocationIndex] = invocation;
656
+ updateToolInvocationPart(value.toolCallId, invocation);
657
+ execUpdate();
658
+ },
659
+ onDataPart(value) {
660
+ data.push(...value);
661
+ execUpdate();
662
+ },
663
+ onMessageAnnotationsPart(value) {
664
+ if (messageAnnotations == null) {
665
+ messageAnnotations = [...value];
666
+ } else {
667
+ messageAnnotations.push(...value);
668
+ }
669
+ execUpdate();
670
+ },
671
+ onFinishStepPart(value) {
672
+ step += 1;
673
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
674
+ currentReasoningPart = void 0;
675
+ currentReasoningTextDetail = void 0;
676
+ },
677
+ onStartStepPart(value) {
678
+ if (!replaceLastMessage) {
679
+ message.id = value.messageId;
680
+ }
681
+ message.parts.push({ type: "step-start" });
682
+ execUpdate();
683
+ },
684
+ onFinishMessagePart(value) {
685
+ finishReason = value.finishReason;
686
+ if (value.usage != null) {
687
+ usage = value.usage;
688
+ }
689
+ },
690
+ onErrorPart(error) {
691
+ throw new Error(error);
692
+ }
693
+ });
694
+ onFinish?.({ message, finishReason, usage });
695
+ }
336
696
  }
337
697
  /**
338
- * Streams a response from the agent
339
- * @param params - Stream parameters including prompt
340
- * @returns Promise containing the enhanced Response object with processDataStream method
698
+ * Processes the stream response and handles tool calls
341
699
  */
342
- async stream(params) {
343
- const processedParams = {
344
- ...params,
345
- output: zodToJsonSchema(params.output),
346
- experimental_output: zodToJsonSchema(params.experimental_output),
347
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
348
- };
700
+ async processStreamResponse(processedParams, writable) {
349
701
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
350
702
  method: "POST",
351
703
  body: processedParams,
@@ -354,13 +706,135 @@ var Agent = class extends BaseResource {
354
706
  if (!response.body) {
355
707
  throw new Error("No response body");
356
708
  }
357
- response.processDataStream = async (options = {}) => {
709
+ try {
710
+ const streamProtocol = processedParams.output ? "text" : "data";
711
+ let toolCalls = [];
712
+ let messages = [];
713
+ const [streamForWritable, streamForProcessing] = response.body.tee();
714
+ streamForWritable.pipeTo(writable, {
715
+ preventClose: true
716
+ }).catch((error) => {
717
+ console.error("Error piping to writable stream:", error);
718
+ });
719
+ this.processChatResponse({
720
+ stream: streamForProcessing,
721
+ update: ({ message }) => {
722
+ messages.push(message);
723
+ },
724
+ onFinish: async ({ finishReason, message }) => {
725
+ if (finishReason === "tool-calls") {
726
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
727
+ if (toolCall) {
728
+ toolCalls.push(toolCall);
729
+ }
730
+ for (const toolCall2 of toolCalls) {
731
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
732
+ if (clientTool && clientTool.execute) {
733
+ const result = await clientTool.execute(
734
+ {
735
+ context: toolCall2?.args,
736
+ runId: processedParams.runId,
737
+ resourceId: processedParams.resourceId,
738
+ threadId: processedParams.threadId,
739
+ runtimeContext: processedParams.runtimeContext
740
+ },
741
+ {
742
+ messages: response.messages,
743
+ toolCallId: toolCall2?.toolCallId
744
+ }
745
+ );
746
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
747
+ const toolInvocationPart = lastMessage?.parts?.find(
748
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
749
+ );
750
+ if (toolInvocationPart) {
751
+ toolInvocationPart.toolInvocation = {
752
+ ...toolInvocationPart.toolInvocation,
753
+ state: "result",
754
+ result
755
+ };
756
+ }
757
+ const toolInvocation = lastMessage?.toolInvocations?.find(
758
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
759
+ );
760
+ if (toolInvocation) {
761
+ toolInvocation.state = "result";
762
+ toolInvocation.result = result;
763
+ }
764
+ const writer = writable.getWriter();
765
+ try {
766
+ await writer.write(
767
+ new TextEncoder().encode(
768
+ "a:" + JSON.stringify({
769
+ toolCallId: toolCall2.toolCallId,
770
+ result
771
+ }) + "\n"
772
+ )
773
+ );
774
+ } finally {
775
+ writer.releaseLock();
776
+ }
777
+ const originalMessages = processedParams.messages;
778
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
779
+ this.processStreamResponse(
780
+ {
781
+ ...processedParams,
782
+ messages: [...messageArray, ...messages, lastMessage]
783
+ },
784
+ writable
785
+ );
786
+ }
787
+ }
788
+ } else {
789
+ setTimeout(() => {
790
+ if (!writable.locked) {
791
+ writable.close();
792
+ }
793
+ }, 0);
794
+ }
795
+ },
796
+ lastMessage: void 0,
797
+ streamProtocol
798
+ });
799
+ } catch (error) {
800
+ console.error("Error processing stream response:", error);
801
+ }
802
+ return response;
803
+ }
804
+ /**
805
+ * Streams a response from the agent
806
+ * @param params - Stream parameters including prompt
807
+ * @returns Promise containing the enhanced Response object with processDataStream and processTextStream methods
808
+ */
809
+ async stream(params) {
810
+ const processedParams = {
811
+ ...params,
812
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
813
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
814
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
815
+ clientTools: processClientTools(params.clientTools)
816
+ };
817
+ const { readable, writable } = new TransformStream();
818
+ const response = await this.processStreamResponse(processedParams, writable);
819
+ const streamResponse = new Response(readable, {
820
+ status: response.status,
821
+ statusText: response.statusText,
822
+ headers: response.headers
823
+ });
824
+ streamResponse.processDataStream = async (options = {}) => {
358
825
  await processDataStream({
359
- stream: response.body,
826
+ stream: streamResponse.body,
360
827
  ...options
361
828
  });
362
829
  };
363
- return response;
830
+ streamResponse.processTextStream = async (options) => {
831
+ await processTextStream({
832
+ stream: streamResponse.body,
833
+ onTextPart: options?.onTextPart ?? (() => {
834
+ })
835
+ });
836
+ };
837
+ return streamResponse;
364
838
  }
365
839
  /**
366
840
  * Gets details about a specific tool available to the agent
@@ -572,24 +1046,24 @@ var Vector = class extends BaseResource {
572
1046
  }
573
1047
  };
574
1048
 
575
- // src/resources/workflow.ts
1049
+ // src/resources/legacy-workflow.ts
576
1050
  var RECORD_SEPARATOR = "";
577
- var Workflow = class extends BaseResource {
1051
+ var LegacyWorkflow = class extends BaseResource {
578
1052
  constructor(options, workflowId) {
579
1053
  super(options);
580
1054
  this.workflowId = workflowId;
581
1055
  }
582
1056
  /**
583
- * Retrieves details about the workflow
584
- * @returns Promise containing workflow details including steps and graphs
1057
+ * Retrieves details about the legacy workflow
1058
+ * @returns Promise containing legacy workflow details including steps and graphs
585
1059
  */
586
1060
  details() {
587
- return this.request(`/api/workflows/${this.workflowId}`);
1061
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
588
1062
  }
589
1063
  /**
590
- * Retrieves all runs for a workflow
1064
+ * Retrieves all runs for a legacy workflow
591
1065
  * @param params - Parameters for filtering runs
592
- * @returns Promise containing workflow runs array
1066
+ * @returns Promise containing legacy workflow runs array
593
1067
  */
594
1068
  runs(params) {
595
1069
  const searchParams = new URLSearchParams();
@@ -609,25 +1083,13 @@ var Workflow = class extends BaseResource {
609
1083
  searchParams.set("resourceId", params.resourceId);
610
1084
  }
611
1085
  if (searchParams.size) {
612
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1086
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
613
1087
  } else {
614
- return this.request(`/api/workflows/${this.workflowId}/runs`);
1088
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
615
1089
  }
616
1090
  }
617
1091
  /**
618
- * @deprecated Use `startAsync` instead
619
- * Executes the workflow with the provided parameters
620
- * @param params - Parameters required for workflow execution
621
- * @returns Promise containing the workflow execution results
622
- */
623
- execute(params) {
624
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
625
- method: "POST",
626
- body: params
627
- });
628
- }
629
- /**
630
- * Creates a new workflow run
1092
+ * Creates a new legacy workflow run
631
1093
  * @returns Promise containing the generated run ID
632
1094
  */
633
1095
  createRun(params) {
@@ -635,34 +1097,34 @@ var Workflow = class extends BaseResource {
635
1097
  if (!!params?.runId) {
636
1098
  searchParams.set("runId", params.runId);
637
1099
  }
638
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
1100
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
639
1101
  method: "POST"
640
1102
  });
641
1103
  }
642
1104
  /**
643
- * Starts a workflow run synchronously without waiting for the workflow to complete
1105
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
644
1106
  * @param params - Object containing the runId and triggerData
645
1107
  * @returns Promise containing success message
646
1108
  */
647
1109
  start(params) {
648
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1110
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
649
1111
  method: "POST",
650
1112
  body: params?.triggerData
651
1113
  });
652
1114
  }
653
1115
  /**
654
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1116
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
655
1117
  * @param stepId - ID of the step to resume
656
- * @param runId - ID of the workflow run
657
- * @param context - Context to resume the workflow with
658
- * @returns Promise containing the workflow resume results
1118
+ * @param runId - ID of the legacy workflow run
1119
+ * @param context - Context to resume the legacy workflow with
1120
+ * @returns Promise containing the legacy workflow resume results
659
1121
  */
660
1122
  resume({
661
1123
  stepId,
662
1124
  runId,
663
1125
  context
664
1126
  }) {
665
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1127
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
666
1128
  method: "POST",
667
1129
  body: {
668
1130
  stepId,
@@ -680,18 +1142,18 @@ var Workflow = class extends BaseResource {
680
1142
  if (!!params?.runId) {
681
1143
  searchParams.set("runId", params.runId);
682
1144
  }
683
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1145
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
684
1146
  method: "POST",
685
1147
  body: params?.triggerData
686
1148
  });
687
1149
  }
688
1150
  /**
689
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1151
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
690
1152
  * @param params - Object containing the runId, stepId, and context
691
1153
  * @returns Promise containing the workflow resume results
692
1154
  */
693
1155
  resumeAsync(params) {
694
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1156
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
695
1157
  method: "POST",
696
1158
  body: {
697
1159
  stepId: params.stepId,
@@ -745,16 +1207,16 @@ var Workflow = class extends BaseResource {
745
1207
  }
746
1208
  }
747
1209
  /**
748
- * Watches workflow transitions in real-time
1210
+ * Watches legacy workflow transitions in real-time
749
1211
  * @param runId - Optional run ID to filter the watch stream
750
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1212
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
751
1213
  */
752
1214
  async watch({ runId }, onRecord) {
753
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1215
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
754
1216
  stream: true
755
1217
  });
756
1218
  if (!response.ok) {
757
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
1219
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
758
1220
  }
759
1221
  if (!response.body) {
760
1222
  throw new Error("Response body is null");
@@ -766,7 +1228,7 @@ var Workflow = class extends BaseResource {
766
1228
  };
767
1229
 
768
1230
  // src/resources/tool.ts
769
- var Tool = class extends BaseResource {
1231
+ var Tool2 = class extends BaseResource {
770
1232
  constructor(options, toolId) {
771
1233
  super(options);
772
1234
  this.toolId = toolId;
@@ -790,7 +1252,7 @@ var Tool = class extends BaseResource {
790
1252
  }
791
1253
  const body = {
792
1254
  data: params.data,
793
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1255
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
794
1256
  };
795
1257
  return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
796
1258
  method: "POST",
@@ -798,14 +1260,16 @@ var Tool = class extends BaseResource {
798
1260
  });
799
1261
  }
800
1262
  };
1263
+
1264
+ // src/resources/workflow.ts
801
1265
  var RECORD_SEPARATOR2 = "";
802
- var VNextWorkflow = class extends BaseResource {
1266
+ var Workflow = class extends BaseResource {
803
1267
  constructor(options, workflowId) {
804
1268
  super(options);
805
1269
  this.workflowId = workflowId;
806
1270
  }
807
1271
  /**
808
- * Creates an async generator that processes a readable stream and yields vNext workflow records
1272
+ * Creates an async generator that processes a readable stream and yields workflow records
809
1273
  * separated by the Record Separator character (\x1E)
810
1274
  *
811
1275
  * @param stream - The readable stream to process
@@ -850,16 +1314,16 @@ var VNextWorkflow = class extends BaseResource {
850
1314
  }
851
1315
  }
852
1316
  /**
853
- * Retrieves details about the vNext workflow
854
- * @returns Promise containing vNext workflow details including steps and graphs
1317
+ * Retrieves details about the workflow
1318
+ * @returns Promise containing workflow details including steps and graphs
855
1319
  */
856
1320
  details() {
857
- return this.request(`/api/workflows/v-next/${this.workflowId}`);
1321
+ return this.request(`/api/workflows/${this.workflowId}`);
858
1322
  }
859
1323
  /**
860
- * Retrieves all runs for a vNext workflow
1324
+ * Retrieves all runs for a workflow
861
1325
  * @param params - Parameters for filtering runs
862
- * @returns Promise containing vNext workflow runs array
1326
+ * @returns Promise containing workflow runs array
863
1327
  */
864
1328
  runs(params) {
865
1329
  const searchParams = new URLSearchParams();
@@ -869,23 +1333,60 @@ var VNextWorkflow = class extends BaseResource {
869
1333
  if (params?.toDate) {
870
1334
  searchParams.set("toDate", params.toDate.toISOString());
871
1335
  }
872
- if (params?.limit) {
1336
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
873
1337
  searchParams.set("limit", String(params.limit));
874
1338
  }
875
- if (params?.offset) {
1339
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
876
1340
  searchParams.set("offset", String(params.offset));
877
1341
  }
878
1342
  if (params?.resourceId) {
879
1343
  searchParams.set("resourceId", params.resourceId);
880
1344
  }
881
1345
  if (searchParams.size) {
882
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs?${searchParams}`);
1346
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
883
1347
  } else {
884
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
1348
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
885
1349
  }
886
1350
  }
887
1351
  /**
888
- * Creates a new vNext workflow run
1352
+ * Retrieves a specific workflow run by its ID
1353
+ * @param runId - The ID of the workflow run to retrieve
1354
+ * @returns Promise containing the workflow run details
1355
+ */
1356
+ runById(runId) {
1357
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1358
+ }
1359
+ /**
1360
+ * Retrieves the execution result for a specific workflow run by its ID
1361
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1362
+ * @returns Promise containing the workflow run execution result
1363
+ */
1364
+ runExecutionResult(runId) {
1365
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1366
+ }
1367
+ /**
1368
+ * Cancels a specific workflow run by its ID
1369
+ * @param runId - The ID of the workflow run to cancel
1370
+ * @returns Promise containing a success message
1371
+ */
1372
+ cancelRun(runId) {
1373
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1374
+ method: "POST"
1375
+ });
1376
+ }
1377
+ /**
1378
+ * Sends an event to a specific workflow run by its ID
1379
+ * @param params - Object containing the runId, event and data
1380
+ * @returns Promise containing a success message
1381
+ */
1382
+ sendRunEvent(params) {
1383
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1384
+ method: "POST",
1385
+ body: { event: params.event, data: params.data }
1386
+ });
1387
+ }
1388
+ /**
1389
+ * Creates a new workflow run
889
1390
  * @param params - Optional object containing the optional runId
890
1391
  * @returns Promise containing the runId of the created run
891
1392
  */
@@ -894,24 +1395,24 @@ var VNextWorkflow = class extends BaseResource {
894
1395
  if (!!params?.runId) {
895
1396
  searchParams.set("runId", params.runId);
896
1397
  }
897
- return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
1398
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
898
1399
  method: "POST"
899
1400
  });
900
1401
  }
901
1402
  /**
902
- * Starts a vNext workflow run synchronously without waiting for the workflow to complete
1403
+ * Starts a workflow run synchronously without waiting for the workflow to complete
903
1404
  * @param params - Object containing the runId, inputData and runtimeContext
904
1405
  * @returns Promise containing success message
905
1406
  */
906
1407
  start(params) {
907
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
908
- return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
1408
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1409
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
909
1410
  method: "POST",
910
1411
  body: { inputData: params?.inputData, runtimeContext }
911
1412
  });
912
1413
  }
913
1414
  /**
914
- * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
1415
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
915
1416
  * @param params - Object containing the runId, step, resumeData and runtimeContext
916
1417
  * @returns Promise containing success message
917
1418
  */
@@ -921,8 +1422,8 @@ var VNextWorkflow = class extends BaseResource {
921
1422
  resumeData,
922
1423
  ...rest
923
1424
  }) {
924
- const runtimeContext = rest.runtimeContext ? Object.fromEntries(rest.runtimeContext.entries()) : void 0;
925
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
1425
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1426
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
926
1427
  method: "POST",
927
1428
  stream: true,
928
1429
  body: {
@@ -933,29 +1434,76 @@ var VNextWorkflow = class extends BaseResource {
933
1434
  });
934
1435
  }
935
1436
  /**
936
- * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
1437
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
937
1438
  * @param params - Object containing the optional runId, inputData and runtimeContext
938
- * @returns Promise containing the vNext workflow execution results
1439
+ * @returns Promise containing the workflow execution results
939
1440
  */
940
1441
  startAsync(params) {
941
1442
  const searchParams = new URLSearchParams();
942
1443
  if (!!params?.runId) {
943
1444
  searchParams.set("runId", params.runId);
944
1445
  }
945
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
946
- return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
1446
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1447
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
947
1448
  method: "POST",
948
1449
  body: { inputData: params.inputData, runtimeContext }
949
1450
  });
950
1451
  }
951
1452
  /**
952
- * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
1453
+ * Starts a workflow run and returns a stream
1454
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1455
+ * @returns Promise containing the workflow execution results
1456
+ */
1457
+ async stream(params) {
1458
+ const searchParams = new URLSearchParams();
1459
+ if (!!params?.runId) {
1460
+ searchParams.set("runId", params.runId);
1461
+ }
1462
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1463
+ const response = await this.request(
1464
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1465
+ {
1466
+ method: "POST",
1467
+ body: { inputData: params.inputData, runtimeContext },
1468
+ stream: true
1469
+ }
1470
+ );
1471
+ if (!response.ok) {
1472
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1473
+ }
1474
+ if (!response.body) {
1475
+ throw new Error("Response body is null");
1476
+ }
1477
+ const transformStream = new TransformStream({
1478
+ start() {
1479
+ },
1480
+ async transform(chunk, controller) {
1481
+ try {
1482
+ const decoded = new TextDecoder().decode(chunk);
1483
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1484
+ for (const chunk2 of chunks) {
1485
+ if (chunk2) {
1486
+ try {
1487
+ const parsedChunk = JSON.parse(chunk2);
1488
+ controller.enqueue(parsedChunk);
1489
+ } catch {
1490
+ }
1491
+ }
1492
+ }
1493
+ } catch {
1494
+ }
1495
+ }
1496
+ });
1497
+ return response.body.pipeThrough(transformStream);
1498
+ }
1499
+ /**
1500
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
953
1501
  * @param params - Object containing the runId, step, resumeData and runtimeContext
954
- * @returns Promise containing the vNext workflow resume results
1502
+ * @returns Promise containing the workflow resume results
955
1503
  */
956
1504
  resumeAsync(params) {
957
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
958
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
1505
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1506
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
959
1507
  method: "POST",
960
1508
  body: {
961
1509
  step: params.step,
@@ -965,24 +1513,51 @@ var VNextWorkflow = class extends BaseResource {
965
1513
  });
966
1514
  }
967
1515
  /**
968
- * Watches vNext workflow transitions in real-time
1516
+ * Watches workflow transitions in real-time
969
1517
  * @param runId - Optional run ID to filter the watch stream
970
- * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
1518
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
971
1519
  */
972
1520
  async watch({ runId }, onRecord) {
973
- const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
1521
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
974
1522
  stream: true
975
1523
  });
976
1524
  if (!response.ok) {
977
- throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
1525
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
978
1526
  }
979
1527
  if (!response.body) {
980
1528
  throw new Error("Response body is null");
981
1529
  }
982
1530
  for await (const record of this.streamProcessor(response.body)) {
983
- onRecord(record);
1531
+ if (typeof record === "string") {
1532
+ onRecord(JSON.parse(record));
1533
+ } else {
1534
+ onRecord(record);
1535
+ }
984
1536
  }
985
1537
  }
1538
+ /**
1539
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1540
+ * serializing each as JSON and separating them with the record separator (\x1E).
1541
+ *
1542
+ * @param records - An iterable or async iterable of objects to stream
1543
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1544
+ */
1545
+ static createRecordStream(records) {
1546
+ const encoder = new TextEncoder();
1547
+ return new ReadableStream({
1548
+ async start(controller) {
1549
+ try {
1550
+ for await (const record of records) {
1551
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1552
+ controller.enqueue(encoder.encode(json));
1553
+ }
1554
+ controller.close();
1555
+ } catch (err) {
1556
+ controller.error(err);
1557
+ }
1558
+ }
1559
+ });
1560
+ }
986
1561
  };
987
1562
 
988
1563
  // src/resources/a2a.ts
@@ -1059,6 +1634,226 @@ var A2A = class extends BaseResource {
1059
1634
  }
1060
1635
  };
1061
1636
 
1637
+ // src/resources/mcp-tool.ts
1638
+ var MCPTool = class extends BaseResource {
1639
+ serverId;
1640
+ toolId;
1641
+ constructor(options, serverId, toolId) {
1642
+ super(options);
1643
+ this.serverId = serverId;
1644
+ this.toolId = toolId;
1645
+ }
1646
+ /**
1647
+ * Retrieves details about this specific tool from the MCP server.
1648
+ * @returns Promise containing the tool's information (name, description, schema).
1649
+ */
1650
+ details() {
1651
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1652
+ }
1653
+ /**
1654
+ * Executes this specific tool on the MCP server.
1655
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1656
+ * @returns Promise containing the result of the tool execution.
1657
+ */
1658
+ execute(params) {
1659
+ const body = {};
1660
+ if (params.data !== void 0) body.data = params.data;
1661
+ if (params.runtimeContext !== void 0) {
1662
+ body.runtimeContext = params.runtimeContext;
1663
+ }
1664
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1665
+ method: "POST",
1666
+ body: Object.keys(body).length > 0 ? body : void 0
1667
+ });
1668
+ }
1669
+ };
1670
+
1671
+ // src/resources/network-memory-thread.ts
1672
+ var NetworkMemoryThread = class extends BaseResource {
1673
+ constructor(options, threadId, networkId) {
1674
+ super(options);
1675
+ this.threadId = threadId;
1676
+ this.networkId = networkId;
1677
+ }
1678
+ /**
1679
+ * Retrieves the memory thread details
1680
+ * @returns Promise containing thread details including title and metadata
1681
+ */
1682
+ get() {
1683
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1684
+ }
1685
+ /**
1686
+ * Updates the memory thread properties
1687
+ * @param params - Update parameters including title and metadata
1688
+ * @returns Promise containing updated thread details
1689
+ */
1690
+ update(params) {
1691
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1692
+ method: "PATCH",
1693
+ body: params
1694
+ });
1695
+ }
1696
+ /**
1697
+ * Deletes the memory thread
1698
+ * @returns Promise containing deletion result
1699
+ */
1700
+ delete() {
1701
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1702
+ method: "DELETE"
1703
+ });
1704
+ }
1705
+ /**
1706
+ * Retrieves messages associated with the thread
1707
+ * @param params - Optional parameters including limit for number of messages to retrieve
1708
+ * @returns Promise containing thread messages and UI messages
1709
+ */
1710
+ getMessages(params) {
1711
+ const query = new URLSearchParams({
1712
+ networkId: this.networkId,
1713
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1714
+ });
1715
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1716
+ }
1717
+ };
1718
+
1719
+ // src/resources/vNextNetwork.ts
1720
+ var RECORD_SEPARATOR3 = "";
1721
+ var VNextNetwork = class extends BaseResource {
1722
+ constructor(options, networkId) {
1723
+ super(options);
1724
+ this.networkId = networkId;
1725
+ }
1726
+ /**
1727
+ * Retrieves details about the network
1728
+ * @returns Promise containing vNext network details
1729
+ */
1730
+ details() {
1731
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1732
+ }
1733
+ /**
1734
+ * Generates a response from the v-next network
1735
+ * @param params - Generation parameters including message
1736
+ * @returns Promise containing the generated response
1737
+ */
1738
+ generate(params) {
1739
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1740
+ method: "POST",
1741
+ body: {
1742
+ ...params,
1743
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1744
+ }
1745
+ });
1746
+ }
1747
+ /**
1748
+ * Generates a response from the v-next network using multiple primitives
1749
+ * @param params - Generation parameters including message
1750
+ * @returns Promise containing the generated response
1751
+ */
1752
+ loop(params) {
1753
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1754
+ method: "POST",
1755
+ body: {
1756
+ ...params,
1757
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1758
+ }
1759
+ });
1760
+ }
1761
+ async *streamProcessor(stream) {
1762
+ const reader = stream.getReader();
1763
+ let doneReading = false;
1764
+ let buffer = "";
1765
+ try {
1766
+ while (!doneReading) {
1767
+ const { done, value } = await reader.read();
1768
+ doneReading = done;
1769
+ if (done && !value) continue;
1770
+ try {
1771
+ const decoded = value ? new TextDecoder().decode(value) : "";
1772
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1773
+ buffer = chunks.pop() || "";
1774
+ for (const chunk of chunks) {
1775
+ if (chunk) {
1776
+ if (typeof chunk === "string") {
1777
+ try {
1778
+ const parsedChunk = JSON.parse(chunk);
1779
+ yield parsedChunk;
1780
+ } catch {
1781
+ }
1782
+ }
1783
+ }
1784
+ }
1785
+ } catch {
1786
+ }
1787
+ }
1788
+ if (buffer) {
1789
+ try {
1790
+ yield JSON.parse(buffer);
1791
+ } catch {
1792
+ }
1793
+ }
1794
+ } finally {
1795
+ reader.cancel().catch(() => {
1796
+ });
1797
+ }
1798
+ }
1799
+ /**
1800
+ * Streams a response from the v-next network
1801
+ * @param params - Stream parameters including message
1802
+ * @returns Promise containing the results
1803
+ */
1804
+ async stream(params, onRecord) {
1805
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1806
+ method: "POST",
1807
+ body: {
1808
+ ...params,
1809
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1810
+ },
1811
+ stream: true
1812
+ });
1813
+ if (!response.ok) {
1814
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1815
+ }
1816
+ if (!response.body) {
1817
+ throw new Error("Response body is null");
1818
+ }
1819
+ for await (const record of this.streamProcessor(response.body)) {
1820
+ if (typeof record === "string") {
1821
+ onRecord(JSON.parse(record));
1822
+ } else {
1823
+ onRecord(record);
1824
+ }
1825
+ }
1826
+ }
1827
+ /**
1828
+ * Streams a response from the v-next network loop
1829
+ * @param params - Stream parameters including message
1830
+ * @returns Promise containing the results
1831
+ */
1832
+ async loopStream(params, onRecord) {
1833
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1834
+ method: "POST",
1835
+ body: {
1836
+ ...params,
1837
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1838
+ },
1839
+ stream: true
1840
+ });
1841
+ if (!response.ok) {
1842
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1843
+ }
1844
+ if (!response.body) {
1845
+ throw new Error("Response body is null");
1846
+ }
1847
+ for await (const record of this.streamProcessor(response.body)) {
1848
+ if (typeof record === "string") {
1849
+ onRecord(JSON.parse(record));
1850
+ } else {
1851
+ onRecord(record);
1852
+ }
1853
+ }
1854
+ }
1855
+ };
1856
+
1062
1857
  // src/client.ts
1063
1858
  var MastraClient = class extends BaseResource {
1064
1859
  constructor(options) {
@@ -1136,6 +1931,48 @@ var MastraClient = class extends BaseResource {
1136
1931
  getMemoryStatus(agentId) {
1137
1932
  return this.request(`/api/memory/status?agentId=${agentId}`);
1138
1933
  }
1934
+ /**
1935
+ * Retrieves memory threads for a resource
1936
+ * @param params - Parameters containing the resource ID
1937
+ * @returns Promise containing array of memory threads
1938
+ */
1939
+ getNetworkMemoryThreads(params) {
1940
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1941
+ }
1942
+ /**
1943
+ * Creates a new memory thread
1944
+ * @param params - Parameters for creating the memory thread
1945
+ * @returns Promise containing the created memory thread
1946
+ */
1947
+ createNetworkMemoryThread(params) {
1948
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1949
+ }
1950
+ /**
1951
+ * Gets a memory thread instance by ID
1952
+ * @param threadId - ID of the memory thread to retrieve
1953
+ * @returns MemoryThread instance
1954
+ */
1955
+ getNetworkMemoryThread(threadId, networkId) {
1956
+ return new NetworkMemoryThread(this.options, threadId, networkId);
1957
+ }
1958
+ /**
1959
+ * Saves messages to memory
1960
+ * @param params - Parameters containing messages to save
1961
+ * @returns Promise containing the saved messages
1962
+ */
1963
+ saveNetworkMessageToMemory(params) {
1964
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
1965
+ method: "POST",
1966
+ body: params
1967
+ });
1968
+ }
1969
+ /**
1970
+ * Gets the status of the memory system
1971
+ * @returns Promise containing memory system status
1972
+ */
1973
+ getNetworkMemoryStatus(networkId) {
1974
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
1975
+ }
1139
1976
  /**
1140
1977
  * Retrieves all available tools
1141
1978
  * @returns Promise containing map of tool IDs to tool details
@@ -1149,7 +1986,22 @@ var MastraClient = class extends BaseResource {
1149
1986
  * @returns Tool instance
1150
1987
  */
1151
1988
  getTool(toolId) {
1152
- return new Tool(this.options, toolId);
1989
+ return new Tool2(this.options, toolId);
1990
+ }
1991
+ /**
1992
+ * Retrieves all available legacy workflows
1993
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1994
+ */
1995
+ getLegacyWorkflows() {
1996
+ return this.request("/api/workflows/legacy");
1997
+ }
1998
+ /**
1999
+ * Gets a legacy workflow instance by ID
2000
+ * @param workflowId - ID of the legacy workflow to retrieve
2001
+ * @returns Legacy Workflow instance
2002
+ */
2003
+ getLegacyWorkflow(workflowId) {
2004
+ return new LegacyWorkflow(this.options, workflowId);
1153
2005
  }
1154
2006
  /**
1155
2007
  * Retrieves all available workflows
@@ -1166,21 +2018,6 @@ var MastraClient = class extends BaseResource {
1166
2018
  getWorkflow(workflowId) {
1167
2019
  return new Workflow(this.options, workflowId);
1168
2020
  }
1169
- /**
1170
- * Retrieves all available vNext workflows
1171
- * @returns Promise containing map of vNext workflow IDs to vNext workflow details
1172
- */
1173
- getVNextWorkflows() {
1174
- return this.request("/api/workflows/v-next");
1175
- }
1176
- /**
1177
- * Gets a vNext workflow instance by ID
1178
- * @param workflowId - ID of the vNext workflow to retrieve
1179
- * @returns vNext Workflow instance
1180
- */
1181
- getVNextWorkflow(workflowId) {
1182
- return new VNextWorkflow(this.options, workflowId);
1183
- }
1184
2021
  /**
1185
2022
  * Gets a vector instance by name
1186
2023
  * @param vectorName - Name of the vector to retrieve
@@ -1195,7 +2032,41 @@ var MastraClient = class extends BaseResource {
1195
2032
  * @returns Promise containing array of log messages
1196
2033
  */
1197
2034
  getLogs(params) {
1198
- return this.request(`/api/logs?transportId=${params.transportId}`);
2035
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2036
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2037
+ const searchParams = new URLSearchParams();
2038
+ if (transportId) {
2039
+ searchParams.set("transportId", transportId);
2040
+ }
2041
+ if (fromDate) {
2042
+ searchParams.set("fromDate", fromDate.toISOString());
2043
+ }
2044
+ if (toDate) {
2045
+ searchParams.set("toDate", toDate.toISOString());
2046
+ }
2047
+ if (logLevel) {
2048
+ searchParams.set("logLevel", logLevel);
2049
+ }
2050
+ if (page) {
2051
+ searchParams.set("page", String(page));
2052
+ }
2053
+ if (perPage) {
2054
+ searchParams.set("perPage", String(perPage));
2055
+ }
2056
+ if (_filters) {
2057
+ if (Array.isArray(_filters)) {
2058
+ for (const filter of _filters) {
2059
+ searchParams.append("filters", filter);
2060
+ }
2061
+ } else {
2062
+ searchParams.set("filters", _filters);
2063
+ }
2064
+ }
2065
+ if (searchParams.size) {
2066
+ return this.request(`/api/logs?${searchParams}`);
2067
+ } else {
2068
+ return this.request(`/api/logs`);
2069
+ }
1199
2070
  }
1200
2071
  /**
1201
2072
  * Gets logs for a specific run
@@ -1203,7 +2074,44 @@ var MastraClient = class extends BaseResource {
1203
2074
  * @returns Promise containing array of log messages
1204
2075
  */
1205
2076
  getLogForRun(params) {
1206
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2077
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2078
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2079
+ const searchParams = new URLSearchParams();
2080
+ if (runId) {
2081
+ searchParams.set("runId", runId);
2082
+ }
2083
+ if (transportId) {
2084
+ searchParams.set("transportId", transportId);
2085
+ }
2086
+ if (fromDate) {
2087
+ searchParams.set("fromDate", fromDate.toISOString());
2088
+ }
2089
+ if (toDate) {
2090
+ searchParams.set("toDate", toDate.toISOString());
2091
+ }
2092
+ if (logLevel) {
2093
+ searchParams.set("logLevel", logLevel);
2094
+ }
2095
+ if (page) {
2096
+ searchParams.set("page", String(page));
2097
+ }
2098
+ if (perPage) {
2099
+ searchParams.set("perPage", String(perPage));
2100
+ }
2101
+ if (_filters) {
2102
+ if (Array.isArray(_filters)) {
2103
+ for (const filter of _filters) {
2104
+ searchParams.append("filters", filter);
2105
+ }
2106
+ } else {
2107
+ searchParams.set("filters", _filters);
2108
+ }
2109
+ }
2110
+ if (searchParams.size) {
2111
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2112
+ } else {
2113
+ return this.request(`/api/logs/${runId}`);
2114
+ }
1207
2115
  }
1208
2116
  /**
1209
2117
  * List of all log transports
@@ -1261,6 +2169,13 @@ var MastraClient = class extends BaseResource {
1261
2169
  getNetworks() {
1262
2170
  return this.request("/api/networks");
1263
2171
  }
2172
+ /**
2173
+ * Retrieves all available vNext networks
2174
+ * @returns Promise containing map of vNext network IDs to vNext network details
2175
+ */
2176
+ getVNextNetworks() {
2177
+ return this.request("/api/networks/v-next");
2178
+ }
1264
2179
  /**
1265
2180
  * Gets a network instance by ID
1266
2181
  * @param networkId - ID of the network to retrieve
@@ -1269,6 +2184,62 @@ var MastraClient = class extends BaseResource {
1269
2184
  getNetwork(networkId) {
1270
2185
  return new Network(this.options, networkId);
1271
2186
  }
2187
+ /**
2188
+ * Gets a vNext network instance by ID
2189
+ * @param networkId - ID of the vNext network to retrieve
2190
+ * @returns vNext Network instance
2191
+ */
2192
+ getVNextNetwork(networkId) {
2193
+ return new VNextNetwork(this.options, networkId);
2194
+ }
2195
+ /**
2196
+ * Retrieves a list of available MCP servers.
2197
+ * @param params - Optional parameters for pagination (limit, offset).
2198
+ * @returns Promise containing the list of MCP servers and pagination info.
2199
+ */
2200
+ getMcpServers(params) {
2201
+ const searchParams = new URLSearchParams();
2202
+ if (params?.limit !== void 0) {
2203
+ searchParams.set("limit", String(params.limit));
2204
+ }
2205
+ if (params?.offset !== void 0) {
2206
+ searchParams.set("offset", String(params.offset));
2207
+ }
2208
+ const queryString = searchParams.toString();
2209
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
2210
+ }
2211
+ /**
2212
+ * Retrieves detailed information for a specific MCP server.
2213
+ * @param serverId - The ID of the MCP server to retrieve.
2214
+ * @param params - Optional parameters, e.g., specific version.
2215
+ * @returns Promise containing the detailed MCP server information.
2216
+ */
2217
+ getMcpServerDetails(serverId, params) {
2218
+ const searchParams = new URLSearchParams();
2219
+ if (params?.version) {
2220
+ searchParams.set("version", params.version);
2221
+ }
2222
+ const queryString = searchParams.toString();
2223
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
2224
+ }
2225
+ /**
2226
+ * Retrieves a list of tools for a specific MCP server.
2227
+ * @param serverId - The ID of the MCP server.
2228
+ * @returns Promise containing the list of tools.
2229
+ */
2230
+ getMcpServerTools(serverId) {
2231
+ return this.request(`/api/mcp/${serverId}/tools`);
2232
+ }
2233
+ /**
2234
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
2235
+ * This instance can then be used to fetch details or execute the tool.
2236
+ * @param serverId - The ID of the MCP server.
2237
+ * @param toolId - The ID of the tool.
2238
+ * @returns MCPTool instance.
2239
+ */
2240
+ getMcpServerTool(serverId, toolId) {
2241
+ return new MCPTool(this.options, serverId, toolId);
2242
+ }
1272
2243
  /**
1273
2244
  * Gets an A2A client for interacting with an agent via the A2A protocol
1274
2245
  * @param agentId - ID of the agent to interact with
@@ -1277,6 +2248,41 @@ var MastraClient = class extends BaseResource {
1277
2248
  getA2A(agentId) {
1278
2249
  return new A2A(this.options, agentId);
1279
2250
  }
2251
+ /**
2252
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2253
+ * @param agentId - ID of the agent.
2254
+ * @param threadId - ID of the thread.
2255
+ * @param resourceId - Optional ID of the resource.
2256
+ * @returns Working memory for the specified thread or resource.
2257
+ */
2258
+ getWorkingMemory({
2259
+ agentId,
2260
+ threadId,
2261
+ resourceId
2262
+ }) {
2263
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2264
+ }
2265
+ /**
2266
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2267
+ * @param agentId - ID of the agent.
2268
+ * @param threadId - ID of the thread.
2269
+ * @param workingMemory - The new working memory content.
2270
+ * @param resourceId - Optional ID of the resource.
2271
+ */
2272
+ updateWorkingMemory({
2273
+ agentId,
2274
+ threadId,
2275
+ workingMemory,
2276
+ resourceId
2277
+ }) {
2278
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2279
+ method: "POST",
2280
+ body: {
2281
+ workingMemory,
2282
+ resourceId
2283
+ }
2284
+ });
2285
+ }
1280
2286
  };
1281
2287
 
1282
2288
  export { MastraClient };