@mastra/client-js 0.0.0-ai-v5-20250626003446 → 0.0.0-ai-v5-20250718021026

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,194 @@
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
+ import { parseClientRuntimeContext } from '../utils';
14
+ import type { RuntimeContext } from '@mastra/core/runtime-context';
15
+
16
+ const RECORD_SEPARATOR = '\x1E';
17
+
18
+ export class VNextNetwork extends BaseResource {
19
+ constructor(
20
+ options: ClientOptions,
21
+ private networkId: string,
22
+ ) {
23
+ super(options);
24
+ }
25
+
26
+ /**
27
+ * Retrieves details about the network
28
+ * @returns Promise containing vNext network details
29
+ */
30
+ details(): Promise<GetVNextNetworkResponse> {
31
+ return this.request(`/api/networks/v-next/${this.networkId}`);
32
+ }
33
+
34
+ /**
35
+ * Generates a response from the v-next network
36
+ * @param params - Generation parameters including message
37
+ * @returns Promise containing the generated response
38
+ */
39
+ generate(params: GenerateOrStreamVNextNetworkParams): Promise<GenerateVNextNetworkResponse> {
40
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
41
+ method: 'POST',
42
+ body: {
43
+ ...params,
44
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
45
+ },
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Generates a response from the v-next network using multiple primitives
51
+ * @param params - Generation parameters including message
52
+ * @returns Promise containing the generated response
53
+ */
54
+ loop(params: {
55
+ message: string;
56
+ runtimeContext?: RuntimeContext | Record<string, any>;
57
+ }): Promise<LoopVNextNetworkResponse> {
58
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
59
+ method: 'POST',
60
+ body: {
61
+ ...params,
62
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
63
+ },
64
+ });
65
+ }
66
+
67
+ private async *streamProcessor(stream: ReadableStream): AsyncGenerator<WatchEvent, void, unknown> {
68
+ const reader = stream.getReader();
69
+
70
+ // Track if we've finished reading from the stream
71
+ let doneReading = false;
72
+ // Buffer to accumulate partial chunks
73
+ let buffer = '';
74
+
75
+ try {
76
+ while (!doneReading) {
77
+ // Read the next chunk from the stream
78
+ const { done, value } = await reader.read();
79
+ doneReading = done;
80
+
81
+ // Skip processing if we're done and there's no value
82
+ if (done && !value) continue;
83
+
84
+ try {
85
+ // Decode binary data to text
86
+ const decoded = value ? new TextDecoder().decode(value) : '';
87
+
88
+ // Split the combined buffer and new data by record separator
89
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
90
+
91
+ // The last chunk might be incomplete, so save it for the next iteration
92
+ buffer = chunks.pop() || '';
93
+
94
+ // Process complete chunks
95
+ for (const chunk of chunks) {
96
+ if (chunk) {
97
+ // Only process non-empty chunks
98
+ if (typeof chunk === 'string') {
99
+ try {
100
+ const parsedChunk = JSON.parse(chunk);
101
+ yield parsedChunk;
102
+ } catch {
103
+ // Silently ignore parsing errors to maintain stream processing
104
+ // This allows the stream to continue even if one record is malformed
105
+ }
106
+ }
107
+ }
108
+ }
109
+ } catch {
110
+ // Silently ignore parsing errors to maintain stream processing
111
+ // This allows the stream to continue even if one record is malformed
112
+ }
113
+ }
114
+
115
+ // Process any remaining data in the buffer after stream is done
116
+ if (buffer) {
117
+ try {
118
+ yield JSON.parse(buffer);
119
+ } catch {
120
+ // Ignore parsing error for final chunk
121
+ }
122
+ }
123
+ } finally {
124
+ // Always ensure we clean up the reader
125
+ reader.cancel().catch(() => {
126
+ // Ignore cancel errors
127
+ });
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Streams a response from the v-next network
133
+ * @param params - Stream parameters including message
134
+ * @returns Promise containing the results
135
+ */
136
+ async stream(params: GenerateOrStreamVNextNetworkParams, onRecord: (record: WatchEvent) => void) {
137
+ const response: Response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
138
+ method: 'POST',
139
+ body: {
140
+ ...params,
141
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
142
+ },
143
+ stream: true,
144
+ });
145
+
146
+ if (!response.ok) {
147
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
148
+ }
149
+
150
+ if (!response.body) {
151
+ throw new Error('Response body is null');
152
+ }
153
+
154
+ for await (const record of this.streamProcessor(response.body)) {
155
+ if (typeof record === 'string') {
156
+ onRecord(JSON.parse(record));
157
+ } else {
158
+ onRecord(record);
159
+ }
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Streams a response from the v-next network loop
165
+ * @param params - Stream parameters including message
166
+ * @returns Promise containing the results
167
+ */
168
+ async loopStream(params: LoopStreamVNextNetworkParams, onRecord: (record: WatchEvent) => void) {
169
+ const response: Response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
170
+ method: 'POST',
171
+ body: {
172
+ ...params,
173
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
174
+ },
175
+ stream: true,
176
+ });
177
+
178
+ if (!response.ok) {
179
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
180
+ }
181
+
182
+ if (!response.body) {
183
+ throw new Error('Response body is null');
184
+ }
185
+
186
+ for await (const record of this.streamProcessor(response.body)) {
187
+ if (typeof record === 'string') {
188
+ onRecord(JSON.parse(record));
189
+ } else {
190
+ onRecord(record);
191
+ }
192
+ }
193
+ }
194
+ }
@@ -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();
@@ -266,8 +289,11 @@ export class Workflow extends BaseResource {
266
289
  throw new Error('Response body is null');
267
290
  }
268
291
 
292
+ //using undefined instead of empty string to avoid parsing errors
293
+ let failedChunk: string | undefined = undefined;
294
+
269
295
  // Create a transform stream that processes the response body
270
- const transformStream = new TransformStream<ArrayBuffer, WorkflowWatchResult>({
296
+ const transformStream = new TransformStream<ArrayBuffer, { type: string; payload: any }>({
271
297
  start() {},
272
298
  async transform(chunk, controller) {
273
299
  try {
@@ -280,11 +306,13 @@ export class Workflow extends BaseResource {
280
306
  // Process each chunk
281
307
  for (const chunk of chunks) {
282
308
  if (chunk) {
309
+ const newChunk: string = failedChunk ? failedChunk + chunk : chunk;
283
310
  try {
284
- const parsedChunk = JSON.parse(chunk);
311
+ const parsedChunk = JSON.parse(newChunk);
285
312
  controller.enqueue(parsedChunk);
286
- } catch {
287
- // Silently ignore parsing errors
313
+ failedChunk = undefined;
314
+ } catch (error) {
315
+ failedChunk = newChunk;
288
316
  }
289
317
  }
290
318
  }
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,61 @@ 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
+ runtimeContext?: RuntimeContext | Record<string, any>;
398
+ }
399
+
400
+ export interface LoopStreamVNextNetworkParams {
401
+ message: string;
402
+ threadId?: string;
403
+ resourceId?: string;
404
+ maxIterations?: number;
405
+ runtimeContext?: RuntimeContext | Record<string, any>;
406
+ }
407
+
408
+ export interface LoopVNextNetworkResponse {
409
+ status: 'success';
410
+ result: {
411
+ text: string;
412
+ };
413
+ steps: WorkflowResult<any, any>['steps'];
414
+ }
415
+
327
416
  export interface McpServerListResponse {
328
417
  servers: ServerInfo[];
329
418
  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
  }