@mastra/client-js 0.0.0-fix-message-embedding-20250506021742 → 0.0.0-fix-generate-title-20250616171351

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