@mastra/client-js 0.0.0-separate-trace-data-from-component-20250501141108 → 0.0.0-support-d1-client-20250701191943

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,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
+ }
@@ -1,5 +1,16 @@
1
- import type { GetWorkflowResponse, ClientOptions, WorkflowRunResult, GetWorkflowRunsResponse } from '../types';
1
+ import type { RuntimeContext } from '@mastra/core/runtime-context';
2
+ import type {
3
+ ClientOptions,
4
+ GetWorkflowResponse,
5
+ GetWorkflowRunsResponse,
6
+ GetWorkflowRunsParams,
7
+ WorkflowRunResult,
8
+ WorkflowWatchResult,
9
+ GetWorkflowRunByIdResponse,
10
+ GetWorkflowRunExecutionResultResponse,
11
+ } from '../types';
2
12
 
13
+ import { parseClientRuntimeContext } from '../utils';
3
14
  import { BaseResource } from './base';
4
15
 
5
16
  const RECORD_SEPARATOR = '\x1E';
@@ -12,6 +23,77 @@ export class Workflow extends BaseResource {
12
23
  super(options);
13
24
  }
14
25
 
26
+ /**
27
+ * Creates an async generator that processes a readable stream and yields workflow records
28
+ * separated by the Record Separator character (\x1E)
29
+ *
30
+ * @param stream - The readable stream to process
31
+ * @returns An async generator that yields parsed records
32
+ */
33
+ private async *streamProcessor(stream: ReadableStream): AsyncGenerator<WorkflowWatchResult, void, unknown> {
34
+ const reader = stream.getReader();
35
+
36
+ // Track if we've finished reading from the stream
37
+ let doneReading = false;
38
+ // Buffer to accumulate partial chunks
39
+ let buffer = '';
40
+
41
+ try {
42
+ while (!doneReading) {
43
+ // Read the next chunk from the stream
44
+ const { done, value } = await reader.read();
45
+ doneReading = done;
46
+
47
+ // Skip processing if we're done and there's no value
48
+ if (done && !value) continue;
49
+
50
+ try {
51
+ // Decode binary data to text
52
+ const decoded = value ? new TextDecoder().decode(value) : '';
53
+
54
+ // Split the combined buffer and new data by record separator
55
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
56
+
57
+ // The last chunk might be incomplete, so save it for the next iteration
58
+ buffer = chunks.pop() || '';
59
+
60
+ // Process complete chunks
61
+ for (const chunk of chunks) {
62
+ if (chunk) {
63
+ // Only process non-empty chunks
64
+ if (typeof chunk === 'string') {
65
+ try {
66
+ const parsedChunk = JSON.parse(chunk);
67
+ yield parsedChunk;
68
+ } catch {
69
+ // Silently ignore parsing errors to maintain stream processing
70
+ // This allows the stream to continue even if one record is malformed
71
+ }
72
+ }
73
+ }
74
+ }
75
+ } catch {
76
+ // Silently ignore parsing errors to maintain stream processing
77
+ // This allows the stream to continue even if one record is malformed
78
+ }
79
+ }
80
+
81
+ // Process any remaining data in the buffer after stream is done
82
+ if (buffer) {
83
+ try {
84
+ yield JSON.parse(buffer);
85
+ } catch {
86
+ // Ignore parsing error for final chunk
87
+ }
88
+ }
89
+ } finally {
90
+ // Always ensure we clean up the reader
91
+ reader.cancel().catch(() => {
92
+ // Ignore cancel errors
93
+ });
94
+ }
95
+ }
96
+
15
97
  /**
16
98
  * Retrieves details about the workflow
17
99
  * @returns Promise containing workflow details including steps and graphs
@@ -22,28 +104,67 @@ export class Workflow extends BaseResource {
22
104
 
23
105
  /**
24
106
  * Retrieves all runs for a workflow
107
+ * @param params - Parameters for filtering runs
25
108
  * @returns Promise containing workflow runs array
26
109
  */
27
- runs(): Promise<GetWorkflowRunsResponse> {
28
- return this.request(`/api/workflows/${this.workflowId}/runs`);
110
+ runs(params?: GetWorkflowRunsParams): Promise<GetWorkflowRunsResponse> {
111
+ const searchParams = new URLSearchParams();
112
+ if (params?.fromDate) {
113
+ searchParams.set('fromDate', params.fromDate.toISOString());
114
+ }
115
+ if (params?.toDate) {
116
+ searchParams.set('toDate', params.toDate.toISOString());
117
+ }
118
+ if (params?.limit) {
119
+ searchParams.set('limit', String(params.limit));
120
+ }
121
+ if (params?.offset) {
122
+ searchParams.set('offset', String(params.offset));
123
+ }
124
+ if (params?.resourceId) {
125
+ searchParams.set('resourceId', params.resourceId);
126
+ }
127
+
128
+ if (searchParams.size) {
129
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
130
+ } else {
131
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
132
+ }
29
133
  }
30
134
 
31
135
  /**
32
- * @deprecated Use `startAsync` instead
33
- * Executes the workflow with the provided parameters
34
- * @param params - Parameters required for workflow execution
35
- * @returns Promise containing the workflow execution results
136
+ * Retrieves a specific workflow run by its ID
137
+ * @param runId - The ID of the workflow run to retrieve
138
+ * @returns Promise containing the workflow run details
139
+ */
140
+ runById(runId: string): Promise<GetWorkflowRunByIdResponse> {
141
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
142
+ }
143
+
144
+ /**
145
+ * Retrieves the execution result for a specific workflow run by its ID
146
+ * @param runId - The ID of the workflow run to retrieve the execution result for
147
+ * @returns Promise containing the workflow run execution result
36
148
  */
37
- execute(params: Record<string, any>): Promise<WorkflowRunResult> {
38
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
149
+ runExecutionResult(runId: string): Promise<GetWorkflowRunExecutionResultResponse> {
150
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
151
+ }
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`, {
39
160
  method: 'POST',
40
- body: params,
41
161
  });
42
162
  }
43
163
 
44
164
  /**
45
165
  * Creates a new workflow run
46
- * @returns Promise containing the generated run ID
166
+ * @param params - Optional object containing the optional runId
167
+ * @returns Promise containing the runId of the created run
47
168
  */
48
169
  createRun(params?: { runId?: string }): Promise<{ runId: string }> {
49
170
  const searchParams = new URLSearchParams();
@@ -52,150 +173,162 @@ export class Workflow extends BaseResource {
52
173
  searchParams.set('runId', params.runId);
53
174
  }
54
175
 
55
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
176
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
56
177
  method: 'POST',
57
178
  });
58
179
  }
59
180
 
60
181
  /**
61
182
  * Starts a workflow run synchronously without waiting for the workflow to complete
62
- * @param params - Object containing the runId and triggerData
183
+ * @param params - Object containing the runId, inputData and runtimeContext
63
184
  * @returns Promise containing success message
64
185
  */
65
- start(params: { runId: string; triggerData: Record<string, any> }): Promise<{ message: string }> {
186
+ start(params: {
187
+ runId: string;
188
+ inputData: Record<string, any>;
189
+ runtimeContext?: RuntimeContext | Record<string, any>;
190
+ }): Promise<{ message: string }> {
191
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
66
192
  return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
67
193
  method: 'POST',
68
- body: params?.triggerData,
194
+ body: { inputData: params?.inputData, runtimeContext },
69
195
  });
70
196
  }
71
197
 
72
198
  /**
73
199
  * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
74
- * @param stepId - ID of the step to resume
75
- * @param runId - ID of the workflow run
76
- * @param context - Context to resume the workflow with
77
- * @returns Promise containing the workflow resume results
200
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
201
+ * @returns Promise containing success message
78
202
  */
79
203
  resume({
80
- stepId,
204
+ step,
81
205
  runId,
82
- context,
206
+ resumeData,
207
+ ...rest
83
208
  }: {
84
- stepId: string;
209
+ step: string | string[];
85
210
  runId: string;
86
- context: Record<string, any>;
211
+ resumeData?: Record<string, any>;
212
+ runtimeContext?: RuntimeContext | Record<string, any>;
87
213
  }): Promise<{ message: string }> {
214
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
88
215
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
89
216
  method: 'POST',
217
+ stream: true,
90
218
  body: {
91
- stepId,
92
- context,
219
+ step,
220
+ resumeData,
221
+ runtimeContext,
93
222
  },
94
223
  });
95
224
  }
96
225
 
97
226
  /**
98
227
  * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
99
- * @param params - Object containing the optional runId and triggerData
228
+ * @param params - Object containing the optional runId, inputData and runtimeContext
100
229
  * @returns Promise containing the workflow execution results
101
230
  */
102
- startAsync(params: { runId?: string; triggerData: Record<string, any> }): Promise<WorkflowRunResult> {
231
+ startAsync(params: {
232
+ runId?: string;
233
+ inputData: Record<string, any>;
234
+ runtimeContext?: RuntimeContext | Record<string, any>;
235
+ }): Promise<WorkflowRunResult> {
103
236
  const searchParams = new URLSearchParams();
104
237
 
105
238
  if (!!params?.runId) {
106
239
  searchParams.set('runId', params.runId);
107
240
  }
108
241
 
242
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
243
+
109
244
  return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
110
245
  method: 'POST',
111
- body: params?.triggerData,
246
+ body: { inputData: params.inputData, runtimeContext },
112
247
  });
113
248
  }
114
249
 
115
250
  /**
116
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
117
- * @param params - Object containing the runId, stepId, and context
118
- * @returns Promise containing the workflow resume results
251
+ * Starts a workflow run and returns a stream
252
+ * @param params - Object containing the optional runId, inputData and runtimeContext
253
+ * @returns Promise containing the workflow execution results
119
254
  */
120
- resumeAsync(params: { runId: string; stepId: string; context: Record<string, any> }): Promise<WorkflowRunResult> {
121
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
122
- method: 'POST',
123
- body: {
124
- stepId: params.stepId,
125
- context: params.context,
126
- },
127
- });
128
- }
255
+ async stream(params: { runId?: string; inputData: Record<string, any>; runtimeContext?: RuntimeContext }) {
256
+ const searchParams = new URLSearchParams();
129
257
 
130
- /**
131
- * Creates an async generator that processes a readable stream and yields records
132
- * separated by the Record Separator character (\x1E)
133
- *
134
- * @param stream - The readable stream to process
135
- * @returns An async generator that yields parsed records
136
- */
137
- private async *streamProcessor(stream: ReadableStream): AsyncGenerator<WorkflowRunResult, void, unknown> {
138
- const reader = stream.getReader();
258
+ if (!!params?.runId) {
259
+ searchParams.set('runId', params.runId);
260
+ }
139
261
 
140
- // Track if we've finished reading from the stream
141
- let doneReading = false;
142
- // Buffer to accumulate partial chunks
143
- let buffer = '';
262
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
263
+ const response: Response = await this.request(
264
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
265
+ {
266
+ method: 'POST',
267
+ body: { inputData: params.inputData, runtimeContext },
268
+ stream: true,
269
+ },
270
+ );
144
271
 
145
- try {
146
- while (!doneReading) {
147
- // Read the next chunk from the stream
148
- const { done, value } = await reader.read();
149
- doneReading = done;
272
+ if (!response.ok) {
273
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
274
+ }
150
275
 
151
- // Skip processing if we're done and there's no value
152
- if (done && !value) continue;
276
+ if (!response.body) {
277
+ throw new Error('Response body is null');
278
+ }
153
279
 
280
+ // Create a transform stream that processes the response body
281
+ const transformStream = new TransformStream<ArrayBuffer, { type: string; payload: any }>({
282
+ start() {},
283
+ async transform(chunk, controller) {
154
284
  try {
155
285
  // Decode binary data to text
156
- const decoded = value ? new TextDecoder().decode(value) : '';
286
+ const decoded = new TextDecoder().decode(chunk);
157
287
 
158
- // Split the combined buffer and new data by record separator
159
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
160
-
161
- // The last chunk might be incomplete, so save it for the next iteration
162
- buffer = chunks.pop() || '';
288
+ // Split by record separator
289
+ const chunks = decoded.split(RECORD_SEPARATOR);
163
290
 
164
- // Process complete chunks
291
+ // Process each chunk
165
292
  for (const chunk of chunks) {
166
293
  if (chunk) {
167
- // Only process non-empty chunks
168
- if (typeof chunk === 'string') {
169
- try {
170
- const parsedChunk = JSON.parse(chunk);
171
- yield parsedChunk;
172
- } catch {
173
- // Silently ignore parsing errors to maintain stream processing
174
- // This allows the stream to continue even if one record is malformed
175
- }
294
+ try {
295
+ const parsedChunk = JSON.parse(chunk);
296
+ controller.enqueue(parsedChunk);
297
+ } catch {
298
+ // Silently ignore parsing errors
176
299
  }
177
300
  }
178
301
  }
179
302
  } catch {
180
- // Silently ignore parsing errors to maintain stream processing
181
- // This allows the stream to continue even if one record is malformed
303
+ // Silently ignore processing errors
182
304
  }
183
- }
305
+ },
306
+ });
184
307
 
185
- // Process any remaining data in the buffer after stream is done
186
- if (buffer) {
187
- try {
188
- yield JSON.parse(buffer);
189
- } catch {
190
- // Ignore parsing error for final chunk
191
- }
192
- }
193
- } finally {
194
- // Always ensure we clean up the reader
195
- reader.cancel().catch(() => {
196
- // Ignore cancel errors
197
- });
198
- }
308
+ // Pipe the response body through the transform stream
309
+ return response.body.pipeThrough(transformStream);
310
+ }
311
+
312
+ /**
313
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
314
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
315
+ * @returns Promise containing the workflow resume results
316
+ */
317
+ resumeAsync(params: {
318
+ runId: string;
319
+ step: string | string[];
320
+ resumeData?: Record<string, any>;
321
+ runtimeContext?: RuntimeContext | Record<string, any>;
322
+ }): Promise<WorkflowRunResult> {
323
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
324
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
325
+ method: 'POST',
326
+ body: {
327
+ step: params.step,
328
+ resumeData: params.resumeData,
329
+ runtimeContext,
330
+ },
331
+ });
199
332
  }
200
333
 
201
334
  /**
@@ -203,7 +336,7 @@ export class Workflow extends BaseResource {
203
336
  * @param runId - Optional run ID to filter the watch stream
204
337
  * @returns AsyncGenerator that yields parsed records from the workflow watch stream
205
338
  */
206
- async watch({ runId }: { runId?: string }, onRecord: (record: WorkflowRunResult) => void) {
339
+ async watch({ runId }: { runId?: string }, onRecord: (record: WorkflowWatchResult) => void) {
207
340
  const response: Response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
208
341
  stream: true,
209
342
  });
@@ -217,7 +350,35 @@ export class Workflow extends BaseResource {
217
350
  }
218
351
 
219
352
  for await (const record of this.streamProcessor(response.body)) {
220
- onRecord(record);
353
+ if (typeof record === 'string') {
354
+ onRecord(JSON.parse(record));
355
+ } else {
356
+ onRecord(record);
357
+ }
221
358
  }
222
359
  }
360
+
361
+ /**
362
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
363
+ * serializing each as JSON and separating them with the record separator (\x1E).
364
+ *
365
+ * @param records - An iterable or async iterable of objects to stream
366
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
367
+ */
368
+ static createRecordStream(records: Iterable<any> | AsyncIterable<any>): ReadableStream {
369
+ const encoder = new TextEncoder();
370
+ return new ReadableStream({
371
+ async start(controller) {
372
+ try {
373
+ for await (const record of records as AsyncIterable<any>) {
374
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
375
+ controller.enqueue(encoder.encode(json));
376
+ }
377
+ controller.close();
378
+ } catch (err) {
379
+ controller.error(err);
380
+ }
381
+ },
382
+ });
383
+ }
223
384
  }