@mastra/client-js 0.0.0-pg-pool-options-20250428183821 → 0.0.0-redis-cloud-transporter-20250508194049

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.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { CoreMessage, AiMessageType, StorageThreadType, MessageType, StepAction, StepGraph, WorkflowRunResult as WorkflowRunResult$1, QueryResult, BaseLogMessage, GenerateReturn } from '@mastra/core';
1
+ import { AbstractAgent } from '@ag-ui/client';
2
+ import { processDataStream } from '@ai-sdk/ui-utils';
3
+ import { CoreMessage, AiMessageType, StorageThreadType, MessageType, StepAction, StepGraph, WorkflowRuns, WorkflowRunResult as WorkflowRunResult$1, QueryResult, BaseLogMessage, GenerateReturn } from '@mastra/core';
2
4
  import { JSONSchema7 } from 'json-schema';
3
5
  import { ZodSchema } from 'zod';
4
- import { processDataStream } from '@ai-sdk/ui-utils';
5
6
  import { AgentGenerateOptions, AgentStreamOptions } from '@mastra/core/agent';
6
7
  import { NewWorkflow, WorkflowResult, WatchEvent } from '@mastra/core/workflows/vNext';
7
8
  import { RuntimeContext } from '@mastra/core/runtime-context';
@@ -40,6 +41,9 @@ type StreamParams<T extends JSONSchema7 | ZodSchema | undefined = undefined> = {
40
41
  } & Omit<AgentStreamOptions<T>, 'onFinish' | 'onStepFinish' | 'telemetry'>;
41
42
  interface GetEvalsByAgentIdResponse extends GetAgentResponse {
42
43
  evals: any[];
44
+ instructions: string;
45
+ name: string;
46
+ id: string;
43
47
  }
44
48
  interface GetToolResponse {
45
49
  id: string;
@@ -55,6 +59,14 @@ interface GetWorkflowResponse {
55
59
  stepSubscriberGraph: Record<string, StepGraph>;
56
60
  workflowId?: string;
57
61
  }
62
+ interface GetWorkflowRunsParams {
63
+ fromDate?: Date;
64
+ toDate?: Date;
65
+ limit?: number;
66
+ offset?: number;
67
+ resourceId?: string;
68
+ }
69
+ type GetWorkflowRunsResponse = WorkflowRuns;
58
70
  type WorkflowRunResult = {
59
71
  activePaths: Record<string, {
60
72
  status: string;
@@ -67,8 +79,17 @@ type WorkflowRunResult = {
67
79
  };
68
80
  interface GetVNextWorkflowResponse {
69
81
  name: string;
70
- steps: NewWorkflow['steps'];
71
- stepGraph: NewWorkflow['stepGraph'];
82
+ steps: {
83
+ [key: string]: {
84
+ id: string;
85
+ description: string;
86
+ inputSchema: string;
87
+ outputSchema: string;
88
+ resumeSchema: string;
89
+ suspendSchema: string;
90
+ };
91
+ };
92
+ stepGraph: NewWorkflow['serializedStepGraph'];
72
93
  inputSchema: string;
73
94
  outputSchema: string;
74
95
  }
@@ -184,6 +205,8 @@ interface GetTelemetryParams {
184
205
  page?: number;
185
206
  perPage?: number;
186
207
  attribute?: Record<string, string>;
208
+ fromDate?: Date;
209
+ toDate?: Date;
187
210
  }
188
211
  interface GetNetworkResponse {
189
212
  name: string;
@@ -389,6 +412,12 @@ declare class Workflow extends BaseResource {
389
412
  * @returns Promise containing workflow details including steps and graphs
390
413
  */
391
414
  details(): Promise<GetWorkflowResponse>;
415
+ /**
416
+ * Retrieves all runs for a workflow
417
+ * @param params - Parameters for filtering runs
418
+ * @returns Promise containing workflow runs array
419
+ */
420
+ runs(params?: GetWorkflowRunsParams): Promise<GetWorkflowRunsResponse>;
392
421
  /**
393
422
  * @deprecated Use `startAsync` instead
394
423
  * Executes the workflow with the provided parameters
@@ -482,6 +511,7 @@ declare class Tool extends BaseResource {
482
511
  */
483
512
  execute(params: {
484
513
  data: any;
514
+ runId?: string;
485
515
  }): Promise<any>;
486
516
  }
487
517
 
@@ -501,6 +531,12 @@ declare class VNextWorkflow extends BaseResource {
501
531
  * @returns Promise containing vNext workflow details including steps and graphs
502
532
  */
503
533
  details(): Promise<GetVNextWorkflowResponse>;
534
+ /**
535
+ * Retrieves all runs for a vNext workflow
536
+ * @param params - Parameters for filtering runs
537
+ * @returns Promise containing vNext workflow runs array
538
+ */
539
+ runs(params?: GetWorkflowRunsParams): Promise<GetWorkflowRunsResponse>;
504
540
  /**
505
541
  * Creates a new vNext workflow run
506
542
  * @param params - Optional object containing the optional runId
@@ -574,6 +610,9 @@ declare class MastraClient extends BaseResource {
574
610
  * @returns Promise containing map of agent IDs to agent details
575
611
  */
576
612
  getAgents(): Promise<Record<string, GetAgentResponse>>;
613
+ getAGUI({ resourceId }: {
614
+ resourceId: string;
615
+ }): Promise<Record<string, AbstractAgent>>;
577
616
  /**
578
617
  * Gets an agent instance by ID
579
618
  * @param agentId - ID of the agent to retrieve
@@ -688,4 +727,4 @@ declare class MastraClient extends BaseResource {
688
727
  getNetwork(networkId: string): Network;
689
728
  }
690
729
 
691
- export { type ClientOptions, type CreateIndexParams, type CreateMemoryThreadParams, type CreateMemoryThreadResponse, type GenerateParams, type GetAgentResponse, type GetEvalsByAgentIdResponse, type GetLogParams, type GetLogsParams, type GetLogsResponse, type GetMemoryThreadMessagesResponse, type GetMemoryThreadParams, type GetMemoryThreadResponse, type GetNetworkResponse, type GetTelemetryParams, type GetTelemetryResponse, type GetToolResponse, type GetVNextWorkflowResponse, type GetVectorIndexResponse, type GetWorkflowResponse, MastraClient, type QueryVectorParams, type QueryVectorResponse, type RequestFunction, type RequestOptions, type SaveMessageToMemoryParams, type SaveMessageToMemoryResponse, type StreamParams, type UpdateMemoryThreadParams, type UpsertVectorParams, type VNextWorkflowRunResult, type VNextWorkflowWatchResult, type WorkflowRunResult };
730
+ export { type ClientOptions, type CreateIndexParams, type CreateMemoryThreadParams, type CreateMemoryThreadResponse, type GenerateParams, type GetAgentResponse, type GetEvalsByAgentIdResponse, type GetLogParams, type GetLogsParams, type GetLogsResponse, type GetMemoryThreadMessagesResponse, type GetMemoryThreadParams, type GetMemoryThreadResponse, type GetNetworkResponse, type GetTelemetryParams, type GetTelemetryResponse, type GetToolResponse, type GetVNextWorkflowResponse, type GetVectorIndexResponse, type GetWorkflowResponse, type GetWorkflowRunsParams, type GetWorkflowRunsResponse, MastraClient, type QueryVectorParams, type QueryVectorResponse, type RequestFunction, type RequestOptions, type SaveMessageToMemoryParams, type SaveMessageToMemoryResponse, type StreamParams, type UpdateMemoryThreadParams, type UpsertVectorParams, type VNextWorkflowRunResult, type VNextWorkflowWatchResult, type WorkflowRunResult };
package/dist/index.js CHANGED
@@ -1,8 +1,173 @@
1
+ import { AbstractAgent, EventType } from '@ag-ui/client';
2
+ import { Observable } from 'rxjs';
3
+ import { processDataStream } from '@ai-sdk/ui-utils';
1
4
  import { ZodSchema } from 'zod';
2
5
  import { zodToJsonSchema } from 'zod-to-json-schema';
3
- import { processDataStream } from '@ai-sdk/ui-utils';
4
6
 
5
- // src/resources/agent.ts
7
+ // src/adapters/agui.ts
8
+ var AGUIAdapter = class extends AbstractAgent {
9
+ agent;
10
+ resourceId;
11
+ constructor({ agent, agentId, resourceId, ...rest }) {
12
+ super({
13
+ agentId,
14
+ ...rest
15
+ });
16
+ this.agent = agent;
17
+ this.resourceId = resourceId;
18
+ }
19
+ run(input) {
20
+ return new Observable((subscriber) => {
21
+ const convertedMessages = convertMessagesToMastraMessages(input.messages);
22
+ subscriber.next({
23
+ type: EventType.RUN_STARTED,
24
+ threadId: input.threadId,
25
+ runId: input.runId
26
+ });
27
+ this.agent.stream({
28
+ threadId: input.threadId,
29
+ resourceId: this.resourceId ?? "",
30
+ runId: input.runId,
31
+ messages: convertedMessages,
32
+ clientTools: input.tools.reduce(
33
+ (acc, tool) => {
34
+ acc[tool.name] = {
35
+ id: tool.name,
36
+ description: tool.description,
37
+ inputSchema: tool.parameters
38
+ };
39
+ return acc;
40
+ },
41
+ {}
42
+ )
43
+ }).then((response) => {
44
+ let currentMessageId = void 0;
45
+ return response.processDataStream({
46
+ onTextPart: (text) => {
47
+ if (currentMessageId === void 0) {
48
+ currentMessageId = generateUUID();
49
+ const message2 = {
50
+ type: EventType.TEXT_MESSAGE_START,
51
+ messageId: currentMessageId,
52
+ role: "assistant"
53
+ };
54
+ subscriber.next(message2);
55
+ }
56
+ const message = {
57
+ type: EventType.TEXT_MESSAGE_CONTENT,
58
+ messageId: currentMessageId,
59
+ delta: text
60
+ };
61
+ subscriber.next(message);
62
+ },
63
+ onFinishMessagePart: (message) => {
64
+ console.log("onFinishMessagePart", message);
65
+ if (currentMessageId !== void 0) {
66
+ const message2 = {
67
+ type: EventType.TEXT_MESSAGE_END,
68
+ messageId: currentMessageId
69
+ };
70
+ subscriber.next(message2);
71
+ }
72
+ subscriber.next({
73
+ type: EventType.RUN_FINISHED,
74
+ threadId: input.threadId,
75
+ runId: input.runId
76
+ });
77
+ subscriber.complete();
78
+ },
79
+ onToolCallPart(streamPart) {
80
+ const parentMessageId = currentMessageId || generateUUID();
81
+ subscriber.next({
82
+ type: EventType.TOOL_CALL_START,
83
+ toolCallId: streamPart.toolCallId,
84
+ toolCallName: streamPart.toolName,
85
+ parentMessageId
86
+ });
87
+ subscriber.next({
88
+ type: EventType.TOOL_CALL_ARGS,
89
+ toolCallId: streamPart.toolCallId,
90
+ delta: JSON.stringify(streamPart.args),
91
+ parentMessageId
92
+ });
93
+ subscriber.next({
94
+ type: EventType.TOOL_CALL_END,
95
+ toolCallId: streamPart.toolCallId,
96
+ parentMessageId
97
+ });
98
+ }
99
+ });
100
+ }).catch((error) => {
101
+ console.log("error", error);
102
+ subscriber.error(error);
103
+ });
104
+ return () => {
105
+ };
106
+ });
107
+ }
108
+ };
109
+ function generateUUID() {
110
+ if (typeof crypto !== "undefined") {
111
+ if (typeof crypto.randomUUID === "function") {
112
+ return crypto.randomUUID();
113
+ }
114
+ if (typeof crypto.getRandomValues === "function") {
115
+ const buffer = new Uint8Array(16);
116
+ crypto.getRandomValues(buffer);
117
+ buffer[6] = buffer[6] & 15 | 64;
118
+ buffer[8] = buffer[8] & 63 | 128;
119
+ let hex = "";
120
+ for (let i = 0; i < 16; i++) {
121
+ hex += buffer[i].toString(16).padStart(2, "0");
122
+ if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
123
+ }
124
+ return hex;
125
+ }
126
+ }
127
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
128
+ const r = Math.random() * 16 | 0;
129
+ const v = c === "x" ? r : r & 3 | 8;
130
+ return v.toString(16);
131
+ });
132
+ }
133
+ function convertMessagesToMastraMessages(messages) {
134
+ const result = [];
135
+ for (const message of messages) {
136
+ if (message.role === "assistant") {
137
+ const parts = message.content ? [{ type: "text", text: message.content }] : [];
138
+ for (const toolCall of message.toolCalls ?? []) {
139
+ parts.push({
140
+ type: "tool-call",
141
+ toolCallId: toolCall.id,
142
+ toolName: toolCall.function.name,
143
+ args: JSON.parse(toolCall.function.arguments)
144
+ });
145
+ }
146
+ result.push({
147
+ role: "assistant",
148
+ content: parts
149
+ });
150
+ } else if (message.role === "user") {
151
+ result.push({
152
+ role: "user",
153
+ content: message.content || ""
154
+ });
155
+ } else if (message.role === "tool") {
156
+ result.push({
157
+ role: "tool",
158
+ content: [
159
+ {
160
+ type: "tool-result",
161
+ toolCallId: message.toolCallId,
162
+ toolName: "unknown",
163
+ result: message.content
164
+ }
165
+ ]
166
+ });
167
+ }
168
+ }
169
+ return result;
170
+ }
6
171
 
7
172
  // src/resources/base.ts
8
173
  var BaseResource = class {
@@ -134,7 +299,8 @@ var Agent = class extends BaseResource {
134
299
  const processedParams = {
135
300
  ...params,
136
301
  output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
137
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
302
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output,
303
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
138
304
  };
139
305
  return this.request(`/api/agents/${this.agentId}/generate`, {
140
306
  method: "POST",
@@ -150,7 +316,8 @@ var Agent = class extends BaseResource {
150
316
  const processedParams = {
151
317
  ...params,
152
318
  output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
153
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
319
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output,
320
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
154
321
  };
155
322
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
156
323
  method: "POST",
@@ -371,6 +538,34 @@ var Workflow = class extends BaseResource {
371
538
  details() {
372
539
  return this.request(`/api/workflows/${this.workflowId}`);
373
540
  }
541
+ /**
542
+ * Retrieves all runs for a workflow
543
+ * @param params - Parameters for filtering runs
544
+ * @returns Promise containing workflow runs array
545
+ */
546
+ runs(params) {
547
+ const searchParams = new URLSearchParams();
548
+ if (params?.fromDate) {
549
+ searchParams.set("fromDate", params.fromDate.toISOString());
550
+ }
551
+ if (params?.toDate) {
552
+ searchParams.set("toDate", params.toDate.toISOString());
553
+ }
554
+ if (params?.limit) {
555
+ searchParams.set("limit", String(params.limit));
556
+ }
557
+ if (params?.offset) {
558
+ searchParams.set("offset", String(params.offset));
559
+ }
560
+ if (params?.resourceId) {
561
+ searchParams.set("resourceId", params.resourceId);
562
+ }
563
+ if (searchParams.size) {
564
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
565
+ } else {
566
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
567
+ }
568
+ }
374
569
  /**
375
570
  * @deprecated Use `startAsync` instead
376
571
  * Executes the workflow with the provided parameters
@@ -487,7 +682,7 @@ var Workflow = class extends BaseResource {
487
682
  }
488
683
  }
489
684
  }
490
- } catch (error) {
685
+ } catch {
491
686
  }
492
687
  }
493
688
  if (buffer) {
@@ -541,9 +736,13 @@ var Tool = class extends BaseResource {
541
736
  * @returns Promise containing the tool execution results
542
737
  */
543
738
  execute(params) {
544
- return this.request(`/api/tools/${this.toolId}/execute`, {
739
+ const url = new URLSearchParams();
740
+ if (params.runId) {
741
+ url.set("runId", params.runId);
742
+ }
743
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
545
744
  method: "POST",
546
- body: params
745
+ body: params.data
547
746
  });
548
747
  }
549
748
  };
@@ -586,7 +785,7 @@ var VNextWorkflow = class extends BaseResource {
586
785
  }
587
786
  }
588
787
  }
589
- } catch (error) {
788
+ } catch {
590
789
  }
591
790
  }
592
791
  if (buffer) {
@@ -607,6 +806,34 @@ var VNextWorkflow = class extends BaseResource {
607
806
  details() {
608
807
  return this.request(`/api/workflows/v-next/${this.workflowId}`);
609
808
  }
809
+ /**
810
+ * Retrieves all runs for a vNext workflow
811
+ * @param params - Parameters for filtering runs
812
+ * @returns Promise containing vNext workflow runs array
813
+ */
814
+ runs(params) {
815
+ const searchParams = new URLSearchParams();
816
+ if (params?.fromDate) {
817
+ searchParams.set("fromDate", params.fromDate.toISOString());
818
+ }
819
+ if (params?.toDate) {
820
+ searchParams.set("toDate", params.toDate.toISOString());
821
+ }
822
+ if (params?.limit) {
823
+ searchParams.set("limit", String(params.limit));
824
+ }
825
+ if (params?.offset) {
826
+ searchParams.set("offset", String(params.offset));
827
+ }
828
+ if (params?.resourceId) {
829
+ searchParams.set("resourceId", params.resourceId);
830
+ }
831
+ if (searchParams.size) {
832
+ return this.request(`/api/workflows/v-next/${this.workflowId}/runs?${searchParams}`);
833
+ } else {
834
+ return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
835
+ }
836
+ }
610
837
  /**
611
838
  * Creates a new vNext workflow run
612
839
  * @param params - Optional object containing the optional runId
@@ -716,6 +943,21 @@ var MastraClient = class extends BaseResource {
716
943
  getAgents() {
717
944
  return this.request("/api/agents");
718
945
  }
946
+ async getAGUI({ resourceId }) {
947
+ const agents = await this.getAgents();
948
+ return Object.entries(agents).reduce(
949
+ (acc, [agentId]) => {
950
+ const agent = this.getAgent(agentId);
951
+ acc[agentId] = new AGUIAdapter({
952
+ agentId,
953
+ agent,
954
+ resourceId
955
+ });
956
+ return acc;
957
+ },
958
+ {}
959
+ );
960
+ }
719
961
  /**
720
962
  * Gets an agent instance by ID
721
963
  * @param agentId - ID of the agent to retrieve
@@ -848,7 +1090,7 @@ var MastraClient = class extends BaseResource {
848
1090
  * @returns Promise containing telemetry data
849
1091
  */
850
1092
  getTelemetry(params) {
851
- const { name, scope, page, perPage, attribute } = params || {};
1093
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
852
1094
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
853
1095
  const searchParams = new URLSearchParams();
854
1096
  if (name) {
@@ -872,6 +1114,12 @@ var MastraClient = class extends BaseResource {
872
1114
  searchParams.set("attribute", _attribute);
873
1115
  }
874
1116
  }
1117
+ if (fromDate) {
1118
+ searchParams.set("fromDate", fromDate.toISOString());
1119
+ }
1120
+ if (toDate) {
1121
+ searchParams.set("toDate", toDate.toISOString());
1122
+ }
875
1123
  if (searchParams.size) {
876
1124
  return this.request(`/api/telemetry?${searchParams}`);
877
1125
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/client-js",
3
- "version": "0.0.0-pg-pool-options-20250428183821",
3
+ "version": "0.0.0-redis-cloud-transporter-20250508194049",
4
4
  "description": "The official TypeScript library for the Mastra Client API",
5
5
  "author": "",
6
6
  "type": "module",
@@ -22,11 +22,13 @@
22
22
  "repository": "github:mastra-ai/client-js",
23
23
  "license": "Elastic-2.0",
24
24
  "dependencies": {
25
+ "@ag-ui/client": "^0.0.27",
25
26
  "@ai-sdk/ui-utils": "^1.1.19",
26
27
  "json-schema": "^0.4.0",
27
- "zod": "^3.24.2",
28
- "zod-to-json-schema": "^3.24.3",
29
- "@mastra/core": "0.0.0-pg-pool-options-20250428183821"
28
+ "rxjs": "7.8.1",
29
+ "zod": "^3.24.3",
30
+ "zod-to-json-schema": "^3.24.5",
31
+ "@mastra/core": "0.0.0-redis-cloud-transporter-20250508194049"
30
32
  },
31
33
  "peerDependencies": {
32
34
  "zod": "^3.24.2"
@@ -39,8 +41,8 @@
39
41
  "@types/node": "^20.17.27",
40
42
  "tsup": "^8.4.0",
41
43
  "typescript": "^5.8.2",
42
- "vitest": "^3.0.9",
43
- "@internal/lint": "0.0.2"
44
+ "vitest": "^3.1.2",
45
+ "@internal/lint": "0.0.0-redis-cloud-transporter-20250508194049"
44
46
  },
45
47
  "scripts": {
46
48
  "build": "tsup src/index.ts --format esm,cjs --dts --clean --treeshake=smallest --splitting",
@@ -0,0 +1,167 @@
1
+ import type { Message } from '@ag-ui/client';
2
+ import { describe, it, expect } from 'vitest';
3
+ import { generateUUID, convertMessagesToMastraMessages } from './agui';
4
+
5
+ describe('generateUUID', () => {
6
+ it('should generate a valid UUID v4 string', () => {
7
+ const uuid = generateUUID();
8
+ // Check UUID format (8-4-4-4-12 hex digits)
9
+ expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
10
+ });
11
+
12
+ it('should generate unique UUIDs', () => {
13
+ const uuids = new Set();
14
+ for (let i = 0; i < 100; i++) {
15
+ uuids.add(generateUUID());
16
+ }
17
+ // All UUIDs should be unique
18
+ expect(uuids.size).toBe(100);
19
+ });
20
+ });
21
+
22
+ describe('convertMessagesToMastraMessages', () => {
23
+ it('should convert user messages correctly', () => {
24
+ const messages: Message[] = [
25
+ {
26
+ id: '1',
27
+ role: 'user',
28
+ content: 'Hello, world!',
29
+ },
30
+ ];
31
+
32
+ const result = convertMessagesToMastraMessages(messages);
33
+
34
+ expect(result).toEqual([
35
+ {
36
+ role: 'user',
37
+ content: 'Hello, world!',
38
+ },
39
+ ]);
40
+ });
41
+
42
+ it('should convert assistant messages correctly', () => {
43
+ const messages: Message[] = [
44
+ {
45
+ id: '1',
46
+ role: 'assistant',
47
+ content: 'Hello, I am an assistant',
48
+ },
49
+ ];
50
+
51
+ const result = convertMessagesToMastraMessages(messages);
52
+
53
+ expect(result).toEqual([
54
+ {
55
+ role: 'assistant',
56
+ content: [{ type: 'text', text: 'Hello, I am an assistant' }],
57
+ },
58
+ ]);
59
+ });
60
+
61
+ it('should convert assistant messages with tool calls correctly', () => {
62
+ const messages: Message[] = [
63
+ {
64
+ id: '1',
65
+ role: 'assistant',
66
+ content: undefined,
67
+ toolCalls: [
68
+ {
69
+ id: 'tool-call-1',
70
+ type: 'function',
71
+ function: {
72
+ name: 'getWeather',
73
+ arguments: '{"location":"San Francisco"}',
74
+ },
75
+ },
76
+ ],
77
+ },
78
+ ];
79
+
80
+ const result = convertMessagesToMastraMessages(messages);
81
+
82
+ expect(result).toEqual([
83
+ {
84
+ role: 'assistant',
85
+ content: [
86
+ {
87
+ type: 'tool-call',
88
+ toolCallId: 'tool-call-1',
89
+ toolName: 'getWeather',
90
+ args: { location: 'San Francisco' },
91
+ },
92
+ ],
93
+ },
94
+ ]);
95
+ });
96
+
97
+ it('should convert tool messages correctly', () => {
98
+ const messages: Message[] = [
99
+ {
100
+ id: '1',
101
+ role: 'tool',
102
+ toolCallId: 'tool-call-1',
103
+ content: '{"temperature":72,"unit":"F"}',
104
+ },
105
+ ];
106
+
107
+ const result = convertMessagesToMastraMessages(messages);
108
+
109
+ expect(result).toEqual([
110
+ {
111
+ role: 'tool',
112
+ content: [
113
+ {
114
+ type: 'tool-result',
115
+ toolCallId: 'tool-call-1',
116
+ toolName: 'unknown',
117
+ result: '{"temperature":72,"unit":"F"}',
118
+ },
119
+ ],
120
+ },
121
+ ]);
122
+ });
123
+
124
+ it('should convert a complex conversation correctly', () => {
125
+ const messages: Message[] = [
126
+ {
127
+ id: '1',
128
+ role: 'user',
129
+ content: "What's the weather in San Francisco?",
130
+ },
131
+ {
132
+ id: '2',
133
+ role: 'assistant',
134
+ content: undefined,
135
+ toolCalls: [
136
+ {
137
+ id: 'tool-call-1',
138
+ type: 'function',
139
+ function: {
140
+ name: 'getWeather',
141
+ arguments: '{"location":"San Francisco"}',
142
+ },
143
+ },
144
+ ],
145
+ },
146
+ {
147
+ id: '3',
148
+ role: 'tool',
149
+ toolCallId: 'tool-call-1',
150
+ content: '{"temperature":72,"unit":"F"}',
151
+ },
152
+ {
153
+ id: '4',
154
+ role: 'assistant',
155
+ content: 'The weather in San Francisco is 72°F.',
156
+ },
157
+ ];
158
+
159
+ const result = convertMessagesToMastraMessages(messages);
160
+
161
+ expect(result).toHaveLength(4);
162
+ expect(result[0].role).toBe('user');
163
+ expect(result[1].role).toBe('assistant');
164
+ expect(result[2].role).toBe('tool');
165
+ expect(result[3].role).toBe('assistant');
166
+ });
167
+ });