@mastra/client-js 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-scorers-api-v2-20250801171841

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.
Files changed (83) hide show
  1. package/CHANGELOG.md +1257 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +2 -1
  4. package/dist/adapters/agui.d.ts +23 -0
  5. package/dist/adapters/agui.d.ts.map +1 -0
  6. package/dist/client.d.ts +265 -0
  7. package/dist/client.d.ts.map +1 -0
  8. package/dist/example.d.ts +2 -0
  9. package/dist/example.d.ts.map +1 -0
  10. package/dist/index.cjs +1644 -126
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.ts +4 -691
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +1643 -129
  15. package/dist/index.js.map +1 -0
  16. package/dist/resources/a2a.d.ts +44 -0
  17. package/dist/resources/a2a.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +112 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +11 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/legacy-workflow.d.ts +87 -0
  25. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  26. package/dist/resources/mcp-tool.d.ts +27 -0
  27. package/dist/resources/mcp-tool.d.ts.map +1 -0
  28. package/dist/resources/memory-thread.d.ts +53 -0
  29. package/dist/resources/memory-thread.d.ts.map +1 -0
  30. package/dist/resources/network-memory-thread.d.ts +47 -0
  31. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  32. package/dist/resources/network.d.ts +30 -0
  33. package/dist/resources/network.d.ts.map +1 -0
  34. package/dist/resources/tool.d.ts +23 -0
  35. package/dist/resources/tool.d.ts.map +1 -0
  36. package/dist/resources/vNextNetwork.d.ts +42 -0
  37. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  38. package/dist/resources/vector.d.ts +48 -0
  39. package/dist/resources/vector.d.ts.map +1 -0
  40. package/dist/resources/workflow.d.ts +154 -0
  41. package/dist/resources/workflow.d.ts.map +1 -0
  42. package/dist/types.d.ts +422 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/utils/index.d.ts +3 -0
  45. package/dist/utils/index.d.ts.map +1 -0
  46. package/dist/utils/process-client-tools.d.ts +3 -0
  47. package/dist/utils/process-client-tools.d.ts.map +1 -0
  48. package/dist/utils/zod-to-json-schema.d.ts +105 -0
  49. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  50. package/integration-tests/agui-adapter.test.ts +122 -0
  51. package/integration-tests/package.json +18 -0
  52. package/integration-tests/src/mastra/index.ts +35 -0
  53. package/integration-tests/vitest.config.ts +9 -0
  54. package/package.json +29 -18
  55. package/src/adapters/agui.test.ts +322 -0
  56. package/src/adapters/agui.ts +239 -0
  57. package/src/client.ts +414 -23
  58. package/src/example.ts +59 -29
  59. package/src/index.test.ts +526 -10
  60. package/src/index.ts +1 -0
  61. package/src/resources/a2a.ts +88 -0
  62. package/src/resources/agent.ts +629 -49
  63. package/src/resources/base.ts +8 -2
  64. package/src/resources/index.ts +4 -2
  65. package/src/resources/{vnext-workflow.ts → legacy-workflow.ts} +141 -124
  66. package/src/resources/mcp-tool.ts +48 -0
  67. package/src/resources/memory-thread.test.ts +285 -0
  68. package/src/resources/memory-thread.ts +49 -3
  69. package/src/resources/network-memory-thread.test.ts +269 -0
  70. package/src/resources/network-memory-thread.ts +81 -0
  71. package/src/resources/network.ts +11 -17
  72. package/src/resources/tool.ts +16 -3
  73. package/src/resources/vNextNetwork.ts +194 -0
  74. package/src/resources/workflow.ts +289 -94
  75. package/src/types.ts +291 -26
  76. package/src/utils/index.ts +11 -0
  77. package/src/utils/process-client-tools.ts +32 -0
  78. package/src/utils/zod-to-json-schema.ts +10 -0
  79. package/src/v2-messages.test.ts +180 -0
  80. package/tsconfig.build.json +9 -0
  81. package/tsconfig.json +1 -1
  82. package/tsup.config.ts +22 -0
  83. package/dist/index.d.cts +0 -691
@@ -1,4 +1,4 @@
1
- import type { RequestFunction, RequestOptions, ClientOptions } from '../types';
1
+ import type { RequestOptions, ClientOptions } from '../types';
2
2
 
3
3
  export class BaseResource {
4
4
  readonly options: ClientOptions;
@@ -21,14 +21,20 @@ export class BaseResource {
21
21
 
22
22
  for (let attempt = 0; attempt <= retries; attempt++) {
23
23
  try {
24
- const response = await fetch(`${baseUrl}${path}`, {
24
+ const response = await fetch(`${baseUrl.replace(/\/$/, '')}${path}`, {
25
25
  ...options,
26
26
  headers: {
27
+ ...(options.body &&
28
+ !(options.body instanceof FormData) &&
29
+ (options.method === 'POST' || options.method === 'PUT')
30
+ ? { 'content-type': 'application/json' }
31
+ : {}),
27
32
  ...headers,
28
33
  ...options.headers,
29
34
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
30
35
  // 'x-mastra-client-type': 'js',
31
36
  },
37
+ signal: this.options.abortSignal,
32
38
  body:
33
39
  options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : undefined,
34
40
  });
@@ -2,7 +2,9 @@ export * from './agent';
2
2
  export * from './network';
3
3
  export * from './memory-thread';
4
4
  export * from './vector';
5
- export * from './workflow';
5
+ export * from './legacy-workflow';
6
6
  export * from './tool';
7
7
  export * from './base';
8
- export * from './vnext-workflow';
8
+ export * from './workflow';
9
+ export * from './a2a';
10
+ export * from './mcp-tool';
@@ -1,16 +1,16 @@
1
- import type { RuntimeContext } from '@mastra/core/runtime-context';
2
1
  import type {
3
2
  ClientOptions,
4
- GetVNextWorkflowResponse,
5
- VNextWorkflowRunResult,
6
- VNextWorkflowWatchResult,
3
+ LegacyWorkflowRunResult,
4
+ GetLegacyWorkflowRunsResponse,
5
+ GetWorkflowRunsParams,
6
+ GetLegacyWorkflowResponse,
7
7
  } from '../types';
8
8
 
9
9
  import { BaseResource } from './base';
10
10
 
11
11
  const RECORD_SEPARATOR = '\x1E';
12
12
 
13
- export class VNextWorkflow extends BaseResource {
13
+ export class LegacyWorkflow extends BaseResource {
14
14
  constructor(
15
15
  options: ClientOptions,
16
16
  private workflowId: string,
@@ -19,13 +19,141 @@ export class VNextWorkflow extends BaseResource {
19
19
  }
20
20
 
21
21
  /**
22
- * Creates an async generator that processes a readable stream and yields vNext workflow records
22
+ * Retrieves details about the legacy workflow
23
+ * @returns Promise containing legacy workflow details including steps and graphs
24
+ */
25
+ details(): Promise<GetLegacyWorkflowResponse> {
26
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
27
+ }
28
+
29
+ /**
30
+ * Retrieves all runs for a legacy workflow
31
+ * @param params - Parameters for filtering runs
32
+ * @returns Promise containing legacy workflow runs array
33
+ */
34
+ runs(params?: GetWorkflowRunsParams): Promise<GetLegacyWorkflowRunsResponse> {
35
+ const searchParams = new URLSearchParams();
36
+ if (params?.fromDate) {
37
+ searchParams.set('fromDate', params.fromDate.toISOString());
38
+ }
39
+ if (params?.toDate) {
40
+ searchParams.set('toDate', params.toDate.toISOString());
41
+ }
42
+ if (params?.limit) {
43
+ searchParams.set('limit', String(params.limit));
44
+ }
45
+ if (params?.offset) {
46
+ searchParams.set('offset', String(params.offset));
47
+ }
48
+ if (params?.resourceId) {
49
+ searchParams.set('resourceId', params.resourceId);
50
+ }
51
+
52
+ if (searchParams.size) {
53
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
54
+ } else {
55
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Creates a new legacy workflow run
61
+ * @returns Promise containing the generated run ID
62
+ */
63
+ createRun(params?: { runId?: string }): Promise<{ runId: string }> {
64
+ const searchParams = new URLSearchParams();
65
+
66
+ if (!!params?.runId) {
67
+ searchParams.set('runId', params.runId);
68
+ }
69
+
70
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
71
+ method: 'POST',
72
+ });
73
+ }
74
+
75
+ /**
76
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
77
+ * @param params - Object containing the runId and triggerData
78
+ * @returns Promise containing success message
79
+ */
80
+ start(params: { runId: string; triggerData: Record<string, any> }): Promise<{ message: string }> {
81
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
82
+ method: 'POST',
83
+ body: params?.triggerData,
84
+ });
85
+ }
86
+
87
+ /**
88
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
89
+ * @param stepId - ID of the step to resume
90
+ * @param runId - ID of the legacy workflow run
91
+ * @param context - Context to resume the legacy workflow with
92
+ * @returns Promise containing the legacy workflow resume results
93
+ */
94
+ resume({
95
+ stepId,
96
+ runId,
97
+ context,
98
+ }: {
99
+ stepId: string;
100
+ runId: string;
101
+ context: Record<string, any>;
102
+ }): Promise<{ message: string }> {
103
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
104
+ method: 'POST',
105
+ body: {
106
+ stepId,
107
+ context,
108
+ },
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
114
+ * @param params - Object containing the optional runId and triggerData
115
+ * @returns Promise containing the workflow execution results
116
+ */
117
+ startAsync(params: { runId?: string; triggerData: Record<string, any> }): Promise<LegacyWorkflowRunResult> {
118
+ const searchParams = new URLSearchParams();
119
+
120
+ if (!!params?.runId) {
121
+ searchParams.set('runId', params.runId);
122
+ }
123
+
124
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
125
+ method: 'POST',
126
+ body: params?.triggerData,
127
+ });
128
+ }
129
+
130
+ /**
131
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
132
+ * @param params - Object containing the runId, stepId, and context
133
+ * @returns Promise containing the workflow resume results
134
+ */
135
+ resumeAsync(params: {
136
+ runId: string;
137
+ stepId: string;
138
+ context: Record<string, any>;
139
+ }): Promise<LegacyWorkflowRunResult> {
140
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
141
+ method: 'POST',
142
+ body: {
143
+ stepId: params.stepId,
144
+ context: params.context,
145
+ },
146
+ });
147
+ }
148
+
149
+ /**
150
+ * Creates an async generator that processes a readable stream and yields records
23
151
  * separated by the Record Separator character (\x1E)
24
152
  *
25
153
  * @param stream - The readable stream to process
26
154
  * @returns An async generator that yields parsed records
27
155
  */
28
- private async *streamProcessor(stream: ReadableStream): AsyncGenerator<VNextWorkflowWatchResult, void, unknown> {
156
+ private async *streamProcessor(stream: ReadableStream): AsyncGenerator<LegacyWorkflowRunResult, void, unknown> {
29
157
  const reader = stream.getReader();
30
158
 
31
159
  // Track if we've finished reading from the stream
@@ -67,7 +195,7 @@ export class VNextWorkflow extends BaseResource {
67
195
  }
68
196
  }
69
197
  }
70
- } catch (error) {
198
+ } catch {
71
199
  // Silently ignore parsing errors to maintain stream processing
72
200
  // This allows the stream to continue even if one record is malformed
73
201
  }
@@ -90,128 +218,17 @@ export class VNextWorkflow extends BaseResource {
90
218
  }
91
219
 
92
220
  /**
93
- * Retrieves details about the vNext workflow
94
- * @returns Promise containing vNext workflow details including steps and graphs
95
- */
96
- details(): Promise<GetVNextWorkflowResponse> {
97
- return this.request(`/api/workflows/v-next/${this.workflowId}`);
98
- }
99
-
100
- /**
101
- * Creates a new vNext workflow run
102
- * @param params - Optional object containing the optional runId
103
- * @returns Promise containing the runId of the created run
104
- */
105
- createRun(params?: { runId?: string }): Promise<{ runId: string }> {
106
- const searchParams = new URLSearchParams();
107
-
108
- if (!!params?.runId) {
109
- searchParams.set('runId', params.runId);
110
- }
111
-
112
- return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
113
- method: 'POST',
114
- });
115
- }
116
-
117
- /**
118
- * Starts a vNext workflow run synchronously without waiting for the workflow to complete
119
- * @param params - Object containing the runId, inputData and runtimeContext
120
- * @returns Promise containing success message
121
- */
122
- start(params: {
123
- runId: string;
124
- inputData: Record<string, any>;
125
- runtimeContext?: RuntimeContext;
126
- }): Promise<{ message: string }> {
127
- return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
128
- method: 'POST',
129
- body: { inputData: params?.inputData, runtimeContext: params.runtimeContext },
130
- });
131
- }
132
-
133
- /**
134
- * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
135
- * @param params - Object containing the runId, step, resumeData and runtimeContext
136
- * @returns Promise containing success message
137
- */
138
- resume({
139
- step,
140
- runId,
141
- resumeData,
142
- runtimeContext,
143
- }: {
144
- step: string | string[];
145
- runId: string;
146
- resumeData?: Record<string, any>;
147
- runtimeContext?: RuntimeContext;
148
- }): Promise<{ message: string }> {
149
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
150
- method: 'POST',
151
- stream: true,
152
- body: {
153
- step,
154
- resumeData,
155
- runtimeContext,
156
- },
157
- });
158
- }
159
-
160
- /**
161
- * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
162
- * @param params - Object containing the optional runId, inputData and runtimeContext
163
- * @returns Promise containing the vNext workflow execution results
164
- */
165
- startAsync(params: {
166
- runId?: string;
167
- inputData: Record<string, any>;
168
- runtimeContext?: RuntimeContext;
169
- }): Promise<VNextWorkflowRunResult> {
170
- const searchParams = new URLSearchParams();
171
-
172
- if (!!params?.runId) {
173
- searchParams.set('runId', params.runId);
174
- }
175
-
176
- return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
177
- method: 'POST',
178
- body: { inputData: params.inputData, runtimeContext: params.runtimeContext },
179
- });
180
- }
181
-
182
- /**
183
- * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
184
- * @param params - Object containing the runId, step, resumeData and runtimeContext
185
- * @returns Promise containing the vNext workflow resume results
186
- */
187
- resumeAsync(params: {
188
- runId: string;
189
- step: string | string[];
190
- resumeData?: Record<string, any>;
191
- runtimeContext?: RuntimeContext;
192
- }): Promise<VNextWorkflowRunResult> {
193
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
194
- method: 'POST',
195
- body: {
196
- step: params.step,
197
- resumeData: params.resumeData,
198
- runtimeContext: params.runtimeContext,
199
- },
200
- });
201
- }
202
-
203
- /**
204
- * Watches vNext workflow transitions in real-time
221
+ * Watches legacy workflow transitions in real-time
205
222
  * @param runId - Optional run ID to filter the watch stream
206
- * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
223
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
207
224
  */
208
- async watch({ runId }: { runId?: string }, onRecord: (record: VNextWorkflowWatchResult) => void) {
209
- const response: Response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
225
+ async watch({ runId }: { runId?: string }, onRecord: (record: LegacyWorkflowRunResult) => void) {
226
+ const response: Response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
210
227
  stream: true,
211
228
  });
212
229
 
213
230
  if (!response.ok) {
214
- throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
231
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
215
232
  }
216
233
 
217
234
  if (!response.body) {
@@ -0,0 +1,48 @@
1
+ import type { RuntimeContext } from '@mastra/core/runtime-context';
2
+ import type { ClientOptions, McpToolInfo } from '../types';
3
+ import { BaseResource } from './base';
4
+
5
+ /**
6
+ * Represents a specific tool available on a specific MCP server.
7
+ * Provides methods to get details and execute the tool.
8
+ */
9
+ export class MCPTool extends BaseResource {
10
+ private serverId: string;
11
+ private toolId: string;
12
+
13
+ constructor(options: ClientOptions, serverId: string, toolId: string) {
14
+ super(options);
15
+ this.serverId = serverId;
16
+ this.toolId = toolId;
17
+ }
18
+
19
+ /**
20
+ * Retrieves details about this specific tool from the MCP server.
21
+ * @returns Promise containing the tool's information (name, description, schema).
22
+ */
23
+ details(): Promise<McpToolInfo> {
24
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
25
+ }
26
+
27
+ /**
28
+ * Executes this specific tool on the MCP server.
29
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
30
+ * @returns Promise containing the result of the tool execution.
31
+ */
32
+ execute(params: { data?: any; runtimeContext?: RuntimeContext }): Promise<any> {
33
+ const body: any = {};
34
+ if (params.data !== undefined) body.data = params.data;
35
+ // If none of data, args the body might be empty or just contain runtimeContext.
36
+ // The handler will look for these, so an empty args object might be appropriate if that's the intent.
37
+ // else body.data = {}; // Or let it be empty if no specific input fields are used
38
+
39
+ if (params.runtimeContext !== undefined) {
40
+ body.runtimeContext = params.runtimeContext;
41
+ }
42
+
43
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
44
+ method: 'POST',
45
+ body: Object.keys(body).length > 0 ? body : undefined,
46
+ });
47
+ }
48
+ }
@@ -0,0 +1,285 @@
1
+ import { describe, expect, beforeEach, it, vi } from 'vitest';
2
+ import { MemoryThread } from './memory-thread';
3
+ import type { ClientOptions } from '../types';
4
+
5
+ // Mock fetch globally
6
+ global.fetch = vi.fn();
7
+
8
+ describe('MemoryThread', () => {
9
+ let thread: MemoryThread;
10
+ const clientOptions: ClientOptions = {
11
+ baseUrl: 'http://localhost:4111',
12
+ headers: {
13
+ Authorization: 'Bearer test-key',
14
+ },
15
+ };
16
+ const threadId = 'test-thread-id';
17
+ const agentId = 'test-agent-id';
18
+
19
+ beforeEach(() => {
20
+ vi.clearAllMocks();
21
+ thread = new MemoryThread(clientOptions, threadId, agentId);
22
+ });
23
+
24
+ const mockFetchResponse = (data: any) => {
25
+ (global.fetch as any).mockResolvedValueOnce({
26
+ ok: true,
27
+ status: 200,
28
+ json: async () => data,
29
+ headers: new Headers({
30
+ 'content-type': 'application/json',
31
+ }),
32
+ });
33
+ };
34
+
35
+ describe('get', () => {
36
+ it('should retrieve thread details', async () => {
37
+ const mockThread = {
38
+ id: threadId,
39
+ title: 'Test Thread',
40
+ metadata: { test: true },
41
+ createdAt: new Date().toISOString(),
42
+ updatedAt: new Date().toISOString(),
43
+ };
44
+
45
+ mockFetchResponse(mockThread);
46
+
47
+ const result = await thread.get();
48
+
49
+ expect(global.fetch).toHaveBeenCalledWith(
50
+ `http://localhost:4111/api/memory/threads/${threadId}?agentId=${agentId}`,
51
+ expect.objectContaining({
52
+ headers: expect.objectContaining({
53
+ Authorization: 'Bearer test-key',
54
+ }),
55
+ }),
56
+ );
57
+ expect(result).toEqual(mockThread);
58
+ });
59
+ });
60
+
61
+ describe('update', () => {
62
+ it('should update thread properties', async () => {
63
+ const updateParams = {
64
+ title: 'Updated Title',
65
+ metadata: { updated: true },
66
+ resourceid: 'resource-1',
67
+ };
68
+
69
+ const mockUpdatedThread = {
70
+ id: threadId,
71
+ ...updateParams,
72
+ createdAt: new Date().toISOString(),
73
+ updatedAt: new Date().toISOString(),
74
+ };
75
+
76
+ mockFetchResponse(mockUpdatedThread);
77
+
78
+ const result = await thread.update(updateParams);
79
+
80
+ expect(global.fetch).toHaveBeenCalledWith(
81
+ `http://localhost:4111/api/memory/threads/${threadId}?agentId=${agentId}`,
82
+ expect.objectContaining({
83
+ method: 'PATCH',
84
+ headers: expect.objectContaining({
85
+ Authorization: 'Bearer test-key',
86
+ }),
87
+ body: JSON.stringify(updateParams),
88
+ }),
89
+ );
90
+ expect(result).toEqual(mockUpdatedThread);
91
+ });
92
+ });
93
+
94
+ describe('delete', () => {
95
+ it('should delete the thread', async () => {
96
+ const mockResponse = { result: 'Thread deleted' };
97
+ mockFetchResponse(mockResponse);
98
+
99
+ const result = await thread.delete();
100
+
101
+ expect(global.fetch).toHaveBeenCalledWith(
102
+ `http://localhost:4111/api/memory/threads/${threadId}?agentId=${agentId}`,
103
+ expect.objectContaining({
104
+ method: 'DELETE',
105
+ headers: expect.objectContaining({
106
+ Authorization: 'Bearer test-key',
107
+ }),
108
+ }),
109
+ );
110
+ expect(result).toEqual(mockResponse);
111
+ });
112
+ });
113
+
114
+ describe('getMessages', () => {
115
+ it('should retrieve thread messages', async () => {
116
+ const mockMessages = {
117
+ messages: [
118
+ { id: 'msg-1', content: 'Hello', role: 'user' },
119
+ { id: 'msg-2', content: 'Hi there', role: 'assistant' },
120
+ ],
121
+ uiMessages: [
122
+ { id: 'msg-1', content: 'Hello', role: 'user' },
123
+ { id: 'msg-2', content: 'Hi there', role: 'assistant' },
124
+ ],
125
+ };
126
+
127
+ mockFetchResponse(mockMessages);
128
+
129
+ const result = await thread.getMessages();
130
+
131
+ expect(global.fetch).toHaveBeenCalledWith(
132
+ `http://localhost:4111/api/memory/threads/${threadId}/messages?agentId=${agentId}`,
133
+ expect.objectContaining({
134
+ headers: expect.objectContaining({
135
+ Authorization: 'Bearer test-key',
136
+ }),
137
+ }),
138
+ );
139
+ expect(result).toEqual(mockMessages);
140
+ });
141
+
142
+ it('should retrieve thread messages with limit', async () => {
143
+ const mockMessages = {
144
+ messages: [{ id: 'msg-1', content: 'Hello', role: 'user' }],
145
+ uiMessages: [{ id: 'msg-1', content: 'Hello', role: 'user' }],
146
+ };
147
+
148
+ mockFetchResponse(mockMessages);
149
+
150
+ const result = await thread.getMessages({ limit: 5 });
151
+
152
+ expect(global.fetch).toHaveBeenCalledWith(
153
+ `http://localhost:4111/api/memory/threads/${threadId}/messages?agentId=${agentId}&limit=5`,
154
+ expect.objectContaining({
155
+ headers: expect.objectContaining({
156
+ Authorization: 'Bearer test-key',
157
+ }),
158
+ }),
159
+ );
160
+ expect(result).toEqual(mockMessages);
161
+ });
162
+ });
163
+
164
+ describe('deleteMessages', () => {
165
+ it('should delete a single message by string ID', async () => {
166
+ const messageId = 'test-message-id';
167
+ const mockResponse = { success: true, message: '1 message deleted successfully' };
168
+
169
+ mockFetchResponse(mockResponse);
170
+
171
+ const result = await thread.deleteMessages(messageId);
172
+
173
+ expect(global.fetch).toHaveBeenCalledWith(
174
+ `http://localhost:4111/api/memory/messages/delete?agentId=${agentId}`,
175
+ expect.objectContaining({
176
+ method: 'POST',
177
+ headers: expect.objectContaining({
178
+ 'content-type': 'application/json',
179
+ Authorization: 'Bearer test-key',
180
+ }),
181
+ body: JSON.stringify({ messageIds: messageId }),
182
+ }),
183
+ );
184
+ expect(result).toEqual(mockResponse);
185
+ });
186
+
187
+ it('should delete multiple messages by array of string IDs', async () => {
188
+ const messageIds = ['msg-1', 'msg-2', 'msg-3'];
189
+ const mockResponse = { success: true, message: '3 messages deleted successfully' };
190
+
191
+ mockFetchResponse(mockResponse);
192
+
193
+ const result = await thread.deleteMessages(messageIds);
194
+
195
+ expect(global.fetch).toHaveBeenCalledWith(
196
+ `http://localhost:4111/api/memory/messages/delete?agentId=${agentId}`,
197
+ expect.objectContaining({
198
+ method: 'POST',
199
+ headers: expect.objectContaining({
200
+ 'content-type': 'application/json',
201
+ Authorization: 'Bearer test-key',
202
+ }),
203
+ body: JSON.stringify({ messageIds }),
204
+ }),
205
+ );
206
+ expect(result).toEqual(mockResponse);
207
+ });
208
+
209
+ it('should delete a message by object with id property', async () => {
210
+ const messageObj = { id: 'test-message-id' };
211
+ const mockResponse = { success: true, message: '1 message deleted successfully' };
212
+
213
+ mockFetchResponse(mockResponse);
214
+
215
+ const result = await thread.deleteMessages(messageObj);
216
+
217
+ expect(global.fetch).toHaveBeenCalledWith(
218
+ `http://localhost:4111/api/memory/messages/delete?agentId=${agentId}`,
219
+ expect.objectContaining({
220
+ method: 'POST',
221
+ headers: expect.objectContaining({
222
+ 'content-type': 'application/json',
223
+ Authorization: 'Bearer test-key',
224
+ }),
225
+ body: JSON.stringify({ messageIds: messageObj }),
226
+ }),
227
+ );
228
+ expect(result).toEqual(mockResponse);
229
+ });
230
+
231
+ it('should delete messages by array of objects', async () => {
232
+ const messageObjs = [{ id: 'msg-1' }, { id: 'msg-2' }];
233
+ const mockResponse = { success: true, message: '2 messages deleted successfully' };
234
+
235
+ mockFetchResponse(mockResponse);
236
+
237
+ const result = await thread.deleteMessages(messageObjs);
238
+
239
+ expect(global.fetch).toHaveBeenCalledWith(
240
+ `http://localhost:4111/api/memory/messages/delete?agentId=${agentId}`,
241
+ expect.objectContaining({
242
+ method: 'POST',
243
+ headers: expect.objectContaining({
244
+ 'content-type': 'application/json',
245
+ Authorization: 'Bearer test-key',
246
+ }),
247
+ body: JSON.stringify({ messageIds: messageObjs }),
248
+ }),
249
+ );
250
+ expect(result).toEqual(mockResponse);
251
+ });
252
+
253
+ it('should handle empty array', async () => {
254
+ const messageIds: string[] = [];
255
+
256
+ (global.fetch as any).mockResolvedValueOnce({
257
+ ok: false,
258
+ status: 400,
259
+ statusText: 'Bad Request',
260
+ json: async () => ({ error: 'messageIds array cannot be empty' }),
261
+ headers: new Headers({
262
+ 'content-type': 'application/json',
263
+ }),
264
+ });
265
+
266
+ await expect(thread.deleteMessages(messageIds)).rejects.toThrow();
267
+ });
268
+
269
+ it('should handle bulk delete errors', async () => {
270
+ const messageIds = ['msg-1', 'msg-2'];
271
+
272
+ (global.fetch as any).mockResolvedValueOnce({
273
+ ok: false,
274
+ status: 500,
275
+ statusText: 'Internal Server Error',
276
+ json: async () => ({ error: 'Database error' }),
277
+ headers: new Headers({
278
+ 'content-type': 'application/json',
279
+ }),
280
+ });
281
+
282
+ await expect(thread.deleteMessages(messageIds)).rejects.toThrow();
283
+ });
284
+ });
285
+ });