@mastra/client-js 0.0.0-ai-v5-20250625173645 → 0.0.0-ai-v5-20250710191716

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.
@@ -0,0 +1,63 @@
1
+ import type { StorageThreadType } from '@mastra/core';
2
+
3
+ import type {
4
+ GetMemoryThreadMessagesResponse,
5
+ ClientOptions,
6
+ UpdateMemoryThreadParams,
7
+ GetMemoryThreadMessagesParams,
8
+ } from '../types';
9
+
10
+ import { BaseResource } from './base';
11
+
12
+ export class NetworkMemoryThread extends BaseResource {
13
+ constructor(
14
+ options: ClientOptions,
15
+ private threadId: string,
16
+ private networkId: string,
17
+ ) {
18
+ super(options);
19
+ }
20
+
21
+ /**
22
+ * Retrieves the memory thread details
23
+ * @returns Promise containing thread details including title and metadata
24
+ */
25
+ get(): Promise<StorageThreadType> {
26
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
27
+ }
28
+
29
+ /**
30
+ * Updates the memory thread properties
31
+ * @param params - Update parameters including title and metadata
32
+ * @returns Promise containing updated thread details
33
+ */
34
+ update(params: UpdateMemoryThreadParams): Promise<StorageThreadType> {
35
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
36
+ method: 'PATCH',
37
+ body: params,
38
+ });
39
+ }
40
+
41
+ /**
42
+ * Deletes the memory thread
43
+ * @returns Promise containing deletion result
44
+ */
45
+ delete(): Promise<{ result: string }> {
46
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
47
+ method: 'DELETE',
48
+ });
49
+ }
50
+
51
+ /**
52
+ * Retrieves messages associated with the thread
53
+ * @param params - Optional parameters including limit for number of messages to retrieve
54
+ * @returns Promise containing thread messages and UI messages
55
+ */
56
+ getMessages(params?: GetMemoryThreadMessagesParams): Promise<GetMemoryThreadMessagesResponse> {
57
+ const query = new URLSearchParams({
58
+ networkId: this.networkId,
59
+ ...(params?.limit ? { limit: params.limit.toString() } : {}),
60
+ });
61
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
62
+ }
63
+ }
@@ -1,10 +1,9 @@
1
1
  import { processDataStream } from '@ai-sdk/ui-utils';
2
2
  import type { GenerateReturn } from '@mastra/core';
3
3
  import type { JSONSchema7 } from 'json-schema';
4
- import { ZodSchema } from 'zod';
5
- import { zodToJsonSchema } from '../utils/zod-to-json-schema';
6
-
4
+ import type { ZodSchema } from 'zod';
7
5
  import type { GenerateParams, ClientOptions, StreamParams, GetNetworkResponse } from '../types';
6
+ import { zodToJsonSchema } from '../utils/zod-to-json-schema';
8
7
 
9
8
  import { BaseResource } from './base';
10
9
 
@@ -0,0 +1,177 @@
1
+ import type { WatchEvent } from '@mastra/core/workflows';
2
+
3
+ import type {
4
+ ClientOptions,
5
+ GetVNextNetworkResponse,
6
+ GenerateVNextNetworkResponse,
7
+ LoopVNextNetworkResponse,
8
+ GenerateOrStreamVNextNetworkParams,
9
+ LoopStreamVNextNetworkParams,
10
+ } from '../types';
11
+
12
+ import { BaseResource } from './base';
13
+
14
+ const RECORD_SEPARATOR = '\x1E';
15
+
16
+ export class VNextNetwork extends BaseResource {
17
+ constructor(
18
+ options: ClientOptions,
19
+ private networkId: string,
20
+ ) {
21
+ super(options);
22
+ }
23
+
24
+ /**
25
+ * Retrieves details about the network
26
+ * @returns Promise containing vNext network details
27
+ */
28
+ details(): Promise<GetVNextNetworkResponse> {
29
+ return this.request(`/api/networks/v-next/${this.networkId}`);
30
+ }
31
+
32
+ /**
33
+ * Generates a response from the v-next network
34
+ * @param params - Generation parameters including message
35
+ * @returns Promise containing the generated response
36
+ */
37
+ generate(params: GenerateOrStreamVNextNetworkParams): Promise<GenerateVNextNetworkResponse> {
38
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
39
+ method: 'POST',
40
+ body: params,
41
+ });
42
+ }
43
+
44
+ /**
45
+ * Generates a response from the v-next network using multiple primitives
46
+ * @param params - Generation parameters including message
47
+ * @returns Promise containing the generated response
48
+ */
49
+ loop(params: { message: string }): Promise<LoopVNextNetworkResponse> {
50
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
51
+ method: 'POST',
52
+ body: params,
53
+ });
54
+ }
55
+
56
+ private async *streamProcessor(stream: ReadableStream): AsyncGenerator<WatchEvent, void, unknown> {
57
+ const reader = stream.getReader();
58
+
59
+ // Track if we've finished reading from the stream
60
+ let doneReading = false;
61
+ // Buffer to accumulate partial chunks
62
+ let buffer = '';
63
+
64
+ try {
65
+ while (!doneReading) {
66
+ // Read the next chunk from the stream
67
+ const { done, value } = await reader.read();
68
+ doneReading = done;
69
+
70
+ // Skip processing if we're done and there's no value
71
+ if (done && !value) continue;
72
+
73
+ try {
74
+ // Decode binary data to text
75
+ const decoded = value ? new TextDecoder().decode(value) : '';
76
+
77
+ // Split the combined buffer and new data by record separator
78
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
79
+
80
+ // The last chunk might be incomplete, so save it for the next iteration
81
+ buffer = chunks.pop() || '';
82
+
83
+ // Process complete chunks
84
+ for (const chunk of chunks) {
85
+ if (chunk) {
86
+ // Only process non-empty chunks
87
+ if (typeof chunk === 'string') {
88
+ try {
89
+ const parsedChunk = JSON.parse(chunk);
90
+ yield parsedChunk;
91
+ } catch {
92
+ // Silently ignore parsing errors to maintain stream processing
93
+ // This allows the stream to continue even if one record is malformed
94
+ }
95
+ }
96
+ }
97
+ }
98
+ } catch {
99
+ // Silently ignore parsing errors to maintain stream processing
100
+ // This allows the stream to continue even if one record is malformed
101
+ }
102
+ }
103
+
104
+ // Process any remaining data in the buffer after stream is done
105
+ if (buffer) {
106
+ try {
107
+ yield JSON.parse(buffer);
108
+ } catch {
109
+ // Ignore parsing error for final chunk
110
+ }
111
+ }
112
+ } finally {
113
+ // Always ensure we clean up the reader
114
+ reader.cancel().catch(() => {
115
+ // Ignore cancel errors
116
+ });
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Streams a response from the v-next network
122
+ * @param params - Stream parameters including message
123
+ * @returns Promise containing the results
124
+ */
125
+ async stream(params: GenerateOrStreamVNextNetworkParams, onRecord: (record: WatchEvent) => void) {
126
+ const response: Response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
127
+ method: 'POST',
128
+ body: params,
129
+ stream: true,
130
+ });
131
+
132
+ if (!response.ok) {
133
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
134
+ }
135
+
136
+ if (!response.body) {
137
+ throw new Error('Response body is null');
138
+ }
139
+
140
+ for await (const record of this.streamProcessor(response.body)) {
141
+ if (typeof record === 'string') {
142
+ onRecord(JSON.parse(record));
143
+ } else {
144
+ onRecord(record);
145
+ }
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Streams a response from the v-next network loop
151
+ * @param params - Stream parameters including message
152
+ * @returns Promise containing the results
153
+ */
154
+ async loopStream(params: LoopStreamVNextNetworkParams, onRecord: (record: WatchEvent) => void) {
155
+ const response: Response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
156
+ method: 'POST',
157
+ body: params,
158
+ stream: true,
159
+ });
160
+
161
+ if (!response.ok) {
162
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
163
+ }
164
+
165
+ if (!response.body) {
166
+ throw new Error('Response body is null');
167
+ }
168
+
169
+ for await (const record of this.streamProcessor(response.body)) {
170
+ if (typeof record === 'string') {
171
+ onRecord(JSON.parse(record));
172
+ } else {
173
+ onRecord(record);
174
+ }
175
+ }
176
+ }
177
+ }
@@ -115,10 +115,10 @@ export class Workflow extends BaseResource {
115
115
  if (params?.toDate) {
116
116
  searchParams.set('toDate', params.toDate.toISOString());
117
117
  }
118
- if (params?.limit) {
118
+ if (params?.limit !== null && params?.limit !== undefined && !isNaN(Number(params?.limit))) {
119
119
  searchParams.set('limit', String(params.limit));
120
120
  }
121
- if (params?.offset) {
121
+ if (params?.offset !== null && params?.offset !== undefined && !isNaN(Number(params?.offset))) {
122
122
  searchParams.set('offset', String(params.offset));
123
123
  }
124
124
  if (params?.resourceId) {
@@ -150,6 +150,29 @@ export class Workflow extends BaseResource {
150
150
  return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
151
151
  }
152
152
 
153
+ /**
154
+ * Cancels a specific workflow run by its ID
155
+ * @param runId - The ID of the workflow run to cancel
156
+ * @returns Promise containing a success message
157
+ */
158
+ cancelRun(runId: string): Promise<{ message: string }> {
159
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
160
+ method: 'POST',
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Sends an event to a specific workflow run by its ID
166
+ * @param params - Object containing the runId, event and data
167
+ * @returns Promise containing a success message
168
+ */
169
+ sendRunEvent(params: { runId: string; event: string; data: unknown }): Promise<{ message: string }> {
170
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
171
+ method: 'POST',
172
+ body: { event: params.event, data: params.data },
173
+ });
174
+ }
175
+
153
176
  /**
154
177
  * Creates a new workflow run
155
178
  * @param params - Optional object containing the optional runId
@@ -237,9 +260,9 @@ export class Workflow extends BaseResource {
237
260
  }
238
261
 
239
262
  /**
240
- * Starts a vNext workflow run and returns a stream
263
+ * Starts a workflow run and returns a stream
241
264
  * @param params - Object containing the optional runId, inputData and runtimeContext
242
- * @returns Promise containing the vNext workflow execution results
265
+ * @returns Promise containing the workflow execution results
243
266
  */
244
267
  async stream(params: { runId?: string; inputData: Record<string, any>; runtimeContext?: RuntimeContext }) {
245
268
  const searchParams = new URLSearchParams();
@@ -267,7 +290,7 @@ export class Workflow extends BaseResource {
267
290
  }
268
291
 
269
292
  // Create a transform stream that processes the response body
270
- const transformStream = new TransformStream<ArrayBuffer, WorkflowWatchResult>({
293
+ const transformStream = new TransformStream<ArrayBuffer, { type: string; payload: any }>({
271
294
  start() {},
272
295
  async transform(chunk, controller) {
273
296
  try {
package/src/types.ts CHANGED
@@ -34,6 +34,7 @@ export interface ClientOptions {
34
34
  /** Custom headers to include with requests */
35
35
  headers?: Record<string, string>;
36
36
  /** Abort signal for request */
37
+ abortSignal?: AbortSignal;
37
38
  }
38
39
 
39
40
  export interface RequestOptions {
@@ -41,7 +42,6 @@ export interface RequestOptions {
41
42
  headers?: Record<string, string>;
42
43
  body?: any;
43
44
  stream?: boolean;
44
- signal?: AbortSignal;
45
45
  }
46
46
 
47
47
  type WithoutMethods<T> = {
@@ -71,7 +71,9 @@ export type GenerateParams<T extends JSONSchema7 | ZodSchema | undefined = undef
71
71
  experimental_output?: T;
72
72
  runtimeContext?: RuntimeContext | Record<string, any>;
73
73
  clientTools?: ToolsInput;
74
- } & WithoutMethods<Omit<AgentGenerateOptions<T>, 'output' | 'experimental_output' | 'runtimeContext' | 'clientTools'>>;
74
+ } & WithoutMethods<
75
+ Omit<AgentGenerateOptions<T>, 'output' | 'experimental_output' | 'runtimeContext' | 'clientTools' | 'abortSignal'>
76
+ >;
75
77
 
76
78
  export type StreamParams<T extends JSONSchema7 | ZodSchema | undefined = undefined> = {
77
79
  messages: string | string[] | CoreMessage[] | UIMessage[];
@@ -79,7 +81,9 @@ export type StreamParams<T extends JSONSchema7 | ZodSchema | undefined = undefin
79
81
  experimental_output?: T;
80
82
  runtimeContext?: RuntimeContext | Record<string, any>;
81
83
  clientTools?: ToolsInput;
82
- } & WithoutMethods<Omit<AgentStreamOptions<T>, 'output' | 'experimental_output' | 'runtimeContext' | 'clientTools'>>;
84
+ } & WithoutMethods<
85
+ Omit<AgentStreamOptions<T>, 'output' | 'experimental_output' | 'runtimeContext' | 'clientTools' | 'abortSignal'>
86
+ >;
83
87
 
84
88
  export interface GetEvalsByAgentIdResponse extends GetAgentResponse {
85
89
  evals: any[];
@@ -140,6 +144,17 @@ export interface GetWorkflowResponse {
140
144
  suspendSchema: string;
141
145
  };
142
146
  };
147
+ allSteps: {
148
+ [key: string]: {
149
+ id: string;
150
+ description: string;
151
+ inputSchema: string;
152
+ outputSchema: string;
153
+ resumeSchema: string;
154
+ suspendSchema: string;
155
+ isWorkflow: boolean;
156
+ };
157
+ };
143
158
  stepGraph: Workflow['serializedStepGraph'];
144
159
  inputSchema: string;
145
160
  outputSchema: string;
@@ -183,6 +198,11 @@ export interface SaveMessageToMemoryParams {
183
198
  agentId: string;
184
199
  }
185
200
 
201
+ export interface SaveNetworkMessageToMemoryParams {
202
+ messages: MastraMessageV1[];
203
+ networkId: string;
204
+ }
205
+
186
206
  export type SaveMessageToMemoryResponse = MastraMessageV1[];
187
207
 
188
208
  export interface CreateMemoryThreadParams {
@@ -193,6 +213,14 @@ export interface CreateMemoryThreadParams {
193
213
  agentId: string;
194
214
  }
195
215
 
216
+ export interface CreateNetworkMemoryThreadParams {
217
+ title?: string;
218
+ metadata?: Record<string, any>;
219
+ resourceId: string;
220
+ threadId?: string;
221
+ networkId: string;
222
+ }
223
+
196
224
  export type CreateMemoryThreadResponse = StorageThreadType;
197
225
 
198
226
  export interface GetMemoryThreadParams {
@@ -200,6 +228,11 @@ export interface GetMemoryThreadParams {
200
228
  agentId: string;
201
229
  }
202
230
 
231
+ export interface GetNetworkMemoryThreadParams {
232
+ resourceId: string;
233
+ networkId: string;
234
+ }
235
+
203
236
  export type GetMemoryThreadResponse = StorageThreadType[];
204
237
 
205
238
  export interface UpdateMemoryThreadParams {
@@ -310,6 +343,7 @@ export interface GetTelemetryParams {
310
343
  }
311
344
 
312
345
  export interface GetNetworkResponse {
346
+ id: string;
313
347
  name: string;
314
348
  instructions: string;
315
349
  agents: Array<{
@@ -324,6 +358,59 @@ export interface GetNetworkResponse {
324
358
  state?: Record<string, any>;
325
359
  }
326
360
 
361
+ export interface GetVNextNetworkResponse {
362
+ id: string;
363
+ name: string;
364
+ instructions: string;
365
+ agents: Array<{
366
+ name: string;
367
+ provider: string;
368
+ modelId: string;
369
+ }>;
370
+ routingModel: {
371
+ provider: string;
372
+ modelId: string;
373
+ };
374
+ workflows: Array<{
375
+ name: string;
376
+ description: string;
377
+ inputSchema: string | undefined;
378
+ outputSchema: string | undefined;
379
+ }>;
380
+ tools: Array<{
381
+ id: string;
382
+ description: string;
383
+ }>;
384
+ }
385
+
386
+ export interface GenerateVNextNetworkResponse {
387
+ task: string;
388
+ result: string;
389
+ resourceId: string;
390
+ resourceType: 'none' | 'tool' | 'agent' | 'workflow';
391
+ }
392
+
393
+ export interface GenerateOrStreamVNextNetworkParams {
394
+ message: string;
395
+ threadId?: string;
396
+ resourceId?: string;
397
+ }
398
+
399
+ export interface LoopStreamVNextNetworkParams {
400
+ message: string;
401
+ threadId?: string;
402
+ resourceId?: string;
403
+ maxIterations?: number;
404
+ }
405
+
406
+ export interface LoopVNextNetworkResponse {
407
+ status: 'success';
408
+ result: {
409
+ text: string;
410
+ };
411
+ steps: WorkflowResult<any, any>['steps'];
412
+ }
413
+
327
414
  export interface McpServerListResponse {
328
415
  servers: ServerInfo[];
329
416
  next: string | null;
@@ -1,7 +1,8 @@
1
1
  import { isVercelTool } from '@mastra/core/tools';
2
2
  import { zodToJsonSchema } from './zod-to-json-schema';
3
+ import type { ToolsInput } from '@mastra/core/agent';
3
4
 
4
- export function processClientTools(clientTools: Record<string, any> | undefined): Record<string, any> | undefined {
5
+ export function processClientTools(clientTools: ToolsInput | undefined): ToolsInput | undefined {
5
6
  if (!clientTools) {
6
7
  return undefined;
7
8
  }
@@ -27,5 +28,5 @@ export function processClientTools(clientTools: Record<string, any> | undefined)
27
28
  ];
28
29
  }
29
30
  }),
30
- ) as Record<string, any>;
31
+ );
31
32
  }