@mastra/client-js 0.0.0-storage-20250225005900 → 0.0.0-vnextWorkflows-20250417075051

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,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 };
package/package.json CHANGED
@@ -1,41 +1,47 @@
1
1
  {
2
2
  "name": "@mastra/client-js",
3
- "version": "0.0.0-storage-20250225005900",
3
+ "version": "0.0.0-vnextWorkflows-20250417075051",
4
4
  "description": "The official TypeScript library for the Mastra Client API",
5
5
  "author": "",
6
- "types": "dist/index.d.mts",
7
- "main": "dist/index.mjs",
6
+ "type": "module",
7
+ "types": "dist/index.d.ts",
8
+ "main": "dist/index.js",
8
9
  "exports": {
9
10
  ".": {
10
11
  "import": {
11
- "types": "./dist/index.d.mts",
12
- "default": "./dist/index.mjs"
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
13
18
  }
14
19
  },
15
20
  "./package.json": "./package.json"
16
21
  },
17
22
  "repository": "github:mastra-ai/client-js",
18
- "license": "ISC",
23
+ "license": "Elastic-2.0",
19
24
  "dependencies": {
25
+ "@ai-sdk/ui-utils": "^1.1.19",
20
26
  "json-schema": "^0.4.0",
21
- "zod": "^3.24.1",
22
- "zod-to-json-schema": "^3.24.1",
23
- "@mastra/core": "^0.0.0-storage-20250225005900"
27
+ "zod": "^3.24.2",
28
+ "zod-to-json-schema": "^3.24.3",
29
+ "@mastra/core": "0.0.0-vnextWorkflows-20250417075051"
24
30
  },
25
31
  "devDependencies": {
26
- "@babel/preset-env": "^7.26.0",
27
- "@babel/preset-typescript": "^7.26.0",
28
- "@tsconfig/recommended": "^1.0.7",
32
+ "@babel/preset-env": "^7.26.9",
33
+ "@babel/preset-typescript": "^7.27.0",
34
+ "@tsconfig/recommended": "^1.0.8",
29
35
  "@types/json-schema": "^7.0.15",
30
- "@types/node": "^22.9.0",
31
- "tsup": "^8.0.1",
32
- "typescript": "^5.7.3",
33
- "vitest": "^3.0.4",
34
- "@internal/lint": "0.0.0"
36
+ "@types/node": "^20.17.27",
37
+ "tsup": "^8.4.0",
38
+ "typescript": "^5.8.2",
39
+ "vitest": "^3.0.9",
40
+ "@internal/lint": "0.0.2"
35
41
  },
36
42
  "scripts": {
37
- "build": "tsup-node src/index.ts --format esm --dts --clean --treeshake",
38
- "dev": "tsup-node src/index.ts --format esm --dts --clean --treeshake --watch",
43
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean --treeshake=smallest --splitting",
44
+ "dev": "pnpm build --watch",
39
45
  "test": "vitest run"
40
46
  }
41
47
  }
package/src/client.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Agent, MemoryThread, Tool, Workflow, Vector, BaseResource } from './resources';
1
+ import { Agent, MemoryThread, Tool, Workflow, Vector, BaseResource, Network } from './resources';
2
2
  import type {
3
3
  ClientOptions,
4
4
  CreateMemoryThreadParams,
@@ -9,6 +9,7 @@ import type {
9
9
  GetLogsResponse,
10
10
  GetMemoryThreadParams,
11
11
  GetMemoryThreadResponse,
12
+ GetNetworkResponse,
12
13
  GetTelemetryParams,
13
14
  GetTelemetryResponse,
14
15
  GetToolResponse,
@@ -202,4 +203,21 @@ export class MastraClient extends BaseResource {
202
203
  return this.request(`/api/telemetry`);
203
204
  }
204
205
  }
206
+
207
+ /**
208
+ * Retrieves all available networks
209
+ * @returns Promise containing map of network IDs to network details
210
+ */
211
+ public getNetworks(): Promise<Record<string, GetNetworkResponse>> {
212
+ return this.request('/api/networks');
213
+ }
214
+
215
+ /**
216
+ * Gets a network instance by ID
217
+ * @param networkId - ID of the network to retrieve
218
+ * @returns Network instance
219
+ */
220
+ public getNetwork(networkId: string) {
221
+ return new Network(this.options, networkId);
222
+ }
205
223
  }
package/src/example.ts CHANGED
@@ -1,43 +1,65 @@
1
- import { MastraClient } from './client';
2
-
3
- (async () => {
4
- const client = new MastraClient({
5
- baseUrl: 'http://localhost:4111',
6
- });
7
-
8
- try {
9
- const agent = client.getAgent('weatherAgent');
10
- const response = await agent.stream({
11
- messages: [
12
- {
13
- role: 'user',
14
- content: 'Hello, world!',
15
- },
16
- ],
17
- });
18
-
19
- const reader = response?.body?.getReader();
20
- const decoder = new TextDecoder();
21
- let buffer = '';
22
-
23
- while (true) {
24
- if (!reader) break;
25
- const { value, done } = await reader.read();
26
- if (done) break;
27
-
28
- const chunk = decoder.decode(value);
29
- buffer += chunk;
30
-
31
- console.log(buffer);
32
-
33
- const matches = buffer.matchAll(/0:"([^"]*)"/g);
34
-
35
- for (const match of matches) {
36
- const content = match[1];
37
- process.stdout.write(`${content}\n`);
38
- }
39
- }
40
- } catch (error) {
41
- console.error(error);
42
- }
43
- })();
1
+ // import { MastraClient } from './client';
2
+ // import type { WorkflowRunResult } from './types';
3
+
4
+ // Agent
5
+
6
+ // (async () => {
7
+ // const client = new MastraClient({
8
+ // baseUrl: 'http://localhost:4111',
9
+ // });
10
+
11
+ // console.log('Starting agent...');
12
+
13
+ // try {
14
+ // const agent = client.getAgent('weatherAgent');
15
+ // const response = await agent.stream({
16
+ // messages: 'what is the weather in new york?',
17
+ // })
18
+
19
+ // response.processDataStream({
20
+ // onTextPart: (text) => {
21
+ // process.stdout.write(text);
22
+ // },
23
+ // onFilePart: (file) => {
24
+ // console.log(file);
25
+ // },
26
+ // onDataPart: (data) => {
27
+ // console.log(data);
28
+ // },
29
+ // onErrorPart: (error) => {
30
+ // console.error(error);
31
+ // },
32
+ // });
33
+
34
+ // } catch (error) {
35
+ // console.error(error);
36
+ // }
37
+ // })();
38
+
39
+ // Workflow
40
+ // (async () => {
41
+ // const client = new MastraClient({
42
+ // baseUrl: 'http://localhost:4111',
43
+ // });
44
+
45
+ // try {
46
+ // const workflowId = 'myWorkflow';
47
+ // const workflow = client.getWorkflow(workflowId);
48
+
49
+ // const { runId } = await workflow.createRun();
50
+
51
+ // workflow.watch({ runId }, record => {
52
+ // console.log(new Date().toTimeString(), record);
53
+ // });
54
+
55
+ // await workflow.start({
56
+ // runId,
57
+ // triggerData: {
58
+ // city: 'New York',
59
+ // },
60
+ // });
61
+
62
+ // } catch (e) {
63
+ // console.error('Workflow error:', e);
64
+ // }
65
+ // })();