@mastra/client-js 0.10.6-alpha.2 → 0.10.6-alpha.4

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,6 +1,6 @@
1
1
  import { AbstractAgent, EventType } from '@ag-ui/client';
2
2
  import { Observable } from 'rxjs';
3
- import { processDataStream } from '@ai-sdk/ui-utils';
3
+ import { processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
4
4
  import { ZodSchema } from 'zod';
5
5
  import originalZodToJsonSchema from 'zod-to-json-schema';
6
6
  import { isVercelTool } from '@mastra/core/tools';
@@ -293,8 +293,6 @@ function parseClientRuntimeContext(runtimeContext) {
293
293
  }
294
294
  return void 0;
295
295
  }
296
-
297
- // src/resources/agent.ts
298
296
  var AgentVoice = class extends BaseResource {
299
297
  constructor(options, agentId) {
300
298
  super(options);
@@ -363,7 +361,7 @@ var Agent = class extends BaseResource {
363
361
  details() {
364
362
  return this.request(`/api/agents/${this.agentId}`);
365
363
  }
366
- generate(params) {
364
+ async generate(params) {
367
365
  const processedParams = {
368
366
  ...params,
369
367
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -371,10 +369,310 @@ var Agent = class extends BaseResource {
371
369
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
372
370
  clientTools: processClientTools(params.clientTools)
373
371
  };
374
- return this.request(`/api/agents/${this.agentId}/generate`, {
372
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
373
+ const response = await this.request(`/api/agents/${this.agentId}/generate`, {
375
374
  method: "POST",
376
375
  body: processedParams
377
376
  });
377
+ if (response.finishReason === "tool-calls") {
378
+ for (const toolCall of response.toolCalls) {
379
+ const clientTool = params.clientTools?.[toolCall.toolName];
380
+ if (clientTool && clientTool.execute) {
381
+ const result = await clientTool.execute(
382
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
383
+ {
384
+ messages: response.messages,
385
+ toolCallId: toolCall?.toolCallId
386
+ }
387
+ );
388
+ const updatedMessages = [
389
+ {
390
+ role: "user",
391
+ content: params.messages
392
+ },
393
+ ...response.response.messages,
394
+ {
395
+ role: "tool",
396
+ content: [
397
+ {
398
+ type: "tool-result",
399
+ toolCallId: toolCall.toolCallId,
400
+ toolName: toolCall.toolName,
401
+ result
402
+ }
403
+ ]
404
+ }
405
+ ];
406
+ return this.generate({
407
+ ...params,
408
+ messages: updatedMessages
409
+ });
410
+ }
411
+ }
412
+ }
413
+ return response;
414
+ }
415
+ async processChatResponse({
416
+ stream,
417
+ update,
418
+ onToolCall,
419
+ onFinish,
420
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
421
+ lastMessage
422
+ }) {
423
+ const replaceLastMessage = lastMessage?.role === "assistant";
424
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
425
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
426
+ return Math.max(max, toolInvocation.step ?? 0);
427
+ }, 0) ?? 0) : 0;
428
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
429
+ id: crypto.randomUUID(),
430
+ createdAt: getCurrentDate(),
431
+ role: "assistant",
432
+ content: "",
433
+ parts: []
434
+ };
435
+ let currentTextPart = void 0;
436
+ let currentReasoningPart = void 0;
437
+ let currentReasoningTextDetail = void 0;
438
+ function updateToolInvocationPart(toolCallId, invocation) {
439
+ const part = message.parts.find(
440
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
441
+ );
442
+ if (part != null) {
443
+ part.toolInvocation = invocation;
444
+ } else {
445
+ message.parts.push({
446
+ type: "tool-invocation",
447
+ toolInvocation: invocation
448
+ });
449
+ }
450
+ }
451
+ const data = [];
452
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
453
+ const partialToolCalls = {};
454
+ let usage = {
455
+ completionTokens: NaN,
456
+ promptTokens: NaN,
457
+ totalTokens: NaN
458
+ };
459
+ let finishReason = "unknown";
460
+ function execUpdate() {
461
+ const copiedData = [...data];
462
+ if (messageAnnotations?.length) {
463
+ message.annotations = messageAnnotations;
464
+ }
465
+ const copiedMessage = {
466
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
467
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
468
+ ...structuredClone(message),
469
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
470
+ // hashing approach by default to detect changes, but it only works for shallow
471
+ // changes. This is why we need to add a revision id to ensure that the message
472
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
473
+ // forwarded to rendering):
474
+ revisionId: crypto.randomUUID()
475
+ };
476
+ update({
477
+ message: copiedMessage,
478
+ data: copiedData,
479
+ replaceLastMessage
480
+ });
481
+ }
482
+ await processDataStream({
483
+ stream,
484
+ onTextPart(value) {
485
+ if (currentTextPart == null) {
486
+ currentTextPart = {
487
+ type: "text",
488
+ text: value
489
+ };
490
+ message.parts.push(currentTextPart);
491
+ } else {
492
+ currentTextPart.text += value;
493
+ }
494
+ message.content += value;
495
+ execUpdate();
496
+ },
497
+ onReasoningPart(value) {
498
+ if (currentReasoningTextDetail == null) {
499
+ currentReasoningTextDetail = { type: "text", text: value };
500
+ if (currentReasoningPart != null) {
501
+ currentReasoningPart.details.push(currentReasoningTextDetail);
502
+ }
503
+ } else {
504
+ currentReasoningTextDetail.text += value;
505
+ }
506
+ if (currentReasoningPart == null) {
507
+ currentReasoningPart = {
508
+ type: "reasoning",
509
+ reasoning: value,
510
+ details: [currentReasoningTextDetail]
511
+ };
512
+ message.parts.push(currentReasoningPart);
513
+ } else {
514
+ currentReasoningPart.reasoning += value;
515
+ }
516
+ message.reasoning = (message.reasoning ?? "") + value;
517
+ execUpdate();
518
+ },
519
+ onReasoningSignaturePart(value) {
520
+ if (currentReasoningTextDetail != null) {
521
+ currentReasoningTextDetail.signature = value.signature;
522
+ }
523
+ },
524
+ onRedactedReasoningPart(value) {
525
+ if (currentReasoningPart == null) {
526
+ currentReasoningPart = {
527
+ type: "reasoning",
528
+ reasoning: "",
529
+ details: []
530
+ };
531
+ message.parts.push(currentReasoningPart);
532
+ }
533
+ currentReasoningPart.details.push({
534
+ type: "redacted",
535
+ data: value.data
536
+ });
537
+ currentReasoningTextDetail = void 0;
538
+ execUpdate();
539
+ },
540
+ onFilePart(value) {
541
+ message.parts.push({
542
+ type: "file",
543
+ mimeType: value.mimeType,
544
+ data: value.data
545
+ });
546
+ execUpdate();
547
+ },
548
+ onSourcePart(value) {
549
+ message.parts.push({
550
+ type: "source",
551
+ source: value
552
+ });
553
+ execUpdate();
554
+ },
555
+ onToolCallStreamingStartPart(value) {
556
+ if (message.toolInvocations == null) {
557
+ message.toolInvocations = [];
558
+ }
559
+ partialToolCalls[value.toolCallId] = {
560
+ text: "",
561
+ step,
562
+ toolName: value.toolName,
563
+ index: message.toolInvocations.length
564
+ };
565
+ const invocation = {
566
+ state: "partial-call",
567
+ step,
568
+ toolCallId: value.toolCallId,
569
+ toolName: value.toolName,
570
+ args: void 0
571
+ };
572
+ message.toolInvocations.push(invocation);
573
+ updateToolInvocationPart(value.toolCallId, invocation);
574
+ execUpdate();
575
+ },
576
+ onToolCallDeltaPart(value) {
577
+ const partialToolCall = partialToolCalls[value.toolCallId];
578
+ partialToolCall.text += value.argsTextDelta;
579
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
580
+ const invocation = {
581
+ state: "partial-call",
582
+ step: partialToolCall.step,
583
+ toolCallId: value.toolCallId,
584
+ toolName: partialToolCall.toolName,
585
+ args: partialArgs
586
+ };
587
+ message.toolInvocations[partialToolCall.index] = invocation;
588
+ updateToolInvocationPart(value.toolCallId, invocation);
589
+ execUpdate();
590
+ },
591
+ async onToolCallPart(value) {
592
+ const invocation = {
593
+ state: "call",
594
+ step,
595
+ ...value
596
+ };
597
+ if (partialToolCalls[value.toolCallId] != null) {
598
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
599
+ } else {
600
+ if (message.toolInvocations == null) {
601
+ message.toolInvocations = [];
602
+ }
603
+ message.toolInvocations.push(invocation);
604
+ }
605
+ updateToolInvocationPart(value.toolCallId, invocation);
606
+ execUpdate();
607
+ if (onToolCall) {
608
+ const result = await onToolCall({ toolCall: value });
609
+ if (result != null) {
610
+ const invocation2 = {
611
+ state: "result",
612
+ step,
613
+ ...value,
614
+ result
615
+ };
616
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
617
+ updateToolInvocationPart(value.toolCallId, invocation2);
618
+ execUpdate();
619
+ }
620
+ }
621
+ },
622
+ onToolResultPart(value) {
623
+ const toolInvocations = message.toolInvocations;
624
+ if (toolInvocations == null) {
625
+ throw new Error("tool_result must be preceded by a tool_call");
626
+ }
627
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
628
+ if (toolInvocationIndex === -1) {
629
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
630
+ }
631
+ const invocation = {
632
+ ...toolInvocations[toolInvocationIndex],
633
+ state: "result",
634
+ ...value
635
+ };
636
+ toolInvocations[toolInvocationIndex] = invocation;
637
+ updateToolInvocationPart(value.toolCallId, invocation);
638
+ execUpdate();
639
+ },
640
+ onDataPart(value) {
641
+ data.push(...value);
642
+ execUpdate();
643
+ },
644
+ onMessageAnnotationsPart(value) {
645
+ if (messageAnnotations == null) {
646
+ messageAnnotations = [...value];
647
+ } else {
648
+ messageAnnotations.push(...value);
649
+ }
650
+ execUpdate();
651
+ },
652
+ onFinishStepPart(value) {
653
+ step += 1;
654
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
655
+ currentReasoningPart = void 0;
656
+ currentReasoningTextDetail = void 0;
657
+ },
658
+ onStartStepPart(value) {
659
+ if (!replaceLastMessage) {
660
+ message.id = value.messageId;
661
+ }
662
+ message.parts.push({ type: "step-start" });
663
+ execUpdate();
664
+ },
665
+ onFinishMessagePart(value) {
666
+ finishReason = value.finishReason;
667
+ if (value.usage != null) {
668
+ usage = value.usage;
669
+ }
670
+ },
671
+ onErrorPart(error) {
672
+ throw new Error(error);
673
+ }
674
+ });
675
+ onFinish?.({ message, finishReason, usage });
378
676
  }
379
677
  /**
380
678
  * Streams a response from the agent
@@ -389,6 +687,25 @@ var Agent = class extends BaseResource {
389
687
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
390
688
  clientTools: processClientTools(params.clientTools)
391
689
  };
690
+ const { readable, writable } = new TransformStream();
691
+ const response = await this.processStreamResponse(processedParams, writable);
692
+ const streamResponse = new Response(readable, {
693
+ status: response.status,
694
+ statusText: response.statusText,
695
+ headers: response.headers
696
+ });
697
+ streamResponse.processDataStream = async (options = {}) => {
698
+ await processDataStream({
699
+ stream: readable,
700
+ ...options
701
+ });
702
+ };
703
+ return streamResponse;
704
+ }
705
+ /**
706
+ * Processes the stream response and handles tool calls
707
+ */
708
+ async processStreamResponse(processedParams, writable) {
392
709
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
393
710
  method: "POST",
394
711
  body: processedParams,
@@ -397,12 +714,81 @@ var Agent = class extends BaseResource {
397
714
  if (!response.body) {
398
715
  throw new Error("No response body");
399
716
  }
400
- response.processDataStream = async (options = {}) => {
401
- await processDataStream({
402
- stream: response.body,
403
- ...options
717
+ try {
718
+ let toolCalls = [];
719
+ let finishReasonToolCalls = false;
720
+ let messages = [];
721
+ let hasProcessedToolCalls = false;
722
+ response.clone().body.pipeTo(writable, {
723
+ preventClose: true
404
724
  });
405
- };
725
+ await this.processChatResponse({
726
+ stream: response.clone().body,
727
+ update: ({ message }) => {
728
+ messages.push(message);
729
+ },
730
+ onFinish: ({ finishReason, message }) => {
731
+ if (finishReason === "tool-calls") {
732
+ finishReasonToolCalls = true;
733
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
734
+ if (toolCall) {
735
+ toolCalls.push(toolCall);
736
+ }
737
+ }
738
+ },
739
+ lastMessage: void 0
740
+ });
741
+ if (finishReasonToolCalls && !hasProcessedToolCalls) {
742
+ hasProcessedToolCalls = true;
743
+ for (const toolCall of toolCalls) {
744
+ const clientTool = processedParams.clientTools?.[toolCall.toolName];
745
+ if (clientTool && clientTool.execute) {
746
+ const result = await clientTool.execute(
747
+ {
748
+ context: toolCall?.args,
749
+ runId: processedParams.runId,
750
+ resourceId: processedParams.resourceId,
751
+ threadId: processedParams.threadId,
752
+ runtimeContext: processedParams.runtimeContext
753
+ },
754
+ {
755
+ messages: response.messages,
756
+ toolCallId: toolCall?.toolCallId
757
+ }
758
+ );
759
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
760
+ const toolInvocationPart = lastMessage?.parts?.find(
761
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall.toolCallId
762
+ );
763
+ if (toolInvocationPart) {
764
+ toolInvocationPart.toolInvocation = {
765
+ ...toolInvocationPart.toolInvocation,
766
+ state: "result",
767
+ result
768
+ };
769
+ }
770
+ const toolInvocation = lastMessage?.toolInvocations?.find(
771
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall.toolCallId
772
+ );
773
+ if (toolInvocation) {
774
+ toolInvocation.state = "result";
775
+ toolInvocation.result = result;
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
+ }
789
+ } catch (error) {
790
+ console.error("Error processing stream response:", error);
791
+ }
406
792
  return response;
407
793
  }
408
794
  /**
@@ -797,7 +1183,7 @@ var LegacyWorkflow = class extends BaseResource {
797
1183
  };
798
1184
 
799
1185
  // src/resources/tool.ts
800
- var Tool = class extends BaseResource {
1186
+ var Tool2 = class extends BaseResource {
801
1187
  constructor(options, toolId) {
802
1188
  super(options);
803
1189
  this.toolId = toolId;
@@ -1497,7 +1883,7 @@ var MastraClient = class extends BaseResource {
1497
1883
  * @returns Tool instance
1498
1884
  */
1499
1885
  getTool(toolId) {
1500
- return new Tool(this.options, toolId);
1886
+ return new Tool2(this.options, toolId);
1501
1887
  }
1502
1888
  /**
1503
1889
  * Retrieves all available legacy workflows
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/client-js",
3
- "version": "0.10.6-alpha.2",
3
+ "version": "0.10.6-alpha.4",
4
4
  "description": "The official TypeScript library for the Mastra Client API",
5
5
  "author": "",
6
6
  "type": "module",
@@ -33,7 +33,7 @@
33
33
  "rxjs": "7.8.1",
34
34
  "zod": "^3.25.67",
35
35
  "zod-to-json-schema": "^3.24.5",
36
- "@mastra/core": "0.10.7-alpha.2"
36
+ "@mastra/core": "0.10.7-alpha.4"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "zod": "^3.0.0"
package/src/example.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { MastraClient } from './client';
2
+ import z from 'zod';
2
3
  // import type { WorkflowRunResult } from './types';
3
4
 
4
5
  // Agent
5
-
6
6
  (async () => {
7
7
  const client = new MastraClient({
8
8
  baseUrl: 'http://localhost:4111',
@@ -29,6 +29,9 @@ import { MastraClient } from './client';
29
29
  onErrorPart: error => {
30
30
  console.error(error);
31
31
  },
32
+ onToolCallPart(streamPart) {
33
+ console.log(streamPart);
34
+ },
32
35
  });
33
36
  } catch (error) {
34
37
  console.error(error);