@mastra/client-js 0.0.0-commonjs-20250227130920 → 0.0.0-default-storage-virtual-file-20250410035748

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,6 +1,8 @@
1
- import { CoreMessage, OutputType, StorageThreadType, AiMessageType, MessageType, StepAction, StepGraph, QueryResult, BaseLogMessage, GenerateReturn } from '@mastra/core';
1
+ import { CoreMessage, AiMessageType, StorageThreadType, MessageType, StepAction, StepGraph, WorkflowRunResult as WorkflowRunResult$1, QueryResult, BaseLogMessage, GenerateReturn } from '@mastra/core';
2
2
  import { JSONSchema7 } from 'json-schema';
3
3
  import { ZodSchema } from 'zod';
4
+ import { processDataStream } from '@ai-sdk/ui-utils';
5
+ import { AgentGenerateOptions, AgentStreamOptions } from '@mastra/core/agent';
4
6
 
5
7
  interface ClientOptions {
6
8
  /** Base URL for API requests */
@@ -19,25 +21,21 @@ interface RequestOptions {
19
21
  headers?: Record<string, string>;
20
22
  body?: any;
21
23
  stream?: boolean;
24
+ signal?: AbortSignal;
22
25
  }
23
26
  interface GetAgentResponse {
24
27
  name: string;
25
28
  instructions: string;
26
29
  tools: Record<string, GetToolResponse>;
27
30
  provider: string;
31
+ modelId: string;
28
32
  }
29
- interface GenerateParams<T extends JSONSchema7 | ZodSchema | undefined = undefined> {
30
- messages: string | string[] | CoreMessage[];
31
- threadId?: string;
32
- resourceid?: string;
33
- output?: OutputType | T;
34
- }
35
- interface StreamParams<T extends JSONSchema7 | ZodSchema | undefined = undefined> {
36
- messages: string | string[] | CoreMessage[];
37
- threadId?: string;
38
- resourceid?: string;
39
- output?: OutputType | T;
40
- }
33
+ type GenerateParams<T extends JSONSchema7 | ZodSchema | undefined = undefined> = {
34
+ messages: string | string[] | CoreMessage[] | AiMessageType[];
35
+ } & Partial<AgentGenerateOptions<T>>;
36
+ type StreamParams<T extends JSONSchema7 | ZodSchema | undefined = undefined> = {
37
+ messages: string | string[] | CoreMessage[] | AiMessageType[];
38
+ } & Omit<AgentStreamOptions<T>, 'onFinish' | 'onStepFinish' | 'telemetry'>;
41
39
  interface GetEvalsByAgentIdResponse extends GetAgentResponse {
42
40
  evals: any[];
43
41
  }
@@ -53,7 +51,18 @@ interface GetWorkflowResponse {
53
51
  steps: Record<string, StepAction<any, any, any, any>>;
54
52
  stepGraph: StepGraph;
55
53
  stepSubscriberGraph: Record<string, StepGraph>;
54
+ workflowId?: string;
56
55
  }
56
+ type WorkflowRunResult = {
57
+ activePaths: Record<string, {
58
+ status: string;
59
+ suspendPayload?: any;
60
+ stepPath: string[];
61
+ }>;
62
+ results: WorkflowRunResult$1<any, any, any>['results'];
63
+ timestamp: number;
64
+ runId: string;
65
+ };
57
66
  interface UpsertVectorParams {
58
67
  indexName: string;
59
68
  vectors: number[][];
@@ -116,8 +125,47 @@ interface GetLogParams {
116
125
  }
117
126
  type GetLogsResponse = BaseLogMessage[];
118
127
  type RequestFunction = (path: string, options?: RequestOptions) => Promise<any>;
128
+ type SpanStatus = {
129
+ code: number;
130
+ };
131
+ type SpanOther = {
132
+ droppedAttributesCount: number;
133
+ droppedEventsCount: number;
134
+ droppedLinksCount: number;
135
+ };
136
+ type SpanEventAttributes = {
137
+ key: string;
138
+ value: {
139
+ [key: string]: string | number | boolean | null;
140
+ };
141
+ };
142
+ type SpanEvent = {
143
+ attributes: SpanEventAttributes[];
144
+ name: string;
145
+ timeUnixNano: string;
146
+ droppedAttributesCount: number;
147
+ };
148
+ type Span = {
149
+ id: string;
150
+ parentSpanId: string | null;
151
+ traceId: string;
152
+ name: string;
153
+ scope: string;
154
+ kind: number;
155
+ status: SpanStatus;
156
+ events: SpanEvent[];
157
+ links: any[];
158
+ attributes: Record<string, string | number | boolean | null>;
159
+ startTime: number;
160
+ endTime: number;
161
+ duration: number;
162
+ other: SpanOther;
163
+ createdAt: string;
164
+ };
119
165
  interface GetTelemetryResponse {
120
- traces: any[];
166
+ traces: {
167
+ traces: Span[];
168
+ };
121
169
  }
122
170
  interface GetTelemetryParams {
123
171
  name?: string;
@@ -126,6 +174,20 @@ interface GetTelemetryParams {
126
174
  perPage?: number;
127
175
  attribute?: Record<string, string>;
128
176
  }
177
+ interface GetNetworkResponse {
178
+ name: string;
179
+ instructions: string;
180
+ agents: Array<{
181
+ name: string;
182
+ provider: string;
183
+ modelId: string;
184
+ }>;
185
+ routingModel: {
186
+ provider: string;
187
+ modelId: string;
188
+ };
189
+ state?: Record<string, any>;
190
+ }
129
191
 
130
192
  declare class BaseResource {
131
193
  readonly options: ClientOptions;
@@ -139,8 +201,38 @@ declare class BaseResource {
139
201
  request<T>(path: string, options?: RequestOptions): Promise<T>;
140
202
  }
141
203
 
204
+ declare class AgentVoice extends BaseResource {
205
+ private agentId;
206
+ constructor(options: ClientOptions, agentId: string);
207
+ /**
208
+ * Convert text to speech using the agent's voice provider
209
+ * @param text - Text to convert to speech
210
+ * @param options - Optional provider-specific options for speech generation
211
+ * @returns Promise containing the audio data
212
+ */
213
+ speak(text: string, options?: {
214
+ speaker?: string;
215
+ [key: string]: any;
216
+ }): Promise<Response>;
217
+ /**
218
+ * Convert speech to text using the agent's voice provider
219
+ * @param audio - Audio data to transcribe
220
+ * @param options - Optional provider-specific options
221
+ * @returns Promise containing the transcribed text
222
+ */
223
+ listen(audio: Blob, options?: Record<string, any>): Promise<Response>;
224
+ /**
225
+ * Get available speakers for the agent's voice provider
226
+ * @returns Promise containing list of available speakers
227
+ */
228
+ getSpeakers(): Promise<Array<{
229
+ voiceId: string;
230
+ [key: string]: any;
231
+ }>>;
232
+ }
142
233
  declare class Agent extends BaseResource {
143
234
  private agentId;
235
+ readonly voice: AgentVoice;
144
236
  constructor(options: ClientOptions, agentId: string);
145
237
  /**
146
238
  * Retrieves details about the agent
@@ -156,9 +248,11 @@ declare class Agent extends BaseResource {
156
248
  /**
157
249
  * Streams a response from the agent
158
250
  * @param params - Stream parameters including prompt
159
- * @returns Promise containing the streamed response
251
+ * @returns Promise containing the enhanced Response object with processDataStream method
160
252
  */
161
- stream<T extends JSONSchema7 | ZodSchema | undefined = undefined>(params: StreamParams<T>): Promise<Response>;
253
+ stream<T extends JSONSchema7 | ZodSchema | undefined = undefined>(params: StreamParams<T>): Promise<Response & {
254
+ processDataStream: (options?: Omit<Parameters<typeof processDataStream>[0], 'stream'>) => Promise<void>;
255
+ }>;
162
256
  /**
163
257
  * Gets details about a specific tool available to the agent
164
258
  * @param toolId - ID of the tool to retrieve
@@ -177,6 +271,30 @@ declare class Agent extends BaseResource {
177
271
  liveEvals(): Promise<GetEvalsByAgentIdResponse>;
178
272
  }
179
273
 
274
+ declare class Network extends BaseResource {
275
+ private networkId;
276
+ constructor(options: ClientOptions, networkId: string);
277
+ /**
278
+ * Retrieves details about the network
279
+ * @returns Promise containing network details
280
+ */
281
+ details(): Promise<GetNetworkResponse>;
282
+ /**
283
+ * Generates a response from the agent
284
+ * @param params - Generation parameters including prompt
285
+ * @returns Promise containing the generated response
286
+ */
287
+ generate<T extends JSONSchema7 | ZodSchema | undefined = undefined>(params: GenerateParams<T>): Promise<GenerateReturn<T>>;
288
+ /**
289
+ * Streams a response from the agent
290
+ * @param params - Stream parameters including prompt
291
+ * @returns Promise containing the enhanced Response object with processDataStream method
292
+ */
293
+ stream<T extends JSONSchema7 | ZodSchema | undefined = undefined>(params: StreamParams<T>): Promise<Response & {
294
+ processDataStream: (options?: Omit<Parameters<typeof processDataStream>[0], 'stream'>) => Promise<void>;
295
+ }>;
296
+ }
297
+
180
298
  declare class MemoryThread extends BaseResource {
181
299
  private threadId;
182
300
  private agentId;
@@ -261,13 +379,34 @@ declare class Workflow extends BaseResource {
261
379
  */
262
380
  details(): Promise<GetWorkflowResponse>;
263
381
  /**
382
+ * @deprecated Use `startAsync` instead
264
383
  * Executes the workflow with the provided parameters
265
384
  * @param params - Parameters required for workflow execution
266
385
  * @returns Promise containing the workflow execution results
267
386
  */
268
- execute(params: Record<string, any>): Promise<Record<string, any>>;
387
+ execute(params: Record<string, any>): Promise<WorkflowRunResult>;
269
388
  /**
270
- * Resumes a suspended workflow step
389
+ * Creates a new workflow run
390
+ * @returns Promise containing the generated run ID
391
+ */
392
+ createRun(params?: {
393
+ runId?: string;
394
+ }): Promise<{
395
+ runId: string;
396
+ }>;
397
+ /**
398
+ * Starts a workflow run synchronously without waiting for the workflow to complete
399
+ * @param params - Object containing the runId and triggerData
400
+ * @returns Promise containing success message
401
+ */
402
+ start(params: {
403
+ runId: string;
404
+ triggerData: Record<string, any>;
405
+ }): Promise<{
406
+ message: string;
407
+ }>;
408
+ /**
409
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
271
410
  * @param stepId - ID of the step to resume
272
411
  * @param runId - ID of the workflow run
273
412
  * @param context - Context to resume the workflow with
@@ -277,12 +416,44 @@ declare class Workflow extends BaseResource {
277
416
  stepId: string;
278
417
  runId: string;
279
418
  context: Record<string, any>;
280
- }): Promise<Record<string, any>>;
419
+ }): Promise<{
420
+ message: string;
421
+ }>;
422
+ /**
423
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
424
+ * @param params - Object containing the optional runId and triggerData
425
+ * @returns Promise containing the workflow execution results
426
+ */
427
+ startAsync(params: {
428
+ runId?: string;
429
+ triggerData: Record<string, any>;
430
+ }): Promise<WorkflowRunResult>;
431
+ /**
432
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
433
+ * @param params - Object containing the runId, stepId, and context
434
+ * @returns Promise containing the workflow resume results
435
+ */
436
+ resumeAsync(params: {
437
+ runId: string;
438
+ stepId: string;
439
+ context: Record<string, any>;
440
+ }): Promise<WorkflowRunResult>;
441
+ /**
442
+ * Creates an async generator that processes a readable stream and yields records
443
+ * separated by the Record Separator character (\x1E)
444
+ *
445
+ * @param stream - The readable stream to process
446
+ * @returns An async generator that yields parsed records
447
+ */
448
+ private streamProcessor;
281
449
  /**
282
450
  * Watches workflow transitions in real-time
283
- * @returns Promise containing the workflow watch stream
451
+ * @param runId - Optional run ID to filter the watch stream
452
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
284
453
  */
285
- watch(): Promise<Response>;
454
+ watch({ runId }: {
455
+ runId?: string;
456
+ }, onRecord: (record: WorkflowRunResult) => void): Promise<void>;
286
457
  }
287
458
 
288
459
  declare class Tool extends BaseResource {
@@ -400,6 +571,17 @@ declare class MastraClient extends BaseResource {
400
571
  * @returns Promise containing telemetry data
401
572
  */
402
573
  getTelemetry(params?: GetTelemetryParams): Promise<GetTelemetryResponse>;
574
+ /**
575
+ * Retrieves all available networks
576
+ * @returns Promise containing map of network IDs to network details
577
+ */
578
+ getNetworks(): Promise<Record<string, GetNetworkResponse>>;
579
+ /**
580
+ * Gets a network instance by ID
581
+ * @param networkId - ID of the network to retrieve
582
+ * @returns Network instance
583
+ */
584
+ getNetwork(networkId: string): Network;
403
585
  }
404
586
 
405
- 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 GetTelemetryParams, type GetTelemetryResponse, type GetToolResponse, type GetVectorIndexResponse, type GetWorkflowResponse, MastraClient, type QueryVectorParams, type QueryVectorResponse, type RequestFunction, type RequestOptions, type SaveMessageToMemoryParams, type SaveMessageToMemoryResponse, type StreamParams, type UpdateMemoryThreadParams, type UpsertVectorParams };
587
+ 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 GetVectorIndexResponse, type GetWorkflowResponse, MastraClient, type QueryVectorParams, type QueryVectorResponse, type RequestFunction, type RequestOptions, type SaveMessageToMemoryParams, type SaveMessageToMemoryResponse, type StreamParams, type UpdateMemoryThreadParams, type UpsertVectorParams, type WorkflowRunResult };
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ZodSchema } from 'zod';
2
2
  import { zodToJsonSchema } from 'zod-to-json-schema';
3
+ import { processDataStream } from '@ai-sdk/ui-utils';
3
4
 
4
5
  // src/resources/agent.ts
5
6
 
@@ -24,11 +25,12 @@ var BaseResource = class {
24
25
  const response = await fetch(`${baseUrl}${path}`, {
25
26
  ...options,
26
27
  headers: {
27
- "Content-Type": "application/json",
28
28
  ...headers,
29
29
  ...options.headers
30
+ // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
31
+ // 'x-mastra-client-type': 'js',
30
32
  },
31
- body: options.body ? JSON.stringify(options.body) : void 0
33
+ body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
32
34
  });
33
35
  if (!response.ok) {
34
36
  const errorBody = await response.text();
@@ -62,11 +64,60 @@ var BaseResource = class {
62
64
  };
63
65
 
64
66
  // src/resources/agent.ts
67
+ var AgentVoice = class extends BaseResource {
68
+ constructor(options, agentId) {
69
+ super(options);
70
+ this.agentId = agentId;
71
+ this.agentId = agentId;
72
+ }
73
+ /**
74
+ * Convert text to speech using the agent's voice provider
75
+ * @param text - Text to convert to speech
76
+ * @param options - Optional provider-specific options for speech generation
77
+ * @returns Promise containing the audio data
78
+ */
79
+ async speak(text, options) {
80
+ return this.request(`/api/agents/${this.agentId}/voice/speak`, {
81
+ method: "POST",
82
+ headers: {
83
+ "Content-Type": "application/json"
84
+ },
85
+ body: { input: text, options },
86
+ stream: true
87
+ });
88
+ }
89
+ /**
90
+ * Convert speech to text using the agent's voice provider
91
+ * @param audio - Audio data to transcribe
92
+ * @param options - Optional provider-specific options
93
+ * @returns Promise containing the transcribed text
94
+ */
95
+ listen(audio, options) {
96
+ const formData = new FormData();
97
+ formData.append("audio", audio);
98
+ if (options) {
99
+ formData.append("options", JSON.stringify(options));
100
+ }
101
+ return this.request(`/api/agents/${this.agentId}/voice/listen`, {
102
+ method: "POST",
103
+ body: formData
104
+ });
105
+ }
106
+ /**
107
+ * Get available speakers for the agent's voice provider
108
+ * @returns Promise containing list of available speakers
109
+ */
110
+ getSpeakers() {
111
+ return this.request(`/api/agents/${this.agentId}/voice/speakers`);
112
+ }
113
+ };
65
114
  var Agent = class extends BaseResource {
66
115
  constructor(options, agentId) {
67
116
  super(options);
68
117
  this.agentId = agentId;
118
+ this.voice = new AgentVoice(options, this.agentId);
69
119
  }
120
+ voice;
70
121
  /**
71
122
  * Retrieves details about the agent
72
123
  * @returns Promise containing agent details including model and instructions
@@ -82,7 +133,8 @@ var Agent = class extends BaseResource {
82
133
  generate(params) {
83
134
  const processedParams = {
84
135
  ...params,
85
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output
136
+ 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
86
138
  };
87
139
  return this.request(`/api/agents/${this.agentId}/generate`, {
88
140
  method: "POST",
@@ -92,18 +144,29 @@ var Agent = class extends BaseResource {
92
144
  /**
93
145
  * Streams a response from the agent
94
146
  * @param params - Stream parameters including prompt
95
- * @returns Promise containing the streamed response
147
+ * @returns Promise containing the enhanced Response object with processDataStream method
96
148
  */
97
- stream(params) {
149
+ async stream(params) {
98
150
  const processedParams = {
99
151
  ...params,
100
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output
152
+ 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
101
154
  };
102
- return this.request(`/api/agents/${this.agentId}/stream`, {
155
+ const response = await this.request(`/api/agents/${this.agentId}/stream`, {
103
156
  method: "POST",
104
157
  body: processedParams,
105
158
  stream: true
106
159
  });
160
+ if (!response.body) {
161
+ throw new Error("No response body");
162
+ }
163
+ response.processDataStream = async (options = {}) => {
164
+ await processDataStream({
165
+ stream: response.body,
166
+ ...options
167
+ });
168
+ };
169
+ return response;
107
170
  }
108
171
  /**
109
172
  * Gets details about a specific tool available to the agent
@@ -128,6 +191,62 @@ var Agent = class extends BaseResource {
128
191
  return this.request(`/api/agents/${this.agentId}/evals/live`);
129
192
  }
130
193
  };
194
+ var Network = class extends BaseResource {
195
+ constructor(options, networkId) {
196
+ super(options);
197
+ this.networkId = networkId;
198
+ }
199
+ /**
200
+ * Retrieves details about the network
201
+ * @returns Promise containing network details
202
+ */
203
+ details() {
204
+ return this.request(`/api/networks/${this.networkId}`);
205
+ }
206
+ /**
207
+ * Generates a response from the agent
208
+ * @param params - Generation parameters including prompt
209
+ * @returns Promise containing the generated response
210
+ */
211
+ generate(params) {
212
+ const processedParams = {
213
+ ...params,
214
+ output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
215
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
216
+ };
217
+ return this.request(`/api/networks/${this.networkId}/generate`, {
218
+ method: "POST",
219
+ body: processedParams
220
+ });
221
+ }
222
+ /**
223
+ * Streams a response from the agent
224
+ * @param params - Stream parameters including prompt
225
+ * @returns Promise containing the enhanced Response object with processDataStream method
226
+ */
227
+ async stream(params) {
228
+ const processedParams = {
229
+ ...params,
230
+ output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
231
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
232
+ };
233
+ const response = await this.request(`/api/networks/${this.networkId}/stream`, {
234
+ method: "POST",
235
+ body: processedParams,
236
+ stream: true
237
+ });
238
+ if (!response.body) {
239
+ throw new Error("No response body");
240
+ }
241
+ response.processDataStream = async (options = {}) => {
242
+ await processDataStream({
243
+ stream: response.body,
244
+ ...options
245
+ });
246
+ };
247
+ return response;
248
+ }
249
+ };
131
250
 
132
251
  // src/resources/memory-thread.ts
133
252
  var MemoryThread = class extends BaseResource {
@@ -239,6 +358,7 @@ var Vector = class extends BaseResource {
239
358
  };
240
359
 
241
360
  // src/resources/workflow.ts
361
+ var RECORD_SEPARATOR = "";
242
362
  var Workflow = class extends BaseResource {
243
363
  constructor(options, workflowId) {
244
364
  super(options);
@@ -252,6 +372,7 @@ var Workflow = class extends BaseResource {
252
372
  return this.request(`/api/workflows/${this.workflowId}`);
253
373
  }
254
374
  /**
375
+ * @deprecated Use `startAsync` instead
255
376
  * Executes the workflow with the provided parameters
256
377
  * @param params - Parameters required for workflow execution
257
378
  * @returns Promise containing the workflow execution results
@@ -263,7 +384,31 @@ var Workflow = class extends BaseResource {
263
384
  });
264
385
  }
265
386
  /**
266
- * Resumes a suspended workflow step
387
+ * Creates a new workflow run
388
+ * @returns Promise containing the generated run ID
389
+ */
390
+ createRun(params) {
391
+ const searchParams = new URLSearchParams();
392
+ if (!!params?.runId) {
393
+ searchParams.set("runId", params.runId);
394
+ }
395
+ return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
396
+ method: "POST"
397
+ });
398
+ }
399
+ /**
400
+ * Starts a workflow run synchronously without waiting for the workflow to complete
401
+ * @param params - Object containing the runId and triggerData
402
+ * @returns Promise containing success message
403
+ */
404
+ start(params) {
405
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
406
+ method: "POST",
407
+ body: params?.triggerData
408
+ });
409
+ }
410
+ /**
411
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
267
412
  * @param stepId - ID of the step to resume
268
413
  * @param runId - ID of the workflow run
269
414
  * @param context - Context to resume the workflow with
@@ -274,23 +419,106 @@ var Workflow = class extends BaseResource {
274
419
  runId,
275
420
  context
276
421
  }) {
277
- return this.request(`/api/workflows/${this.workflowId}/resume`, {
422
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
278
423
  method: "POST",
279
424
  body: {
280
425
  stepId,
281
- runId,
282
426
  context
283
427
  }
284
428
  });
285
429
  }
430
+ /**
431
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
432
+ * @param params - Object containing the optional runId and triggerData
433
+ * @returns Promise containing the workflow execution results
434
+ */
435
+ startAsync(params) {
436
+ const searchParams = new URLSearchParams();
437
+ if (!!params?.runId) {
438
+ searchParams.set("runId", params.runId);
439
+ }
440
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
441
+ method: "POST",
442
+ body: params?.triggerData
443
+ });
444
+ }
445
+ /**
446
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
447
+ * @param params - Object containing the runId, stepId, and context
448
+ * @returns Promise containing the workflow resume results
449
+ */
450
+ resumeAsync(params) {
451
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
452
+ method: "POST",
453
+ body: {
454
+ stepId: params.stepId,
455
+ context: params.context
456
+ }
457
+ });
458
+ }
459
+ /**
460
+ * Creates an async generator that processes a readable stream and yields records
461
+ * separated by the Record Separator character (\x1E)
462
+ *
463
+ * @param stream - The readable stream to process
464
+ * @returns An async generator that yields parsed records
465
+ */
466
+ async *streamProcessor(stream) {
467
+ const reader = stream.getReader();
468
+ let doneReading = false;
469
+ let buffer = "";
470
+ try {
471
+ while (!doneReading) {
472
+ const { done, value } = await reader.read();
473
+ doneReading = done;
474
+ if (done && !value) continue;
475
+ try {
476
+ const decoded = value ? new TextDecoder().decode(value) : "";
477
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
478
+ buffer = chunks.pop() || "";
479
+ for (const chunk of chunks) {
480
+ if (chunk) {
481
+ if (typeof chunk === "string") {
482
+ try {
483
+ const parsedChunk = JSON.parse(chunk);
484
+ yield parsedChunk;
485
+ } catch {
486
+ }
487
+ }
488
+ }
489
+ }
490
+ } catch (error) {
491
+ }
492
+ }
493
+ if (buffer) {
494
+ try {
495
+ yield JSON.parse(buffer);
496
+ } catch {
497
+ }
498
+ }
499
+ } finally {
500
+ reader.cancel().catch(() => {
501
+ });
502
+ }
503
+ }
286
504
  /**
287
505
  * Watches workflow transitions in real-time
288
- * @returns Promise containing the workflow watch stream
506
+ * @param runId - Optional run ID to filter the watch stream
507
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
289
508
  */
290
- watch() {
291
- return this.request(`/api/workflows/${this.workflowId}/watch`, {
509
+ async watch({ runId }, onRecord) {
510
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
292
511
  stream: true
293
512
  });
513
+ if (!response.ok) {
514
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
515
+ }
516
+ if (!response.body) {
517
+ throw new Error("Response body is null");
518
+ }
519
+ for await (const record of this.streamProcessor(response.body)) {
520
+ onRecord(record);
521
+ }
294
522
  }
295
523
  };
296
524
 
@@ -451,9 +679,6 @@ var MastraClient = class extends BaseResource {
451
679
  getTelemetry(params) {
452
680
  const { name, scope, page, perPage, attribute } = params || {};
453
681
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
454
- ({
455
- ..._attribute?.length ? { attribute: _attribute } : {}
456
- });
457
682
  const searchParams = new URLSearchParams();
458
683
  if (name) {
459
684
  searchParams.set("name", name);
@@ -482,6 +707,21 @@ var MastraClient = class extends BaseResource {
482
707
  return this.request(`/api/telemetry`);
483
708
  }
484
709
  }
710
+ /**
711
+ * Retrieves all available networks
712
+ * @returns Promise containing map of network IDs to network details
713
+ */
714
+ getNetworks() {
715
+ return this.request("/api/networks");
716
+ }
717
+ /**
718
+ * Gets a network instance by ID
719
+ * @param networkId - ID of the network to retrieve
720
+ * @returns Network instance
721
+ */
722
+ getNetwork(networkId) {
723
+ return new Network(this.options, networkId);
724
+ }
485
725
  };
486
726
 
487
727
  export { MastraClient };