@mastra/client-js 0.0.0-bundle-dynamic-imports-20250424001248 → 0.0.0-bundle-recursion-20251030002519

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.
Files changed (67) hide show
  1. package/CHANGELOG.md +2417 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +7 -8
  4. package/dist/client.d.ts +287 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/example.d.ts +2 -0
  7. package/dist/example.d.ts.map +1 -0
  8. package/dist/index.cjs +3005 -295
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +5 -585
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +3004 -300
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources/a2a.d.ts +41 -0
  15. package/dist/resources/a2a.d.ts.map +1 -0
  16. package/dist/resources/agent-builder.d.ts +208 -0
  17. package/dist/resources/agent-builder.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +204 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +11 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/mcp-tool.d.ts +28 -0
  25. package/dist/resources/mcp-tool.d.ts.map +1 -0
  26. package/dist/resources/memory-thread.d.ts +61 -0
  27. package/dist/resources/memory-thread.d.ts.map +1 -0
  28. package/dist/resources/network-memory-thread.d.ts +47 -0
  29. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  30. package/dist/resources/observability.d.ts +35 -0
  31. package/dist/resources/observability.d.ts.map +1 -0
  32. package/dist/resources/tool.d.ts +24 -0
  33. package/dist/resources/tool.d.ts.map +1 -0
  34. package/dist/resources/vector.d.ts +51 -0
  35. package/dist/resources/vector.d.ts.map +1 -0
  36. package/dist/resources/workflow.d.ts +269 -0
  37. package/dist/resources/workflow.d.ts.map +1 -0
  38. package/dist/tools.d.ts +22 -0
  39. package/dist/tools.d.ts.map +1 -0
  40. package/dist/types.d.ts +475 -0
  41. package/dist/types.d.ts.map +1 -0
  42. package/dist/utils/index.d.ts +11 -0
  43. package/dist/utils/index.d.ts.map +1 -0
  44. package/dist/utils/process-client-tools.d.ts +3 -0
  45. package/dist/utils/process-client-tools.d.ts.map +1 -0
  46. package/dist/utils/process-mastra-stream.d.ts +11 -0
  47. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  48. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  49. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  50. package/package.json +39 -19
  51. package/dist/index.d.cts +0 -585
  52. package/eslint.config.js +0 -6
  53. package/src/client.ts +0 -214
  54. package/src/example.ts +0 -65
  55. package/src/index.test.ts +0 -710
  56. package/src/index.ts +0 -2
  57. package/src/resources/agent.ts +0 -205
  58. package/src/resources/base.ts +0 -70
  59. package/src/resources/index.ts +0 -7
  60. package/src/resources/memory-thread.ts +0 -53
  61. package/src/resources/network.ts +0 -92
  62. package/src/resources/tool.ts +0 -32
  63. package/src/resources/vector.ts +0 -83
  64. package/src/resources/workflow.ts +0 -215
  65. package/src/types.ts +0 -224
  66. package/tsconfig.json +0 -5
  67. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,10 +1,141 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
- var zodToJsonSchema = require('zod-to-json-schema');
5
3
  var uiUtils = require('@ai-sdk/ui-utils');
4
+ var uuid = require('@lukeed/uuid');
5
+ var error = require('@mastra/core/error');
6
+ var runtimeContext = require('@mastra/core/runtime-context');
7
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
8
+ var zod = require('zod');
9
+ var originalZodToJsonSchema = require('zod-to-json-schema');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
6
14
 
7
15
  // src/resources/agent.ts
16
+ function parseClientRuntimeContext(runtimeContext$1) {
17
+ if (runtimeContext$1) {
18
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
19
+ return Object.fromEntries(runtimeContext$1.entries());
20
+ }
21
+ return runtimeContext$1;
22
+ }
23
+ return void 0;
24
+ }
25
+ function base64RuntimeContext(runtimeContext) {
26
+ if (runtimeContext) {
27
+ return btoa(JSON.stringify(runtimeContext));
28
+ }
29
+ return void 0;
30
+ }
31
+ function runtimeContextQueryString(runtimeContext, delimiter = "?") {
32
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
33
+ if (!runtimeContextParam) return "";
34
+ const searchParams = new URLSearchParams();
35
+ searchParams.set("runtimeContext", runtimeContextParam);
36
+ const queryString = searchParams.toString();
37
+ return queryString ? `${delimiter}${queryString}` : "";
38
+ }
39
+ function isZodType(value) {
40
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
41
+ }
42
+ function zodToJsonSchema(zodSchema) {
43
+ if (!isZodType(zodSchema)) {
44
+ return zodSchema;
45
+ }
46
+ if ("toJSONSchema" in zod.z) {
47
+ const fn = "toJSONSchema";
48
+ return zod.z[fn].call(zod.z, zodSchema);
49
+ }
50
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "relative" });
51
+ }
52
+
53
+ // src/utils/process-client-tools.ts
54
+ function processClientTools(clientTools) {
55
+ if (!clientTools) {
56
+ return void 0;
57
+ }
58
+ return Object.fromEntries(
59
+ Object.entries(clientTools).map(([key, value]) => {
60
+ if (isVercelTool.isVercelTool(value)) {
61
+ return [
62
+ key,
63
+ {
64
+ ...value,
65
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
66
+ }
67
+ ];
68
+ } else {
69
+ return [
70
+ key,
71
+ {
72
+ ...value,
73
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
74
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
75
+ }
76
+ ];
77
+ }
78
+ })
79
+ );
80
+ }
81
+
82
+ // src/utils/process-mastra-stream.ts
83
+ async function sharedProcessMastraStream({
84
+ stream,
85
+ onChunk
86
+ }) {
87
+ const reader = stream.getReader();
88
+ const decoder = new TextDecoder();
89
+ let buffer = "";
90
+ try {
91
+ while (true) {
92
+ const { done, value } = await reader.read();
93
+ if (done) break;
94
+ buffer += decoder.decode(value, { stream: true });
95
+ const lines = buffer.split("\n\n");
96
+ buffer = lines.pop() || "";
97
+ for (const line of lines) {
98
+ if (line.startsWith("data: ")) {
99
+ const data = line.slice(6);
100
+ if (data === "[DONE]") {
101
+ console.info("\u{1F3C1} Stream finished");
102
+ return;
103
+ }
104
+ let json;
105
+ try {
106
+ json = JSON.parse(data);
107
+ } catch (error) {
108
+ console.error("\u274C JSON parse error:", error, "Data:", data);
109
+ continue;
110
+ }
111
+ if (json) {
112
+ await onChunk(json);
113
+ }
114
+ }
115
+ }
116
+ }
117
+ } finally {
118
+ reader.releaseLock();
119
+ }
120
+ }
121
+ async function processMastraNetworkStream({
122
+ stream,
123
+ onChunk
124
+ }) {
125
+ return sharedProcessMastraStream({
126
+ stream,
127
+ onChunk
128
+ });
129
+ }
130
+ async function processMastraStream({
131
+ stream,
132
+ onChunk
133
+ }) {
134
+ return sharedProcessMastraStream({
135
+ stream,
136
+ onChunk
137
+ });
138
+ }
8
139
 
9
140
  // src/resources/base.ts
10
141
  var BaseResource = class {
@@ -20,18 +151,21 @@ var BaseResource = class {
20
151
  */
21
152
  async request(path, options = {}) {
22
153
  let lastError = null;
23
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
154
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
24
155
  let delay = backoffMs;
25
156
  for (let attempt = 0; attempt <= retries; attempt++) {
26
157
  try {
27
- const response = await fetch(`${baseUrl}${path}`, {
158
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
28
159
  ...options,
29
160
  headers: {
161
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
30
162
  ...headers,
31
163
  ...options.headers
32
164
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
33
165
  // 'x-mastra-client-type': 'js',
34
166
  },
167
+ signal: this.options.abortSignal,
168
+ credentials: options.credentials ?? credentials,
35
169
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
36
170
  });
37
171
  if (!response.ok) {
@@ -66,6 +200,61 @@ var BaseResource = class {
66
200
  };
67
201
 
68
202
  // src/resources/agent.ts
203
+ async function executeToolCallAndRespond({
204
+ response,
205
+ params,
206
+ runId,
207
+ resourceId,
208
+ threadId,
209
+ runtimeContext,
210
+ respondFn
211
+ }) {
212
+ if (response.finishReason === "tool-calls") {
213
+ const toolCalls = response.toolCalls;
214
+ if (!toolCalls || !Array.isArray(toolCalls)) {
215
+ return response;
216
+ }
217
+ for (const toolCall of toolCalls) {
218
+ const clientTool = params.clientTools?.[toolCall.toolName];
219
+ if (clientTool && clientTool.execute) {
220
+ const result = await clientTool.execute(
221
+ {
222
+ context: toolCall?.args,
223
+ runId,
224
+ resourceId,
225
+ threadId,
226
+ runtimeContext,
227
+ tracingContext: { currentSpan: void 0 },
228
+ suspend: async () => {
229
+ }
230
+ },
231
+ {
232
+ messages: response.messages,
233
+ toolCallId: toolCall?.toolCallId
234
+ }
235
+ );
236
+ const updatedMessages = [
237
+ ...response.response.messages || [],
238
+ {
239
+ role: "tool",
240
+ content: [
241
+ {
242
+ type: "tool-result",
243
+ toolCallId: toolCall.toolCallId,
244
+ toolName: toolCall.toolName,
245
+ result
246
+ }
247
+ ]
248
+ }
249
+ ];
250
+ return respondFn({
251
+ ...params,
252
+ messages: updatedMessages
253
+ });
254
+ }
255
+ }
256
+ }
257
+ }
69
258
  var AgentVoice = class extends BaseResource {
70
259
  constructor(options, agentId) {
71
260
  super(options);
@@ -107,10 +296,21 @@ var AgentVoice = class extends BaseResource {
107
296
  }
108
297
  /**
109
298
  * Get available speakers for the agent's voice provider
299
+ * @param runtimeContext - Optional runtime context to pass as query parameter
300
+ * @param runtimeContext - Optional runtime context to pass as query parameter
110
301
  * @returns Promise containing list of available speakers
111
302
  */
112
- getSpeakers() {
113
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
303
+ getSpeakers(runtimeContext) {
304
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
305
+ }
306
+ /**
307
+ * Get the listener configuration for the agent's voice provider
308
+ * @param runtimeContext - Optional runtime context to pass as query parameter
309
+ * @param runtimeContext - Optional runtime context to pass as query parameter
310
+ * @returns Promise containing a check if the agent has listening capabilities
311
+ */
312
+ getListener(runtimeContext) {
313
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
114
314
  }
115
315
  };
116
316
  var Agent = class extends BaseResource {
@@ -122,39 +322,677 @@ var Agent = class extends BaseResource {
122
322
  voice;
123
323
  /**
124
324
  * Retrieves details about the agent
325
+ * @param runtimeContext - Optional runtime context to pass as query parameter
125
326
  * @returns Promise containing agent details including model and instructions
126
327
  */
127
- details() {
128
- return this.request(`/api/agents/${this.agentId}`);
328
+ details(runtimeContext) {
329
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
129
330
  }
130
- /**
131
- * Generates a response from the agent
132
- * @param params - Generation parameters including prompt
133
- * @returns Promise containing the generated response
134
- */
135
- generate(params) {
331
+ enhanceInstructions(instructions, comment) {
332
+ return this.request(`/api/agents/${this.agentId}/instructions/enhance`, {
333
+ method: "POST",
334
+ body: { instructions, comment }
335
+ });
336
+ }
337
+ async generateLegacy(params) {
136
338
  const processedParams = {
137
339
  ...params,
138
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
139
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
340
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
341
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
342
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
343
+ clientTools: processClientTools(params.clientTools)
140
344
  };
141
- return this.request(`/api/agents/${this.agentId}/generate`, {
142
- method: "POST",
143
- body: processedParams
345
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
346
+ const response = await this.request(
347
+ `/api/agents/${this.agentId}/generate-legacy`,
348
+ {
349
+ method: "POST",
350
+ body: processedParams
351
+ }
352
+ );
353
+ if (response.finishReason === "tool-calls") {
354
+ const toolCalls = response.toolCalls;
355
+ if (!toolCalls || !Array.isArray(toolCalls)) {
356
+ return response;
357
+ }
358
+ for (const toolCall of toolCalls) {
359
+ const clientTool = params.clientTools?.[toolCall.toolName];
360
+ if (clientTool && clientTool.execute) {
361
+ const result = await clientTool.execute(
362
+ {
363
+ context: toolCall?.args,
364
+ runId,
365
+ resourceId,
366
+ threadId,
367
+ runtimeContext,
368
+ tracingContext: { currentSpan: void 0 },
369
+ suspend: async () => {
370
+ }
371
+ },
372
+ {
373
+ messages: response.messages,
374
+ toolCallId: toolCall?.toolCallId
375
+ }
376
+ );
377
+ const updatedMessages = [
378
+ ...response.response.messages,
379
+ {
380
+ role: "tool",
381
+ content: [
382
+ {
383
+ type: "tool-result",
384
+ toolCallId: toolCall.toolCallId,
385
+ toolName: toolCall.toolName,
386
+ result
387
+ }
388
+ ]
389
+ }
390
+ ];
391
+ return this.generate({
392
+ ...params,
393
+ messages: updatedMessages
394
+ });
395
+ }
396
+ }
397
+ }
398
+ return response;
399
+ }
400
+ async generate(messagesOrParams, options) {
401
+ let params;
402
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
403
+ params = messagesOrParams;
404
+ } else {
405
+ params = {
406
+ messages: messagesOrParams,
407
+ ...options
408
+ };
409
+ }
410
+ const processedParams = {
411
+ ...params,
412
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
413
+ clientTools: processClientTools(params.clientTools),
414
+ structuredOutput: params.structuredOutput ? {
415
+ ...params.structuredOutput,
416
+ schema: zodToJsonSchema(params.structuredOutput.schema)
417
+ } : void 0
418
+ };
419
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
420
+ const response = await this.request(
421
+ `/api/agents/${this.agentId}/generate`,
422
+ {
423
+ method: "POST",
424
+ body: processedParams
425
+ }
426
+ );
427
+ if (response.finishReason === "tool-calls") {
428
+ return executeToolCallAndRespond({
429
+ response,
430
+ params,
431
+ runId,
432
+ resourceId,
433
+ threadId,
434
+ runtimeContext,
435
+ respondFn: this.generate.bind(this)
436
+ });
437
+ }
438
+ return response;
439
+ }
440
+ async processChatResponse({
441
+ stream,
442
+ update,
443
+ onToolCall,
444
+ onFinish,
445
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
446
+ lastMessage
447
+ }) {
448
+ const replaceLastMessage = lastMessage?.role === "assistant";
449
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
450
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
451
+ return Math.max(max, toolInvocation.step ?? 0);
452
+ }, 0) ?? 0) : 0;
453
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
454
+ id: uuid.v4(),
455
+ createdAt: getCurrentDate(),
456
+ role: "assistant",
457
+ content: "",
458
+ parts: []
459
+ };
460
+ let currentTextPart = void 0;
461
+ let currentReasoningPart = void 0;
462
+ let currentReasoningTextDetail = void 0;
463
+ function updateToolInvocationPart(toolCallId, invocation) {
464
+ const part = message.parts.find(
465
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
466
+ );
467
+ if (part != null) {
468
+ part.toolInvocation = invocation;
469
+ } else {
470
+ message.parts.push({
471
+ type: "tool-invocation",
472
+ toolInvocation: invocation
473
+ });
474
+ }
475
+ }
476
+ const data = [];
477
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
478
+ const partialToolCalls = {};
479
+ let usage = {
480
+ completionTokens: NaN,
481
+ promptTokens: NaN,
482
+ totalTokens: NaN
483
+ };
484
+ let finishReason = "unknown";
485
+ function execUpdate() {
486
+ const copiedData = [...data];
487
+ if (messageAnnotations?.length) {
488
+ message.annotations = messageAnnotations;
489
+ }
490
+ const copiedMessage = {
491
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
492
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
493
+ ...structuredClone(message),
494
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
495
+ // hashing approach by default to detect changes, but it only works for shallow
496
+ // changes. This is why we need to add a revision id to ensure that the message
497
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
498
+ // forwarded to rendering):
499
+ revisionId: uuid.v4()
500
+ };
501
+ update({
502
+ message: copiedMessage,
503
+ data: copiedData,
504
+ replaceLastMessage
505
+ });
506
+ }
507
+ await uiUtils.processDataStream({
508
+ stream,
509
+ onTextPart(value) {
510
+ if (currentTextPart == null) {
511
+ currentTextPart = {
512
+ type: "text",
513
+ text: value
514
+ };
515
+ message.parts.push(currentTextPart);
516
+ } else {
517
+ currentTextPart.text += value;
518
+ }
519
+ message.content += value;
520
+ execUpdate();
521
+ },
522
+ onReasoningPart(value) {
523
+ if (currentReasoningTextDetail == null) {
524
+ currentReasoningTextDetail = { type: "text", text: value };
525
+ if (currentReasoningPart != null) {
526
+ currentReasoningPart.details.push(currentReasoningTextDetail);
527
+ }
528
+ } else {
529
+ currentReasoningTextDetail.text += value;
530
+ }
531
+ if (currentReasoningPart == null) {
532
+ currentReasoningPart = {
533
+ type: "reasoning",
534
+ reasoning: value,
535
+ details: [currentReasoningTextDetail]
536
+ };
537
+ message.parts.push(currentReasoningPart);
538
+ } else {
539
+ currentReasoningPart.reasoning += value;
540
+ }
541
+ message.reasoning = (message.reasoning ?? "") + value;
542
+ execUpdate();
543
+ },
544
+ onReasoningSignaturePart(value) {
545
+ if (currentReasoningTextDetail != null) {
546
+ currentReasoningTextDetail.signature = value.signature;
547
+ }
548
+ },
549
+ onRedactedReasoningPart(value) {
550
+ if (currentReasoningPart == null) {
551
+ currentReasoningPart = {
552
+ type: "reasoning",
553
+ reasoning: "",
554
+ details: []
555
+ };
556
+ message.parts.push(currentReasoningPart);
557
+ }
558
+ currentReasoningPart.details.push({
559
+ type: "redacted",
560
+ data: value.data
561
+ });
562
+ currentReasoningTextDetail = void 0;
563
+ execUpdate();
564
+ },
565
+ onFilePart(value) {
566
+ message.parts.push({
567
+ type: "file",
568
+ mimeType: value.mimeType,
569
+ data: value.data
570
+ });
571
+ execUpdate();
572
+ },
573
+ onSourcePart(value) {
574
+ message.parts.push({
575
+ type: "source",
576
+ source: value
577
+ });
578
+ execUpdate();
579
+ },
580
+ onToolCallStreamingStartPart(value) {
581
+ if (message.toolInvocations == null) {
582
+ message.toolInvocations = [];
583
+ }
584
+ partialToolCalls[value.toolCallId] = {
585
+ text: "",
586
+ step,
587
+ toolName: value.toolName,
588
+ index: message.toolInvocations.length
589
+ };
590
+ const invocation = {
591
+ state: "partial-call",
592
+ step,
593
+ toolCallId: value.toolCallId,
594
+ toolName: value.toolName,
595
+ args: void 0
596
+ };
597
+ message.toolInvocations.push(invocation);
598
+ updateToolInvocationPart(value.toolCallId, invocation);
599
+ execUpdate();
600
+ },
601
+ onToolCallDeltaPart(value) {
602
+ const partialToolCall = partialToolCalls[value.toolCallId];
603
+ partialToolCall.text += value.argsTextDelta;
604
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
605
+ const invocation = {
606
+ state: "partial-call",
607
+ step: partialToolCall.step,
608
+ toolCallId: value.toolCallId,
609
+ toolName: partialToolCall.toolName,
610
+ args: partialArgs
611
+ };
612
+ message.toolInvocations[partialToolCall.index] = invocation;
613
+ updateToolInvocationPart(value.toolCallId, invocation);
614
+ execUpdate();
615
+ },
616
+ async onToolCallPart(value) {
617
+ const invocation = {
618
+ state: "call",
619
+ step,
620
+ ...value
621
+ };
622
+ if (partialToolCalls[value.toolCallId] != null) {
623
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
624
+ } else {
625
+ if (message.toolInvocations == null) {
626
+ message.toolInvocations = [];
627
+ }
628
+ message.toolInvocations.push(invocation);
629
+ }
630
+ updateToolInvocationPart(value.toolCallId, invocation);
631
+ execUpdate();
632
+ if (onToolCall) {
633
+ const result = await onToolCall({ toolCall: value });
634
+ if (result != null) {
635
+ const invocation2 = {
636
+ state: "result",
637
+ step,
638
+ ...value,
639
+ result
640
+ };
641
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
642
+ updateToolInvocationPart(value.toolCallId, invocation2);
643
+ execUpdate();
644
+ }
645
+ }
646
+ },
647
+ onToolResultPart(value) {
648
+ const toolInvocations = message.toolInvocations;
649
+ if (toolInvocations == null) {
650
+ throw new Error("tool_result must be preceded by a tool_call");
651
+ }
652
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
653
+ if (toolInvocationIndex === -1) {
654
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
655
+ }
656
+ const invocation = {
657
+ ...toolInvocations[toolInvocationIndex],
658
+ state: "result",
659
+ ...value
660
+ };
661
+ toolInvocations[toolInvocationIndex] = invocation;
662
+ updateToolInvocationPart(value.toolCallId, invocation);
663
+ execUpdate();
664
+ },
665
+ onDataPart(value) {
666
+ data.push(...value);
667
+ execUpdate();
668
+ },
669
+ onMessageAnnotationsPart(value) {
670
+ if (messageAnnotations == null) {
671
+ messageAnnotations = [...value];
672
+ } else {
673
+ messageAnnotations.push(...value);
674
+ }
675
+ execUpdate();
676
+ },
677
+ onFinishStepPart(value) {
678
+ step += 1;
679
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
680
+ currentReasoningPart = void 0;
681
+ currentReasoningTextDetail = void 0;
682
+ },
683
+ onStartStepPart(value) {
684
+ if (!replaceLastMessage) {
685
+ message.id = value.messageId;
686
+ }
687
+ message.parts.push({ type: "step-start" });
688
+ execUpdate();
689
+ },
690
+ onFinishMessagePart(value) {
691
+ finishReason = value.finishReason;
692
+ if (value.usage != null) {
693
+ usage = value.usage;
694
+ }
695
+ },
696
+ onErrorPart(error) {
697
+ throw new Error(error);
698
+ }
144
699
  });
700
+ onFinish?.({ message, finishReason, usage });
145
701
  }
146
702
  /**
147
703
  * Streams a response from the agent
148
704
  * @param params - Stream parameters including prompt
149
705
  * @returns Promise containing the enhanced Response object with processDataStream method
150
706
  */
151
- async stream(params) {
707
+ async streamLegacy(params) {
152
708
  const processedParams = {
153
709
  ...params,
154
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
155
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
710
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
711
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
712
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
713
+ clientTools: processClientTools(params.clientTools)
714
+ };
715
+ const { readable, writable } = new TransformStream();
716
+ const response = await this.processStreamResponseLegacy(processedParams, writable);
717
+ const streamResponse = new Response(readable, {
718
+ status: response.status,
719
+ statusText: response.statusText,
720
+ headers: response.headers
721
+ });
722
+ streamResponse.processDataStream = async (options = {}) => {
723
+ await uiUtils.processDataStream({
724
+ stream: streamResponse.body,
725
+ ...options
726
+ });
727
+ };
728
+ return streamResponse;
729
+ }
730
+ async processChatResponse_vNext({
731
+ stream,
732
+ update,
733
+ onToolCall,
734
+ onFinish,
735
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
736
+ lastMessage
737
+ }) {
738
+ const replaceLastMessage = lastMessage?.role === "assistant";
739
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
740
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
741
+ return Math.max(max, toolInvocation.step ?? 0);
742
+ }, 0) ?? 0) : 0;
743
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
744
+ id: uuid.v4(),
745
+ createdAt: getCurrentDate(),
746
+ role: "assistant",
747
+ content: "",
748
+ parts: []
749
+ };
750
+ let currentTextPart = void 0;
751
+ let currentReasoningPart = void 0;
752
+ let currentReasoningTextDetail = void 0;
753
+ function updateToolInvocationPart(toolCallId, invocation) {
754
+ const part = message.parts.find(
755
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
756
+ );
757
+ if (part != null) {
758
+ part.toolInvocation = invocation;
759
+ } else {
760
+ message.parts.push({
761
+ type: "tool-invocation",
762
+ toolInvocation: invocation
763
+ });
764
+ }
765
+ }
766
+ const data = [];
767
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
768
+ const partialToolCalls = {};
769
+ let usage = {
770
+ completionTokens: NaN,
771
+ promptTokens: NaN,
772
+ totalTokens: NaN
156
773
  };
157
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
774
+ let finishReason = "unknown";
775
+ function execUpdate() {
776
+ const copiedData = [...data];
777
+ if (messageAnnotations?.length) {
778
+ message.annotations = messageAnnotations;
779
+ }
780
+ const copiedMessage = {
781
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
782
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
783
+ ...structuredClone(message),
784
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
785
+ // hashing approach by default to detect changes, but it only works for shallow
786
+ // changes. This is why we need to add a revision id to ensure that the message
787
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
788
+ // forwarded to rendering):
789
+ revisionId: uuid.v4()
790
+ };
791
+ update({
792
+ message: copiedMessage,
793
+ data: copiedData,
794
+ replaceLastMessage
795
+ });
796
+ }
797
+ await processMastraStream({
798
+ stream,
799
+ // TODO: casting as any here because the stream types were all typed as any before in core.
800
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
801
+ onChunk: async (chunk) => {
802
+ switch (chunk.type) {
803
+ case "tripwire": {
804
+ message.parts.push({
805
+ type: "text",
806
+ text: chunk.payload.tripwireReason
807
+ });
808
+ execUpdate();
809
+ break;
810
+ }
811
+ case "step-start": {
812
+ if (!replaceLastMessage) {
813
+ message.id = chunk.payload.messageId;
814
+ }
815
+ message.parts.push({ type: "step-start" });
816
+ execUpdate();
817
+ break;
818
+ }
819
+ case "text-delta": {
820
+ if (currentTextPart == null) {
821
+ currentTextPart = {
822
+ type: "text",
823
+ text: chunk.payload.text
824
+ };
825
+ message.parts.push(currentTextPart);
826
+ } else {
827
+ currentTextPart.text += chunk.payload.text;
828
+ }
829
+ message.content += chunk.payload.text;
830
+ execUpdate();
831
+ break;
832
+ }
833
+ case "reasoning-delta": {
834
+ if (currentReasoningTextDetail == null) {
835
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
836
+ if (currentReasoningPart != null) {
837
+ currentReasoningPart.details.push(currentReasoningTextDetail);
838
+ }
839
+ } else {
840
+ currentReasoningTextDetail.text += chunk.payload.text;
841
+ }
842
+ if (currentReasoningPart == null) {
843
+ currentReasoningPart = {
844
+ type: "reasoning",
845
+ reasoning: chunk.payload.text,
846
+ details: [currentReasoningTextDetail]
847
+ };
848
+ message.parts.push(currentReasoningPart);
849
+ } else {
850
+ currentReasoningPart.reasoning += chunk.payload.text;
851
+ }
852
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
853
+ execUpdate();
854
+ break;
855
+ }
856
+ case "file": {
857
+ message.parts.push({
858
+ type: "file",
859
+ mimeType: chunk.payload.mimeType,
860
+ data: chunk.payload.data
861
+ });
862
+ execUpdate();
863
+ break;
864
+ }
865
+ case "source": {
866
+ message.parts.push({
867
+ type: "source",
868
+ source: chunk.payload.source
869
+ });
870
+ execUpdate();
871
+ break;
872
+ }
873
+ case "tool-call": {
874
+ const invocation = {
875
+ state: "call",
876
+ step,
877
+ ...chunk.payload
878
+ };
879
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
880
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
881
+ } else {
882
+ if (message.toolInvocations == null) {
883
+ message.toolInvocations = [];
884
+ }
885
+ message.toolInvocations.push(invocation);
886
+ }
887
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
888
+ execUpdate();
889
+ if (onToolCall) {
890
+ const result = await onToolCall({ toolCall: chunk.payload });
891
+ if (result != null) {
892
+ const invocation2 = {
893
+ state: "result",
894
+ step,
895
+ ...chunk.payload,
896
+ result
897
+ };
898
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
899
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
900
+ execUpdate();
901
+ }
902
+ }
903
+ }
904
+ case "tool-call-input-streaming-start": {
905
+ if (message.toolInvocations == null) {
906
+ message.toolInvocations = [];
907
+ }
908
+ partialToolCalls[chunk.payload.toolCallId] = {
909
+ text: "",
910
+ step,
911
+ toolName: chunk.payload.toolName,
912
+ index: message.toolInvocations.length
913
+ };
914
+ const invocation = {
915
+ state: "partial-call",
916
+ step,
917
+ toolCallId: chunk.payload.toolCallId,
918
+ toolName: chunk.payload.toolName,
919
+ args: chunk.payload.args
920
+ };
921
+ message.toolInvocations.push(invocation);
922
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
923
+ execUpdate();
924
+ break;
925
+ }
926
+ case "tool-call-delta": {
927
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
928
+ partialToolCall.text += chunk.payload.argsTextDelta;
929
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
930
+ const invocation = {
931
+ state: "partial-call",
932
+ step: partialToolCall.step,
933
+ toolCallId: chunk.payload.toolCallId,
934
+ toolName: partialToolCall.toolName,
935
+ args: partialArgs
936
+ };
937
+ message.toolInvocations[partialToolCall.index] = invocation;
938
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
939
+ execUpdate();
940
+ break;
941
+ }
942
+ case "tool-result": {
943
+ const toolInvocations = message.toolInvocations;
944
+ if (toolInvocations == null) {
945
+ throw new Error("tool_result must be preceded by a tool_call");
946
+ }
947
+ const toolInvocationIndex = toolInvocations.findIndex(
948
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
949
+ );
950
+ if (toolInvocationIndex === -1) {
951
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
952
+ }
953
+ const invocation = {
954
+ ...toolInvocations[toolInvocationIndex],
955
+ state: "result",
956
+ ...chunk.payload
957
+ };
958
+ toolInvocations[toolInvocationIndex] = invocation;
959
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
960
+ execUpdate();
961
+ break;
962
+ }
963
+ case "error": {
964
+ throw error.getErrorFromUnknown(chunk.payload.error, {
965
+ fallbackMessage: "Unknown error in stream",
966
+ supportSerialization: false
967
+ });
968
+ }
969
+ case "data": {
970
+ data.push(...chunk.payload.data);
971
+ execUpdate();
972
+ break;
973
+ }
974
+ case "step-finish": {
975
+ step += 1;
976
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
977
+ currentReasoningPart = void 0;
978
+ currentReasoningTextDetail = void 0;
979
+ execUpdate();
980
+ break;
981
+ }
982
+ case "finish": {
983
+ finishReason = chunk.payload.stepResult.reason;
984
+ if (chunk.payload.usage != null) {
985
+ usage = chunk.payload.usage;
986
+ }
987
+ break;
988
+ }
989
+ }
990
+ }
991
+ });
992
+ onFinish?.({ message, finishReason, usage });
993
+ }
994
+ async processStreamResponse(processedParams, writable, route = "stream") {
995
+ const response = await this.request(`/api/agents/${this.agentId}/${route}`, {
158
996
  method: "POST",
159
997
  body: processedParams,
160
998
  stream: true
@@ -162,91 +1000,411 @@ var Agent = class extends BaseResource {
162
1000
  if (!response.body) {
163
1001
  throw new Error("No response body");
164
1002
  }
165
- response.processDataStream = async (options = {}) => {
166
- await uiUtils.processDataStream({
167
- stream: response.body,
1003
+ try {
1004
+ let toolCalls = [];
1005
+ let messages = [];
1006
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1007
+ streamForWritable.pipeTo(
1008
+ new WritableStream({
1009
+ async write(chunk) {
1010
+ let writer;
1011
+ try {
1012
+ writer = writable.getWriter();
1013
+ const text = new TextDecoder().decode(chunk);
1014
+ const lines = text.split("\n\n");
1015
+ const readableLines = lines.filter((line) => line !== "[DONE]").join("\n\n");
1016
+ await writer.write(new TextEncoder().encode(readableLines));
1017
+ } catch {
1018
+ await writer?.write(chunk);
1019
+ } finally {
1020
+ writer?.releaseLock();
1021
+ }
1022
+ }
1023
+ }),
1024
+ {
1025
+ preventClose: true
1026
+ }
1027
+ ).catch((error) => {
1028
+ console.error("Error piping to writable stream:", error);
1029
+ });
1030
+ this.processChatResponse_vNext({
1031
+ stream: streamForProcessing,
1032
+ update: ({ message }) => {
1033
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1034
+ if (existingIndex !== -1) {
1035
+ messages[existingIndex] = message;
1036
+ } else {
1037
+ messages.push(message);
1038
+ }
1039
+ },
1040
+ onFinish: async ({ finishReason, message }) => {
1041
+ if (finishReason === "tool-calls") {
1042
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1043
+ if (toolCall) {
1044
+ toolCalls.push(toolCall);
1045
+ }
1046
+ let shouldExecuteClientTool = false;
1047
+ for (const toolCall2 of toolCalls) {
1048
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1049
+ if (clientTool && clientTool.execute) {
1050
+ shouldExecuteClientTool = true;
1051
+ const result = await clientTool.execute(
1052
+ {
1053
+ context: toolCall2?.args,
1054
+ runId: processedParams.runId,
1055
+ resourceId: processedParams.resourceId,
1056
+ threadId: processedParams.threadId,
1057
+ runtimeContext: processedParams.runtimeContext,
1058
+ // TODO: Pass proper tracing context when client-js supports tracing
1059
+ tracingContext: { currentSpan: void 0 },
1060
+ suspend: async () => {
1061
+ }
1062
+ },
1063
+ {
1064
+ messages: response.messages,
1065
+ toolCallId: toolCall2?.toolCallId
1066
+ }
1067
+ );
1068
+ const lastMessageRaw = messages[messages.length - 1];
1069
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1070
+ const toolInvocationPart = lastMessage?.parts?.find(
1071
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1072
+ );
1073
+ if (toolInvocationPart) {
1074
+ toolInvocationPart.toolInvocation = {
1075
+ ...toolInvocationPart.toolInvocation,
1076
+ state: "result",
1077
+ result
1078
+ };
1079
+ }
1080
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1081
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1082
+ );
1083
+ if (toolInvocation) {
1084
+ toolInvocation.state = "result";
1085
+ toolInvocation.result = result;
1086
+ }
1087
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1088
+ this.processStreamResponse(
1089
+ {
1090
+ ...processedParams,
1091
+ messages: updatedMessages
1092
+ },
1093
+ writable
1094
+ ).catch((error) => {
1095
+ console.error("Error processing stream response:", error);
1096
+ });
1097
+ }
1098
+ }
1099
+ if (!shouldExecuteClientTool) {
1100
+ setTimeout(() => {
1101
+ writable.close();
1102
+ }, 0);
1103
+ }
1104
+ } else {
1105
+ setTimeout(() => {
1106
+ writable.close();
1107
+ }, 0);
1108
+ }
1109
+ },
1110
+ lastMessage: void 0
1111
+ }).catch((error) => {
1112
+ console.error("Error processing stream response:", error);
1113
+ });
1114
+ } catch (error) {
1115
+ console.error("Error processing stream response:", error);
1116
+ }
1117
+ return response;
1118
+ }
1119
+ async network(params) {
1120
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1121
+ method: "POST",
1122
+ body: params,
1123
+ stream: true
1124
+ });
1125
+ if (!response.body) {
1126
+ throw new Error("No response body");
1127
+ }
1128
+ const streamResponse = new Response(response.body, {
1129
+ status: response.status,
1130
+ statusText: response.statusText,
1131
+ headers: response.headers
1132
+ });
1133
+ streamResponse.processDataStream = async ({
1134
+ onChunk
1135
+ }) => {
1136
+ await processMastraNetworkStream({
1137
+ stream: streamResponse.body,
1138
+ onChunk
1139
+ });
1140
+ };
1141
+ return streamResponse;
1142
+ }
1143
+ async stream(messagesOrParams, options) {
1144
+ let params;
1145
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1146
+ params = messagesOrParams;
1147
+ } else {
1148
+ params = {
1149
+ messages: messagesOrParams,
168
1150
  ...options
1151
+ };
1152
+ }
1153
+ const processedParams = {
1154
+ ...params,
1155
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1156
+ clientTools: processClientTools(params.clientTools),
1157
+ structuredOutput: params.structuredOutput ? {
1158
+ ...params.structuredOutput,
1159
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1160
+ } : void 0
1161
+ };
1162
+ const { readable, writable } = new TransformStream();
1163
+ const response = await this.processStreamResponse(processedParams, writable);
1164
+ const streamResponse = new Response(readable, {
1165
+ status: response.status,
1166
+ statusText: response.statusText,
1167
+ headers: response.headers
1168
+ });
1169
+ streamResponse.processDataStream = async ({
1170
+ onChunk
1171
+ }) => {
1172
+ await processMastraStream({
1173
+ stream: streamResponse.body,
1174
+ onChunk
169
1175
  });
170
1176
  };
1177
+ return streamResponse;
1178
+ }
1179
+ async approveToolCall(params) {
1180
+ const { readable, writable } = new TransformStream();
1181
+ const response = await this.processStreamResponse(params, writable, "approve-tool-call");
1182
+ const streamResponse = new Response(readable, {
1183
+ status: response.status,
1184
+ statusText: response.statusText,
1185
+ headers: response.headers
1186
+ });
1187
+ streamResponse.processDataStream = async ({
1188
+ onChunk
1189
+ }) => {
1190
+ await processMastraStream({
1191
+ stream: streamResponse.body,
1192
+ onChunk
1193
+ });
1194
+ };
1195
+ return streamResponse;
1196
+ }
1197
+ async declineToolCall(params) {
1198
+ const { readable, writable } = new TransformStream();
1199
+ const response = await this.processStreamResponse(params, writable, "decline-tool-call");
1200
+ const streamResponse = new Response(readable, {
1201
+ status: response.status,
1202
+ statusText: response.statusText,
1203
+ headers: response.headers
1204
+ });
1205
+ streamResponse.processDataStream = async ({
1206
+ onChunk
1207
+ }) => {
1208
+ await processMastraStream({
1209
+ stream: streamResponse.body,
1210
+ onChunk
1211
+ });
1212
+ };
1213
+ return streamResponse;
1214
+ }
1215
+ /**
1216
+ * Processes the stream response and handles tool calls
1217
+ */
1218
+ async processStreamResponseLegacy(processedParams, writable) {
1219
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1220
+ method: "POST",
1221
+ body: processedParams,
1222
+ stream: true
1223
+ });
1224
+ if (!response.body) {
1225
+ throw new Error("No response body");
1226
+ }
1227
+ try {
1228
+ let toolCalls = [];
1229
+ let messages = [];
1230
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1231
+ streamForWritable.pipeTo(writable, {
1232
+ preventClose: true
1233
+ }).catch((error) => {
1234
+ console.error("Error piping to writable stream:", error);
1235
+ });
1236
+ this.processChatResponse({
1237
+ stream: streamForProcessing,
1238
+ update: ({ message }) => {
1239
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1240
+ if (existingIndex !== -1) {
1241
+ messages[existingIndex] = message;
1242
+ } else {
1243
+ messages.push(message);
1244
+ }
1245
+ },
1246
+ onFinish: async ({ finishReason, message }) => {
1247
+ if (finishReason === "tool-calls") {
1248
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1249
+ if (toolCall) {
1250
+ toolCalls.push(toolCall);
1251
+ }
1252
+ for (const toolCall2 of toolCalls) {
1253
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1254
+ if (clientTool && clientTool.execute) {
1255
+ const result = await clientTool.execute(
1256
+ {
1257
+ context: toolCall2?.args,
1258
+ runId: processedParams.runId,
1259
+ resourceId: processedParams.resourceId,
1260
+ threadId: processedParams.threadId,
1261
+ runtimeContext: processedParams.runtimeContext,
1262
+ // TODO: Pass proper tracing context when client-js supports tracing
1263
+ tracingContext: { currentSpan: void 0 },
1264
+ suspend: async () => {
1265
+ }
1266
+ },
1267
+ {
1268
+ messages: response.messages,
1269
+ toolCallId: toolCall2?.toolCallId
1270
+ }
1271
+ );
1272
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1273
+ const toolInvocationPart = lastMessage?.parts?.find(
1274
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1275
+ );
1276
+ if (toolInvocationPart) {
1277
+ toolInvocationPart.toolInvocation = {
1278
+ ...toolInvocationPart.toolInvocation,
1279
+ state: "result",
1280
+ result
1281
+ };
1282
+ }
1283
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1284
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1285
+ );
1286
+ if (toolInvocation) {
1287
+ toolInvocation.state = "result";
1288
+ toolInvocation.result = result;
1289
+ }
1290
+ const writer = writable.getWriter();
1291
+ try {
1292
+ await writer.write(
1293
+ new TextEncoder().encode(
1294
+ "a:" + JSON.stringify({
1295
+ toolCallId: toolCall2.toolCallId,
1296
+ result
1297
+ }) + "\n"
1298
+ )
1299
+ );
1300
+ } finally {
1301
+ writer.releaseLock();
1302
+ }
1303
+ this.processStreamResponseLegacy(
1304
+ {
1305
+ ...processedParams,
1306
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1307
+ },
1308
+ writable
1309
+ ).catch((error) => {
1310
+ console.error("Error processing stream response:", error);
1311
+ });
1312
+ }
1313
+ }
1314
+ } else {
1315
+ setTimeout(() => {
1316
+ writable.close();
1317
+ }, 0);
1318
+ }
1319
+ },
1320
+ lastMessage: void 0
1321
+ }).catch((error) => {
1322
+ console.error("Error processing stream response:", error);
1323
+ });
1324
+ } catch (error) {
1325
+ console.error("Error processing stream response:", error);
1326
+ }
171
1327
  return response;
172
1328
  }
173
1329
  /**
174
1330
  * Gets details about a specific tool available to the agent
175
1331
  * @param toolId - ID of the tool to retrieve
1332
+ * @param runtimeContext - Optional runtime context to pass as query parameter
176
1333
  * @returns Promise containing tool details
177
1334
  */
178
- getTool(toolId) {
179
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1335
+ getTool(toolId, runtimeContext) {
1336
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
1337
+ }
1338
+ /**
1339
+ * Executes a tool for the agent
1340
+ * @param toolId - ID of the tool to execute
1341
+ * @param params - Parameters required for tool execution
1342
+ * @returns Promise containing the tool execution results
1343
+ */
1344
+ executeTool(toolId, params) {
1345
+ const body = {
1346
+ data: params.data,
1347
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1348
+ };
1349
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1350
+ method: "POST",
1351
+ body
1352
+ });
180
1353
  }
181
1354
  /**
182
1355
  * Retrieves evaluation results for the agent
1356
+ * @param runtimeContext - Optional runtime context to pass as query parameter
183
1357
  * @returns Promise containing agent evaluations
184
1358
  */
185
- evals() {
186
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1359
+ evals(runtimeContext) {
1360
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
187
1361
  }
188
1362
  /**
189
1363
  * Retrieves live evaluation results for the agent
1364
+ * @param runtimeContext - Optional runtime context to pass as query parameter
190
1365
  * @returns Promise containing live agent evaluations
191
1366
  */
192
- liveEvals() {
193
- return this.request(`/api/agents/${this.agentId}/evals/live`);
194
- }
195
- };
196
- var Network = class extends BaseResource {
197
- constructor(options, networkId) {
198
- super(options);
199
- this.networkId = networkId;
1367
+ liveEvals(runtimeContext) {
1368
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
200
1369
  }
201
1370
  /**
202
- * Retrieves details about the network
203
- * @returns Promise containing network details
1371
+ * Updates the model for the agent
1372
+ * @param params - Parameters for updating the model
1373
+ * @returns Promise containing the updated model
204
1374
  */
205
- details() {
206
- return this.request(`/api/networks/${this.networkId}`);
1375
+ updateModel(params) {
1376
+ return this.request(`/api/agents/${this.agentId}/model`, {
1377
+ method: "POST",
1378
+ body: params
1379
+ });
207
1380
  }
208
1381
  /**
209
- * Generates a response from the agent
210
- * @param params - Generation parameters including prompt
211
- * @returns Promise containing the generated response
1382
+ * Updates the model for the agent in the model list
1383
+ * @param params - Parameters for updating the model
1384
+ * @returns Promise containing the updated model
212
1385
  */
213
- generate(params) {
214
- const processedParams = {
215
- ...params,
216
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
217
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
218
- };
219
- return this.request(`/api/networks/${this.networkId}/generate`, {
1386
+ updateModelInModelList({ modelConfigId, ...params }) {
1387
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
220
1388
  method: "POST",
221
- body: processedParams
1389
+ body: params
222
1390
  });
223
1391
  }
224
1392
  /**
225
- * Streams a response from the agent
226
- * @param params - Stream parameters including prompt
227
- * @returns Promise containing the enhanced Response object with processDataStream method
1393
+ * Reorders the models for the agent
1394
+ * @param params - Parameters for reordering the model list
1395
+ * @returns Promise containing the updated model list
228
1396
  */
229
- async stream(params) {
230
- const processedParams = {
231
- ...params,
232
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
233
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
234
- };
235
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1397
+ reorderModelList(params) {
1398
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
236
1399
  method: "POST",
237
- body: processedParams,
238
- stream: true
1400
+ body: params
239
1401
  });
240
- if (!response.body) {
241
- throw new Error("No response body");
242
- }
243
- response.processDataStream = async (options = {}) => {
244
- await uiUtils.processDataStream({
245
- stream: response.body,
246
- ...options
247
- });
248
- };
249
- return response;
1402
+ }
1403
+ async generateVNext(_messagesOrParams, _options) {
1404
+ throw new Error("generateVNext has been renamed to generate. Please use generate instead.");
1405
+ }
1406
+ async streamVNext(_messagesOrParams, _options) {
1407
+ throw new Error("streamVNext has been renamed to stream. Please use stream instead.");
250
1408
  }
251
1409
  };
252
1410
 
@@ -259,37 +1417,91 @@ var MemoryThread = class extends BaseResource {
259
1417
  }
260
1418
  /**
261
1419
  * Retrieves the memory thread details
1420
+ * @param runtimeContext - Optional runtime context to pass as query parameter
262
1421
  * @returns Promise containing thread details including title and metadata
263
1422
  */
264
- get() {
265
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`);
1423
+ get(runtimeContext) {
1424
+ return this.request(
1425
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${runtimeContextQueryString(runtimeContext, "&")}`
1426
+ );
266
1427
  }
267
1428
  /**
268
1429
  * Updates the memory thread properties
269
- * @param params - Update parameters including title and metadata
1430
+ * @param params - Update parameters including title, metadata, and optional runtime context
270
1431
  * @returns Promise containing updated thread details
271
1432
  */
272
1433
  update(params) {
273
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
274
- method: "PATCH",
275
- body: params
276
- });
1434
+ return this.request(
1435
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`,
1436
+ {
1437
+ method: "PATCH",
1438
+ body: params
1439
+ }
1440
+ );
277
1441
  }
278
1442
  /**
279
1443
  * Deletes the memory thread
1444
+ * @param runtimeContext - Optional runtime context to pass as query parameter
280
1445
  * @returns Promise containing deletion result
281
1446
  */
282
- delete() {
283
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
284
- method: "DELETE"
285
- });
1447
+ delete(runtimeContext) {
1448
+ return this.request(
1449
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${runtimeContextQueryString(runtimeContext, "&")}`,
1450
+ {
1451
+ method: "DELETE"
1452
+ }
1453
+ );
286
1454
  }
287
1455
  /**
288
1456
  * Retrieves messages associated with the thread
1457
+ * @param params - Optional parameters including limit for number of messages to retrieve and runtime context
289
1458
  * @returns Promise containing thread messages and UI messages
290
1459
  */
291
- getMessages() {
292
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
1460
+ getMessages(params) {
1461
+ const query = new URLSearchParams({
1462
+ agentId: this.agentId,
1463
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1464
+ });
1465
+ return this.request(
1466
+ `/api/memory/threads/${this.threadId}/messages?${query.toString()}${runtimeContextQueryString(params?.runtimeContext, "&")}`
1467
+ );
1468
+ }
1469
+ /**
1470
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1471
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, message inclusion options, and runtime context
1472
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1473
+ */
1474
+ getMessagesPaginated({
1475
+ selectBy,
1476
+ runtimeContext,
1477
+ ...rest
1478
+ }) {
1479
+ const query = new URLSearchParams({
1480
+ ...rest,
1481
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1482
+ });
1483
+ return this.request(
1484
+ `/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}${runtimeContextQueryString(runtimeContext, "&")}`
1485
+ );
1486
+ }
1487
+ /**
1488
+ * Deletes one or more messages from the thread
1489
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1490
+ * message object with id property, or array of message objects
1491
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1492
+ * @returns Promise containing deletion result
1493
+ */
1494
+ deleteMessages(messageIds, runtimeContext) {
1495
+ const query = new URLSearchParams({
1496
+ agentId: this.agentId
1497
+ });
1498
+ return this.request(
1499
+ `/api/memory/messages/delete?${query.toString()}${runtimeContextQueryString(runtimeContext, "&")}`,
1500
+ {
1501
+ method: "POST",
1502
+ body: { messageIds }
1503
+ }
1504
+ );
293
1505
  }
294
1506
  };
295
1507
 
@@ -302,10 +1514,13 @@ var Vector = class extends BaseResource {
302
1514
  /**
303
1515
  * Retrieves details about a specific vector index
304
1516
  * @param indexName - Name of the index to get details for
1517
+ * @param runtimeContext - Optional runtime context to pass as query parameter
305
1518
  * @returns Promise containing vector index details
306
1519
  */
307
- details(indexName) {
308
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1520
+ details(indexName, runtimeContext) {
1521
+ return this.request(
1522
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1523
+ );
309
1524
  }
310
1525
  /**
311
1526
  * Deletes a vector index
@@ -319,10 +1534,11 @@ var Vector = class extends BaseResource {
319
1534
  }
320
1535
  /**
321
1536
  * Retrieves a list of all available indexes
1537
+ * @param runtimeContext - Optional runtime context to pass as query parameter
322
1538
  * @returns Promise containing array of index names
323
1539
  */
324
- getIndexes() {
325
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1540
+ getIndexes(runtimeContext) {
1541
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
326
1542
  }
327
1543
  /**
328
1544
  * Creates a new vector index
@@ -359,107 +1575,50 @@ var Vector = class extends BaseResource {
359
1575
  }
360
1576
  };
361
1577
 
362
- // src/resources/workflow.ts
363
- var RECORD_SEPARATOR = "";
364
- var Workflow = class extends BaseResource {
365
- constructor(options, workflowId) {
1578
+ // src/resources/tool.ts
1579
+ var Tool = class extends BaseResource {
1580
+ constructor(options, toolId) {
366
1581
  super(options);
367
- this.workflowId = workflowId;
1582
+ this.toolId = toolId;
368
1583
  }
369
1584
  /**
370
- * Retrieves details about the workflow
371
- * @returns Promise containing workflow details including steps and graphs
1585
+ * Retrieves details about the tool
1586
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1587
+ * @returns Promise containing tool details including description and schemas
372
1588
  */
373
- details() {
374
- return this.request(`/api/workflows/${this.workflowId}`);
1589
+ details(runtimeContext) {
1590
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
375
1591
  }
376
1592
  /**
377
- * @deprecated Use `startAsync` instead
378
- * Executes the workflow with the provided parameters
379
- * @param params - Parameters required for workflow execution
380
- * @returns Promise containing the workflow execution results
1593
+ * Executes the tool with the provided parameters
1594
+ * @param params - Parameters required for tool execution
1595
+ * @returns Promise containing the tool execution results
381
1596
  */
382
1597
  execute(params) {
383
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
384
- method: "POST",
385
- body: params
386
- });
387
- }
388
- /**
389
- * Creates a new workflow run
390
- * @returns Promise containing the generated run ID
391
- */
392
- createRun(params) {
393
- const searchParams = new URLSearchParams();
394
- if (!!params?.runId) {
395
- searchParams.set("runId", params.runId);
396
- }
397
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
398
- method: "POST"
399
- });
400
- }
401
- /**
402
- * Starts a workflow run synchronously without waiting for the workflow to complete
403
- * @param params - Object containing the runId and triggerData
404
- * @returns Promise containing success message
405
- */
406
- start(params) {
407
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
408
- method: "POST",
409
- body: params?.triggerData
410
- });
411
- }
412
- /**
413
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
414
- * @param stepId - ID of the step to resume
415
- * @param runId - ID of the workflow run
416
- * @param context - Context to resume the workflow with
417
- * @returns Promise containing the workflow resume results
418
- */
419
- resume({
420
- stepId,
421
- runId,
422
- context
423
- }) {
424
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
425
- method: "POST",
426
- body: {
427
- stepId,
428
- context
429
- }
430
- });
431
- }
432
- /**
433
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
434
- * @param params - Object containing the optional runId and triggerData
435
- * @returns Promise containing the workflow execution results
436
- */
437
- startAsync(params) {
438
- const searchParams = new URLSearchParams();
439
- if (!!params?.runId) {
440
- searchParams.set("runId", params.runId);
1598
+ const url = new URLSearchParams();
1599
+ if (params.runId) {
1600
+ url.set("runId", params.runId);
441
1601
  }
442
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1602
+ const body = {
1603
+ data: params.data,
1604
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1605
+ };
1606
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
443
1607
  method: "POST",
444
- body: params?.triggerData
1608
+ body
445
1609
  });
446
1610
  }
447
- /**
448
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
449
- * @param params - Object containing the runId, stepId, and context
450
- * @returns Promise containing the workflow resume results
451
- */
452
- resumeAsync(params) {
453
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
454
- method: "POST",
455
- body: {
456
- stepId: params.stepId,
457
- context: params.context
458
- }
459
- });
1611
+ };
1612
+
1613
+ // src/resources/workflow.ts
1614
+ var RECORD_SEPARATOR = "";
1615
+ var Workflow = class extends BaseResource {
1616
+ constructor(options, workflowId) {
1617
+ super(options);
1618
+ this.workflowId = workflowId;
460
1619
  }
461
1620
  /**
462
- * Creates an async generator that processes a readable stream and yields records
1621
+ * Creates an async generator that processes a readable stream and yields workflow records
463
1622
  * separated by the Record Separator character (\x1E)
464
1623
  *
465
1624
  * @param stream - The readable stream to process
@@ -489,7 +1648,7 @@ var Workflow = class extends BaseResource {
489
1648
  }
490
1649
  }
491
1650
  }
492
- } catch (error) {
1651
+ } catch {
493
1652
  }
494
1653
  }
495
1654
  if (buffer) {
@@ -504,120 +1663,1389 @@ var Workflow = class extends BaseResource {
504
1663
  }
505
1664
  }
506
1665
  /**
507
- * Watches workflow transitions in real-time
508
- * @param runId - Optional run ID to filter the watch stream
509
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1666
+ * Retrieves details about the workflow
1667
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1668
+ * @returns Promise containing workflow details including steps and graphs
510
1669
  */
511
- async watch({ runId }, onRecord) {
512
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
513
- stream: true
514
- });
515
- if (!response.ok) {
516
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
1670
+ details(runtimeContext) {
1671
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1672
+ }
1673
+ /**
1674
+ * Retrieves all runs for a workflow
1675
+ * @param params - Parameters for filtering runs
1676
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1677
+ * @returns Promise containing workflow runs array
1678
+ */
1679
+ runs(params, runtimeContext) {
1680
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1681
+ const searchParams = new URLSearchParams();
1682
+ if (params?.fromDate) {
1683
+ searchParams.set("fromDate", params.fromDate.toISOString());
517
1684
  }
518
- if (!response.body) {
519
- throw new Error("Response body is null");
1685
+ if (params?.toDate) {
1686
+ searchParams.set("toDate", params.toDate.toISOString());
520
1687
  }
521
- for await (const record of this.streamProcessor(response.body)) {
522
- onRecord(record);
1688
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1689
+ searchParams.set("limit", String(params.limit));
1690
+ }
1691
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1692
+ searchParams.set("offset", String(params.offset));
1693
+ }
1694
+ if (params?.resourceId) {
1695
+ searchParams.set("resourceId", params.resourceId);
1696
+ }
1697
+ if (runtimeContextParam) {
1698
+ searchParams.set("runtimeContext", runtimeContextParam);
1699
+ }
1700
+ if (searchParams.size) {
1701
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1702
+ } else {
1703
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
523
1704
  }
524
- }
525
- };
526
-
527
- // src/resources/tool.ts
528
- var Tool = class extends BaseResource {
529
- constructor(options, toolId) {
530
- super(options);
531
- this.toolId = toolId;
532
1705
  }
533
1706
  /**
534
- * Retrieves details about the tool
535
- * @returns Promise containing tool details including description and schemas
1707
+ * Retrieves a specific workflow run by its ID
1708
+ * @param runId - The ID of the workflow run to retrieve
1709
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1710
+ * @returns Promise containing the workflow run details
536
1711
  */
537
- details() {
538
- return this.request(`/api/tools/${this.toolId}`);
1712
+ runById(runId, runtimeContext) {
1713
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
539
1714
  }
540
1715
  /**
541
- * Executes the tool with the provided parameters
542
- * @param params - Parameters required for tool execution
543
- * @returns Promise containing the tool execution results
1716
+ * Retrieves the execution result for a specific workflow run by its ID
1717
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1718
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1719
+ * @returns Promise containing the workflow run execution result
544
1720
  */
545
- execute(params) {
546
- return this.request(`/api/tools/${this.toolId}/execute`, {
547
- method: "POST",
548
- body: params
549
- });
550
- }
551
- };
552
-
553
- // src/client.ts
554
- var MastraClient = class extends BaseResource {
555
- constructor(options) {
556
- super(options);
1721
+ runExecutionResult(runId, runtimeContext) {
1722
+ return this.request(
1723
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1724
+ );
557
1725
  }
558
1726
  /**
559
- * Retrieves all available agents
560
- * @returns Promise containing map of agent IDs to agent details
1727
+ * Cancels a specific workflow run by its ID
1728
+ * @param runId - The ID of the workflow run to cancel
1729
+ * @returns Promise containing a success message
561
1730
  */
562
- getAgents() {
563
- return this.request("/api/agents");
1731
+ cancelRun(runId) {
1732
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1733
+ method: "POST"
1734
+ });
564
1735
  }
565
1736
  /**
566
- * Gets an agent instance by ID
567
- * @param agentId - ID of the agent to retrieve
568
- * @returns Agent instance
1737
+ * Sends an event to a specific workflow run by its ID
1738
+ * @param params - Object containing the runId, event and data
1739
+ * @returns Promise containing a success message
569
1740
  */
570
- getAgent(agentId) {
571
- return new Agent(this.options, agentId);
1741
+ sendRunEvent(params) {
1742
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1743
+ method: "POST",
1744
+ body: { event: params.event, data: params.data }
1745
+ });
572
1746
  }
573
1747
  /**
574
- * Retrieves memory threads for a resource
575
- * @param params - Parameters containing the resource ID
576
- * @returns Promise containing array of memory threads
1748
+ * @deprecated Use createRunAsync() instead.
1749
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
577
1750
  */
578
- getMemoryThreads(params) {
579
- return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
1751
+ async createRun(_params) {
1752
+ throw new Error(
1753
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = workflow.createRun();\n After: const run = await workflow.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
1754
+ );
580
1755
  }
581
1756
  /**
582
- * Creates a new memory thread
583
- * @param params - Parameters for creating the memory thread
584
- * @returns Promise containing the created memory thread
1757
+ * Creates a new workflow run
1758
+ * @param params - Optional object containing the optional runId
1759
+ * @returns Promise containing the runId of the created run with methods to control execution
585
1760
  */
586
- createMemoryThread(params) {
587
- return this.request(`/api/memory/threads?agentId=${params.agentId}`, { method: "POST", body: params });
1761
+ async createRunAsync(params) {
1762
+ const searchParams = new URLSearchParams();
1763
+ if (!!params?.runId) {
1764
+ searchParams.set("runId", params.runId);
1765
+ }
1766
+ const res = await this.request(
1767
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1768
+ {
1769
+ method: "POST"
1770
+ }
1771
+ );
1772
+ const runId = res.runId;
1773
+ return {
1774
+ runId,
1775
+ start: async (p) => {
1776
+ return this.start({
1777
+ runId,
1778
+ inputData: p.inputData,
1779
+ runtimeContext: p.runtimeContext,
1780
+ tracingOptions: p.tracingOptions
1781
+ });
1782
+ },
1783
+ startAsync: async (p) => {
1784
+ return this.startAsync({
1785
+ runId,
1786
+ inputData: p.inputData,
1787
+ runtimeContext: p.runtimeContext,
1788
+ tracingOptions: p.tracingOptions
1789
+ });
1790
+ },
1791
+ watch: async (onRecord) => {
1792
+ return this.watch({ runId }, onRecord);
1793
+ },
1794
+ stream: async (p) => {
1795
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1796
+ },
1797
+ resume: async (p) => {
1798
+ return this.resume({
1799
+ runId,
1800
+ step: p.step,
1801
+ resumeData: p.resumeData,
1802
+ runtimeContext: p.runtimeContext,
1803
+ tracingOptions: p.tracingOptions
1804
+ });
1805
+ },
1806
+ resumeAsync: async (p) => {
1807
+ return this.resumeAsync({
1808
+ runId,
1809
+ step: p.step,
1810
+ resumeData: p.resumeData,
1811
+ runtimeContext: p.runtimeContext,
1812
+ tracingOptions: p.tracingOptions
1813
+ });
1814
+ },
1815
+ resumeStreamVNext: async (p) => {
1816
+ return this.resumeStreamVNext({
1817
+ runId,
1818
+ step: p.step,
1819
+ resumeData: p.resumeData,
1820
+ runtimeContext: p.runtimeContext
1821
+ });
1822
+ }
1823
+ };
588
1824
  }
589
1825
  /**
590
- * Gets a memory thread instance by ID
591
- * @param threadId - ID of the memory thread to retrieve
592
- * @returns MemoryThread instance
1826
+ * Starts a workflow run synchronously without waiting for the workflow to complete
1827
+ * @param params - Object containing the runId, inputData and runtimeContext
1828
+ * @returns Promise containing success message
593
1829
  */
594
- getMemoryThread(threadId, agentId) {
595
- return new MemoryThread(this.options, threadId, agentId);
1830
+ start(params) {
1831
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1832
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1833
+ method: "POST",
1834
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1835
+ });
596
1836
  }
597
1837
  /**
598
- * Saves messages to memory
599
- * @param params - Parameters containing messages to save
600
- * @returns Promise containing the saved messages
1838
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1839
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1840
+ * @returns Promise containing success message
601
1841
  */
602
- saveMessageToMemory(params) {
603
- return this.request(`/api/memory/save-messages?agentId=${params.agentId}`, {
1842
+ resume({
1843
+ step,
1844
+ runId,
1845
+ resumeData,
1846
+ tracingOptions,
1847
+ ...rest
1848
+ }) {
1849
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1850
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
604
1851
  method: "POST",
605
- body: params
1852
+ body: {
1853
+ step,
1854
+ resumeData,
1855
+ runtimeContext,
1856
+ tracingOptions
1857
+ }
606
1858
  });
607
1859
  }
608
1860
  /**
609
- * Gets the status of the memory system
610
- * @returns Promise containing memory system status
1861
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1862
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1863
+ * @returns Promise containing the workflow execution results
611
1864
  */
612
- getMemoryStatus(agentId) {
613
- return this.request(`/api/memory/status?agentId=${agentId}`);
1865
+ startAsync(params) {
1866
+ const searchParams = new URLSearchParams();
1867
+ if (!!params?.runId) {
1868
+ searchParams.set("runId", params.runId);
1869
+ }
1870
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1871
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1872
+ method: "POST",
1873
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1874
+ });
614
1875
  }
615
1876
  /**
616
- * Retrieves all available tools
617
- * @returns Promise containing map of tool IDs to tool details
1877
+ * Starts a workflow run and returns a stream
1878
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1879
+ * @returns Promise containing the workflow execution results
618
1880
  */
619
- getTools() {
620
- return this.request("/api/tools");
1881
+ async stream(params) {
1882
+ const searchParams = new URLSearchParams();
1883
+ if (!!params?.runId) {
1884
+ searchParams.set("runId", params.runId);
1885
+ }
1886
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1887
+ const response = await this.request(
1888
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1889
+ {
1890
+ method: "POST",
1891
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions },
1892
+ stream: true
1893
+ }
1894
+ );
1895
+ if (!response.ok) {
1896
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1897
+ }
1898
+ if (!response.body) {
1899
+ throw new Error("Response body is null");
1900
+ }
1901
+ let failedChunk = void 0;
1902
+ const transformStream = new TransformStream({
1903
+ start() {
1904
+ },
1905
+ async transform(chunk, controller) {
1906
+ try {
1907
+ const decoded = new TextDecoder().decode(chunk);
1908
+ const chunks = decoded.split(RECORD_SEPARATOR);
1909
+ for (const chunk2 of chunks) {
1910
+ if (chunk2) {
1911
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1912
+ try {
1913
+ const parsedChunk = JSON.parse(newChunk);
1914
+ controller.enqueue(parsedChunk);
1915
+ failedChunk = void 0;
1916
+ } catch {
1917
+ failedChunk = newChunk;
1918
+ }
1919
+ }
1920
+ }
1921
+ } catch {
1922
+ }
1923
+ }
1924
+ });
1925
+ return response.body.pipeThrough(transformStream);
1926
+ }
1927
+ /**
1928
+ * Observes workflow stream for a workflow run
1929
+ * @param params - Object containing the runId
1930
+ * @returns Promise containing the workflow execution results
1931
+ */
1932
+ async observeStream(params) {
1933
+ const searchParams = new URLSearchParams();
1934
+ searchParams.set("runId", params.runId);
1935
+ const response = await this.request(
1936
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1937
+ {
1938
+ method: "POST",
1939
+ stream: true
1940
+ }
1941
+ );
1942
+ if (!response.ok) {
1943
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1944
+ }
1945
+ if (!response.body) {
1946
+ throw new Error("Response body is null");
1947
+ }
1948
+ let failedChunk = void 0;
1949
+ const transformStream = new TransformStream({
1950
+ start() {
1951
+ },
1952
+ async transform(chunk, controller) {
1953
+ try {
1954
+ const decoded = new TextDecoder().decode(chunk);
1955
+ const chunks = decoded.split(RECORD_SEPARATOR);
1956
+ for (const chunk2 of chunks) {
1957
+ if (chunk2) {
1958
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1959
+ try {
1960
+ const parsedChunk = JSON.parse(newChunk);
1961
+ controller.enqueue(parsedChunk);
1962
+ failedChunk = void 0;
1963
+ } catch {
1964
+ failedChunk = newChunk;
1965
+ }
1966
+ }
1967
+ }
1968
+ } catch {
1969
+ }
1970
+ }
1971
+ });
1972
+ return response.body.pipeThrough(transformStream);
1973
+ }
1974
+ /**
1975
+ * Starts a workflow run and returns a stream
1976
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1977
+ * @returns Promise containing the workflow execution results
1978
+ */
1979
+ async streamVNext(params) {
1980
+ const searchParams = new URLSearchParams();
1981
+ if (!!params?.runId) {
1982
+ searchParams.set("runId", params.runId);
1983
+ }
1984
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1985
+ const response = await this.request(
1986
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1987
+ {
1988
+ method: "POST",
1989
+ body: {
1990
+ inputData: params.inputData,
1991
+ runtimeContext,
1992
+ closeOnSuspend: params.closeOnSuspend,
1993
+ tracingOptions: params.tracingOptions
1994
+ },
1995
+ stream: true
1996
+ }
1997
+ );
1998
+ if (!response.ok) {
1999
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2000
+ }
2001
+ if (!response.body) {
2002
+ throw new Error("Response body is null");
2003
+ }
2004
+ let failedChunk = void 0;
2005
+ const transformStream = new TransformStream({
2006
+ start() {
2007
+ },
2008
+ async transform(chunk, controller) {
2009
+ try {
2010
+ const decoded = new TextDecoder().decode(chunk);
2011
+ const chunks = decoded.split(RECORD_SEPARATOR);
2012
+ for (const chunk2 of chunks) {
2013
+ if (chunk2) {
2014
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2015
+ try {
2016
+ const parsedChunk = JSON.parse(newChunk);
2017
+ controller.enqueue(parsedChunk);
2018
+ failedChunk = void 0;
2019
+ } catch {
2020
+ failedChunk = newChunk;
2021
+ }
2022
+ }
2023
+ }
2024
+ } catch {
2025
+ }
2026
+ }
2027
+ });
2028
+ return response.body.pipeThrough(transformStream);
2029
+ }
2030
+ /**
2031
+ * Observes workflow vNext stream for a workflow run
2032
+ * @param params - Object containing the runId
2033
+ * @returns Promise containing the workflow execution results
2034
+ */
2035
+ async observeStreamVNext(params) {
2036
+ const searchParams = new URLSearchParams();
2037
+ searchParams.set("runId", params.runId);
2038
+ const response = await this.request(
2039
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
2040
+ {
2041
+ method: "POST",
2042
+ stream: true
2043
+ }
2044
+ );
2045
+ if (!response.ok) {
2046
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
2047
+ }
2048
+ if (!response.body) {
2049
+ throw new Error("Response body is null");
2050
+ }
2051
+ let failedChunk = void 0;
2052
+ const transformStream = new TransformStream({
2053
+ start() {
2054
+ },
2055
+ async transform(chunk, controller) {
2056
+ try {
2057
+ const decoded = new TextDecoder().decode(chunk);
2058
+ const chunks = decoded.split(RECORD_SEPARATOR);
2059
+ for (const chunk2 of chunks) {
2060
+ if (chunk2) {
2061
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2062
+ try {
2063
+ const parsedChunk = JSON.parse(newChunk);
2064
+ controller.enqueue(parsedChunk);
2065
+ failedChunk = void 0;
2066
+ } catch {
2067
+ failedChunk = newChunk;
2068
+ }
2069
+ }
2070
+ }
2071
+ } catch {
2072
+ }
2073
+ }
2074
+ });
2075
+ return response.body.pipeThrough(transformStream);
2076
+ }
2077
+ /**
2078
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2079
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2080
+ * @returns Promise containing the workflow resume results
2081
+ */
2082
+ resumeAsync(params) {
2083
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2084
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2085
+ method: "POST",
2086
+ body: {
2087
+ step: params.step,
2088
+ resumeData: params.resumeData,
2089
+ runtimeContext,
2090
+ tracingOptions: params.tracingOptions
2091
+ }
2092
+ });
2093
+ }
2094
+ /**
2095
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2096
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2097
+ * @returns Promise containing the workflow resume results
2098
+ */
2099
+ async resumeStreamVNext(params) {
2100
+ const searchParams = new URLSearchParams();
2101
+ searchParams.set("runId", params.runId);
2102
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2103
+ const response = await this.request(
2104
+ `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
2105
+ {
2106
+ method: "POST",
2107
+ body: {
2108
+ step: params.step,
2109
+ resumeData: params.resumeData,
2110
+ runtimeContext,
2111
+ tracingOptions: params.tracingOptions
2112
+ },
2113
+ stream: true
2114
+ }
2115
+ );
2116
+ if (!response.ok) {
2117
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2118
+ }
2119
+ if (!response.body) {
2120
+ throw new Error("Response body is null");
2121
+ }
2122
+ let failedChunk = void 0;
2123
+ const transformStream = new TransformStream({
2124
+ start() {
2125
+ },
2126
+ async transform(chunk, controller) {
2127
+ try {
2128
+ const decoded = new TextDecoder().decode(chunk);
2129
+ const chunks = decoded.split(RECORD_SEPARATOR);
2130
+ for (const chunk2 of chunks) {
2131
+ if (chunk2) {
2132
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2133
+ try {
2134
+ const parsedChunk = JSON.parse(newChunk);
2135
+ controller.enqueue(parsedChunk);
2136
+ failedChunk = void 0;
2137
+ } catch {
2138
+ failedChunk = newChunk;
2139
+ }
2140
+ }
2141
+ }
2142
+ } catch {
2143
+ }
2144
+ }
2145
+ });
2146
+ return response.body.pipeThrough(transformStream);
2147
+ }
2148
+ /**
2149
+ * Watches workflow transitions in real-time
2150
+ * @param runId - Optional run ID to filter the watch stream
2151
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2152
+ */
2153
+ async watch({ runId }, onRecord) {
2154
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2155
+ stream: true
2156
+ });
2157
+ if (!response.ok) {
2158
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
2159
+ }
2160
+ if (!response.body) {
2161
+ throw new Error("Response body is null");
2162
+ }
2163
+ for await (const record of this.streamProcessor(response.body)) {
2164
+ if (typeof record === "string") {
2165
+ onRecord(JSON.parse(record));
2166
+ } else {
2167
+ onRecord(record);
2168
+ }
2169
+ }
2170
+ }
2171
+ /**
2172
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2173
+ * serializing each as JSON and separating them with the record separator (\x1E).
2174
+ *
2175
+ * @param records - An iterable or async iterable of objects to stream
2176
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2177
+ */
2178
+ static createRecordStream(records) {
2179
+ const encoder = new TextEncoder();
2180
+ return new ReadableStream({
2181
+ async start(controller) {
2182
+ try {
2183
+ for await (const record of records) {
2184
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
2185
+ controller.enqueue(encoder.encode(json));
2186
+ }
2187
+ controller.close();
2188
+ } catch (err) {
2189
+ controller.error(err);
2190
+ }
2191
+ }
2192
+ });
2193
+ }
2194
+ };
2195
+
2196
+ // src/resources/a2a.ts
2197
+ var A2A = class extends BaseResource {
2198
+ constructor(options, agentId) {
2199
+ super(options);
2200
+ this.agentId = agentId;
2201
+ }
2202
+ /**
2203
+ * Get the agent card with metadata about the agent
2204
+ * @returns Promise containing the agent card information
2205
+ */
2206
+ async getCard() {
2207
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2208
+ }
2209
+ /**
2210
+ * Send a message to the agent and gets a message or task response
2211
+ * @param params - Parameters for the task
2212
+ * @returns Promise containing the response
2213
+ */
2214
+ async sendMessage(params) {
2215
+ const response = await this.request(`/a2a/${this.agentId}`, {
2216
+ method: "POST",
2217
+ body: {
2218
+ method: "message/send",
2219
+ params
2220
+ }
2221
+ });
2222
+ return response;
2223
+ }
2224
+ /**
2225
+ * Sends a message to an agent to initiate/continue a task and subscribes
2226
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2227
+ * @param params - Parameters for the task
2228
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2229
+ */
2230
+ async sendStreamingMessage(params) {
2231
+ const response = await this.request(`/a2a/${this.agentId}`, {
2232
+ method: "POST",
2233
+ body: {
2234
+ method: "message/stream",
2235
+ params
2236
+ }
2237
+ });
2238
+ return response;
2239
+ }
2240
+ /**
2241
+ * Get the status and result of a task
2242
+ * @param params - Parameters for querying the task
2243
+ * @returns Promise containing the task response
2244
+ */
2245
+ async getTask(params) {
2246
+ const response = await this.request(`/a2a/${this.agentId}`, {
2247
+ method: "POST",
2248
+ body: {
2249
+ method: "tasks/get",
2250
+ params
2251
+ }
2252
+ });
2253
+ return response;
2254
+ }
2255
+ /**
2256
+ * Cancel a running task
2257
+ * @param params - Parameters identifying the task to cancel
2258
+ * @returns Promise containing the task response
2259
+ */
2260
+ async cancelTask(params) {
2261
+ return this.request(`/a2a/${this.agentId}`, {
2262
+ method: "POST",
2263
+ body: {
2264
+ method: "tasks/cancel",
2265
+ params
2266
+ }
2267
+ });
2268
+ }
2269
+ };
2270
+
2271
+ // src/resources/mcp-tool.ts
2272
+ var MCPTool = class extends BaseResource {
2273
+ serverId;
2274
+ toolId;
2275
+ constructor(options, serverId, toolId) {
2276
+ super(options);
2277
+ this.serverId = serverId;
2278
+ this.toolId = toolId;
2279
+ }
2280
+ /**
2281
+ * Retrieves details about this specific tool from the MCP server.
2282
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2283
+ * @returns Promise containing the tool's information (name, description, schema).
2284
+ */
2285
+ details(runtimeContext) {
2286
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2287
+ }
2288
+ /**
2289
+ * Executes this specific tool on the MCP server.
2290
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2291
+ * @returns Promise containing the result of the tool execution.
2292
+ */
2293
+ execute(params) {
2294
+ const body = {};
2295
+ if (params.data !== void 0) body.data = params.data;
2296
+ if (params.runtimeContext !== void 0) {
2297
+ body.runtimeContext = params.runtimeContext;
2298
+ }
2299
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2300
+ method: "POST",
2301
+ body: Object.keys(body).length > 0 ? body : void 0
2302
+ });
2303
+ }
2304
+ };
2305
+
2306
+ // src/resources/agent-builder.ts
2307
+ var RECORD_SEPARATOR2 = "";
2308
+ var AgentBuilder = class extends BaseResource {
2309
+ constructor(options, actionId) {
2310
+ super(options);
2311
+ this.actionId = actionId;
2312
+ }
2313
+ // Helper function to transform workflow result to action result
2314
+ transformWorkflowResult(result) {
2315
+ if (result.status === "success") {
2316
+ return {
2317
+ success: result.result.success || false,
2318
+ applied: result.result.applied || false,
2319
+ branchName: result.result.branchName,
2320
+ message: result.result.message || "Agent builder action completed",
2321
+ validationResults: result.result.validationResults,
2322
+ error: result.result.error,
2323
+ errors: result.result.errors,
2324
+ stepResults: result.result.stepResults
2325
+ };
2326
+ } else if (result.status === "failed") {
2327
+ return {
2328
+ success: false,
2329
+ applied: false,
2330
+ message: `Agent builder action failed: ${result.error.message}`,
2331
+ error: result.error.message
2332
+ };
2333
+ } else {
2334
+ return {
2335
+ success: false,
2336
+ applied: false,
2337
+ message: "Agent builder action was suspended",
2338
+ error: "Workflow suspended - manual intervention required"
2339
+ };
2340
+ }
2341
+ }
2342
+ /**
2343
+ * Creates a transform stream that parses binary chunks into JSON records.
2344
+ */
2345
+ createRecordParserTransform() {
2346
+ let failedChunk = void 0;
2347
+ return new TransformStream({
2348
+ start() {
2349
+ },
2350
+ async transform(chunk, controller) {
2351
+ try {
2352
+ const decoded = new TextDecoder().decode(chunk);
2353
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2354
+ for (const chunk2 of chunks) {
2355
+ if (chunk2) {
2356
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2357
+ try {
2358
+ const parsedChunk = JSON.parse(newChunk);
2359
+ controller.enqueue(parsedChunk);
2360
+ failedChunk = void 0;
2361
+ } catch {
2362
+ failedChunk = newChunk;
2363
+ }
2364
+ }
2365
+ }
2366
+ } catch {
2367
+ }
2368
+ }
2369
+ });
2370
+ }
2371
+ /**
2372
+ * @deprecated Use createRunAsync() instead.
2373
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2374
+ */
2375
+ async createRun(_params) {
2376
+ throw new Error(
2377
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = agentBuilder.createRun();\n After: const run = await agentBuilder.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
2378
+ );
2379
+ }
2380
+ /**
2381
+ * Creates a new agent builder action run and returns the runId.
2382
+ * This calls `/api/agent-builder/:actionId/create-run`.
2383
+ */
2384
+ async createRunAsync(params) {
2385
+ const searchParams = new URLSearchParams();
2386
+ if (!!params?.runId) {
2387
+ searchParams.set("runId", params.runId);
2388
+ }
2389
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2390
+ return this.request(url, {
2391
+ method: "POST"
2392
+ });
2393
+ }
2394
+ /**
2395
+ * Starts agent builder action asynchronously and waits for completion.
2396
+ * This calls `/api/agent-builder/:actionId/start-async`.
2397
+ */
2398
+ async startAsync(params, runId) {
2399
+ const searchParams = new URLSearchParams();
2400
+ if (runId) {
2401
+ searchParams.set("runId", runId);
2402
+ }
2403
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2404
+ const { runtimeContext: _, ...actionParams } = params;
2405
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2406
+ const result = await this.request(url, {
2407
+ method: "POST",
2408
+ body: { ...actionParams, runtimeContext }
2409
+ });
2410
+ return this.transformWorkflowResult(result);
2411
+ }
2412
+ /**
2413
+ * Starts an existing agent builder action run.
2414
+ * This calls `/api/agent-builder/:actionId/start`.
2415
+ */
2416
+ async startActionRun(params, runId) {
2417
+ const searchParams = new URLSearchParams();
2418
+ searchParams.set("runId", runId);
2419
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2420
+ const { runtimeContext: _, ...actionParams } = params;
2421
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2422
+ return this.request(url, {
2423
+ method: "POST",
2424
+ body: { ...actionParams, runtimeContext }
2425
+ });
2426
+ }
2427
+ /**
2428
+ * Resumes a suspended agent builder action step.
2429
+ * This calls `/api/agent-builder/:actionId/resume`.
2430
+ */
2431
+ async resume(params, runId) {
2432
+ const searchParams = new URLSearchParams();
2433
+ searchParams.set("runId", runId);
2434
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2435
+ const { runtimeContext: _, ...resumeParams } = params;
2436
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2437
+ return this.request(url, {
2438
+ method: "POST",
2439
+ body: { ...resumeParams, runtimeContext }
2440
+ });
2441
+ }
2442
+ /**
2443
+ * Resumes a suspended agent builder action step asynchronously.
2444
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2445
+ */
2446
+ async resumeAsync(params, runId) {
2447
+ const searchParams = new URLSearchParams();
2448
+ searchParams.set("runId", runId);
2449
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2450
+ const { runtimeContext: _, ...resumeParams } = params;
2451
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2452
+ const result = await this.request(url, {
2453
+ method: "POST",
2454
+ body: { ...resumeParams, runtimeContext }
2455
+ });
2456
+ return this.transformWorkflowResult(result);
2457
+ }
2458
+ /**
2459
+ * Creates an async generator that processes a readable stream and yields action records
2460
+ * separated by the Record Separator character (\x1E)
2461
+ *
2462
+ * @param stream - The readable stream to process
2463
+ * @returns An async generator that yields parsed records
2464
+ */
2465
+ async *streamProcessor(stream) {
2466
+ const reader = stream.getReader();
2467
+ let doneReading = false;
2468
+ let buffer = "";
2469
+ try {
2470
+ while (!doneReading) {
2471
+ const { done, value } = await reader.read();
2472
+ doneReading = done;
2473
+ if (done && !value) continue;
2474
+ try {
2475
+ const decoded = value ? new TextDecoder().decode(value) : "";
2476
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2477
+ buffer = chunks.pop() || "";
2478
+ for (const chunk of chunks) {
2479
+ if (chunk) {
2480
+ if (typeof chunk === "string") {
2481
+ try {
2482
+ const parsedChunk = JSON.parse(chunk);
2483
+ yield parsedChunk;
2484
+ } catch {
2485
+ }
2486
+ }
2487
+ }
2488
+ }
2489
+ } catch {
2490
+ }
2491
+ }
2492
+ if (buffer) {
2493
+ try {
2494
+ yield JSON.parse(buffer);
2495
+ } catch {
2496
+ }
2497
+ }
2498
+ } finally {
2499
+ reader.cancel().catch(() => {
2500
+ });
2501
+ }
2502
+ }
2503
+ /**
2504
+ * Streams agent builder action progress in real-time.
2505
+ * This calls `/api/agent-builder/:actionId/stream`.
2506
+ */
2507
+ async stream(params, runId) {
2508
+ const searchParams = new URLSearchParams();
2509
+ if (runId) {
2510
+ searchParams.set("runId", runId);
2511
+ }
2512
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2513
+ const { runtimeContext: _, ...actionParams } = params;
2514
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2515
+ const response = await this.request(url, {
2516
+ method: "POST",
2517
+ body: { ...actionParams, runtimeContext },
2518
+ stream: true
2519
+ });
2520
+ if (!response.ok) {
2521
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2522
+ }
2523
+ if (!response.body) {
2524
+ throw new Error("Response body is null");
2525
+ }
2526
+ return response.body.pipeThrough(this.createRecordParserTransform());
2527
+ }
2528
+ /**
2529
+ * Streams agent builder action progress in real-time using VNext streaming.
2530
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2531
+ */
2532
+ async streamVNext(params, runId) {
2533
+ const searchParams = new URLSearchParams();
2534
+ if (runId) {
2535
+ searchParams.set("runId", runId);
2536
+ }
2537
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2538
+ const { runtimeContext: _, ...actionParams } = params;
2539
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2540
+ const response = await this.request(url, {
2541
+ method: "POST",
2542
+ body: { ...actionParams, runtimeContext },
2543
+ stream: true
2544
+ });
2545
+ if (!response.ok) {
2546
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2547
+ }
2548
+ if (!response.body) {
2549
+ throw new Error("Response body is null");
2550
+ }
2551
+ return response.body.pipeThrough(this.createRecordParserTransform());
2552
+ }
2553
+ /**
2554
+ * Watches an existing agent builder action run by runId.
2555
+ * This is used for hot reload recovery - it loads the existing run state
2556
+ * and streams any remaining progress.
2557
+ * This calls `/api/agent-builder/:actionId/watch`.
2558
+ */
2559
+ async watch({ runId, eventType }, onRecord) {
2560
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2561
+ const response = await this.request(url, {
2562
+ method: "GET",
2563
+ stream: true
2564
+ });
2565
+ if (!response.ok) {
2566
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2567
+ }
2568
+ if (!response.body) {
2569
+ throw new Error("Response body is null");
2570
+ }
2571
+ for await (const record of this.streamProcessor(response.body)) {
2572
+ if (typeof record === "string") {
2573
+ onRecord(JSON.parse(record));
2574
+ } else {
2575
+ onRecord(record);
2576
+ }
2577
+ }
2578
+ }
2579
+ /**
2580
+ * Observes an existing agent builder action run stream.
2581
+ * Replays cached execution from the beginning, then continues with live stream.
2582
+ * This is the recommended method for recovery after page refresh/hot reload.
2583
+ * This calls `/api/agent-builder/:actionId/observe` (which delegates to observeStreamVNext).
2584
+ */
2585
+ async observeStream(params) {
2586
+ const searchParams = new URLSearchParams();
2587
+ searchParams.set("runId", params.runId);
2588
+ const url = `/api/agent-builder/${this.actionId}/observe?${searchParams.toString()}`;
2589
+ const response = await this.request(url, {
2590
+ method: "POST",
2591
+ stream: true
2592
+ });
2593
+ if (!response.ok) {
2594
+ throw new Error(`Failed to observe agent builder action stream: ${response.statusText}`);
2595
+ }
2596
+ if (!response.body) {
2597
+ throw new Error("Response body is null");
2598
+ }
2599
+ return response.body.pipeThrough(this.createRecordParserTransform());
2600
+ }
2601
+ /**
2602
+ * Observes an existing agent builder action run stream using VNext streaming API.
2603
+ * Replays cached execution from the beginning, then continues with live stream.
2604
+ * This calls `/api/agent-builder/:actionId/observe-streamVNext`.
2605
+ */
2606
+ async observeStreamVNext(params) {
2607
+ const searchParams = new URLSearchParams();
2608
+ searchParams.set("runId", params.runId);
2609
+ const url = `/api/agent-builder/${this.actionId}/observe-streamVNext?${searchParams.toString()}`;
2610
+ const response = await this.request(url, {
2611
+ method: "POST",
2612
+ stream: true
2613
+ });
2614
+ if (!response.ok) {
2615
+ throw new Error(`Failed to observe agent builder action stream VNext: ${response.statusText}`);
2616
+ }
2617
+ if (!response.body) {
2618
+ throw new Error("Response body is null");
2619
+ }
2620
+ return response.body.pipeThrough(this.createRecordParserTransform());
2621
+ }
2622
+ /**
2623
+ * Observes an existing agent builder action run stream using legacy streaming API.
2624
+ * Replays cached execution from the beginning, then continues with live stream.
2625
+ * This calls `/api/agent-builder/:actionId/observe-stream-legacy`.
2626
+ */
2627
+ async observeStreamLegacy(params) {
2628
+ const searchParams = new URLSearchParams();
2629
+ searchParams.set("runId", params.runId);
2630
+ const url = `/api/agent-builder/${this.actionId}/observe-stream-legacy?${searchParams.toString()}`;
2631
+ const response = await this.request(url, {
2632
+ method: "POST",
2633
+ stream: true
2634
+ });
2635
+ if (!response.ok) {
2636
+ throw new Error(`Failed to observe agent builder action stream legacy: ${response.statusText}`);
2637
+ }
2638
+ if (!response.body) {
2639
+ throw new Error("Response body is null");
2640
+ }
2641
+ return response.body.pipeThrough(this.createRecordParserTransform());
2642
+ }
2643
+ /**
2644
+ * Resumes a suspended agent builder action and streams the results.
2645
+ * This calls `/api/agent-builder/:actionId/resume-stream`.
2646
+ */
2647
+ async resumeStream(params) {
2648
+ const searchParams = new URLSearchParams();
2649
+ searchParams.set("runId", params.runId);
2650
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2651
+ const { runId: _, runtimeContext: __, ...resumeParams } = params;
2652
+ const url = `/api/agent-builder/${this.actionId}/resume-stream?${searchParams.toString()}`;
2653
+ const response = await this.request(url, {
2654
+ method: "POST",
2655
+ body: { ...resumeParams, runtimeContext },
2656
+ stream: true
2657
+ });
2658
+ if (!response.ok) {
2659
+ throw new Error(`Failed to resume agent builder action stream: ${response.statusText}`);
2660
+ }
2661
+ if (!response.body) {
2662
+ throw new Error("Response body is null");
2663
+ }
2664
+ return response.body.pipeThrough(this.createRecordParserTransform());
2665
+ }
2666
+ /**
2667
+ * Gets a specific action run by its ID.
2668
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2669
+ */
2670
+ async runById(runId) {
2671
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2672
+ return this.request(url, {
2673
+ method: "GET"
2674
+ });
2675
+ }
2676
+ /**
2677
+ * Gets details about this agent builder action.
2678
+ * This calls `/api/agent-builder/:actionId`.
2679
+ */
2680
+ async details() {
2681
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2682
+ return result;
2683
+ }
2684
+ /**
2685
+ * Gets all runs for this agent builder action.
2686
+ * This calls `/api/agent-builder/:actionId/runs`.
2687
+ */
2688
+ async runs(params) {
2689
+ const searchParams = new URLSearchParams();
2690
+ if (params?.fromDate) {
2691
+ searchParams.set("fromDate", params.fromDate.toISOString());
2692
+ }
2693
+ if (params?.toDate) {
2694
+ searchParams.set("toDate", params.toDate.toISOString());
2695
+ }
2696
+ if (params?.limit !== void 0) {
2697
+ searchParams.set("limit", String(params.limit));
2698
+ }
2699
+ if (params?.offset !== void 0) {
2700
+ searchParams.set("offset", String(params.offset));
2701
+ }
2702
+ if (params?.resourceId) {
2703
+ searchParams.set("resourceId", params.resourceId);
2704
+ }
2705
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2706
+ return this.request(url, {
2707
+ method: "GET"
2708
+ });
2709
+ }
2710
+ /**
2711
+ * Gets the execution result of an agent builder action run.
2712
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2713
+ */
2714
+ async runExecutionResult(runId) {
2715
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2716
+ return this.request(url, {
2717
+ method: "GET"
2718
+ });
2719
+ }
2720
+ /**
2721
+ * Cancels an agent builder action run.
2722
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2723
+ */
2724
+ async cancelRun(runId) {
2725
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2726
+ return this.request(url, {
2727
+ method: "POST"
2728
+ });
2729
+ }
2730
+ /**
2731
+ * Sends an event to an agent builder action run.
2732
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2733
+ */
2734
+ async sendRunEvent(params) {
2735
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2736
+ return this.request(url, {
2737
+ method: "POST",
2738
+ body: { event: params.event, data: params.data }
2739
+ });
2740
+ }
2741
+ };
2742
+
2743
+ // src/resources/observability.ts
2744
+ var Observability = class extends BaseResource {
2745
+ constructor(options) {
2746
+ super(options);
2747
+ }
2748
+ /**
2749
+ * Retrieves a specific AI trace by ID
2750
+ * @param traceId - ID of the trace to retrieve
2751
+ * @returns Promise containing the AI trace with all its spans
2752
+ */
2753
+ getTrace(traceId) {
2754
+ return this.request(`/api/observability/traces/${traceId}`);
2755
+ }
2756
+ /**
2757
+ * Retrieves paginated list of AI traces with optional filtering
2758
+ * @param params - Parameters for pagination and filtering
2759
+ * @returns Promise containing paginated traces and pagination info
2760
+ */
2761
+ getTraces(params) {
2762
+ const { pagination, filters } = params;
2763
+ const { page, perPage, dateRange } = pagination || {};
2764
+ const { name, spanType, entityId, entityType } = filters || {};
2765
+ const searchParams = new URLSearchParams();
2766
+ if (page !== void 0) {
2767
+ searchParams.set("page", String(page));
2768
+ }
2769
+ if (perPage !== void 0) {
2770
+ searchParams.set("perPage", String(perPage));
2771
+ }
2772
+ if (name) {
2773
+ searchParams.set("name", name);
2774
+ }
2775
+ if (spanType !== void 0) {
2776
+ searchParams.set("spanType", String(spanType));
2777
+ }
2778
+ if (entityId && entityType) {
2779
+ searchParams.set("entityId", entityId);
2780
+ searchParams.set("entityType", entityType);
2781
+ }
2782
+ if (dateRange) {
2783
+ const dateRangeStr = JSON.stringify({
2784
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2785
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2786
+ });
2787
+ searchParams.set("dateRange", dateRangeStr);
2788
+ }
2789
+ const queryString = searchParams.toString();
2790
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2791
+ }
2792
+ /**
2793
+ * Retrieves scores by trace ID and span ID
2794
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2795
+ * @returns Promise containing scores and pagination info
2796
+ */
2797
+ getScoresBySpan(params) {
2798
+ const { traceId, spanId, page, perPage } = params;
2799
+ const searchParams = new URLSearchParams();
2800
+ if (page !== void 0) {
2801
+ searchParams.set("page", String(page));
2802
+ }
2803
+ if (perPage !== void 0) {
2804
+ searchParams.set("perPage", String(perPage));
2805
+ }
2806
+ const queryString = searchParams.toString();
2807
+ return this.request(
2808
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2809
+ );
2810
+ }
2811
+ score(params) {
2812
+ return this.request(`/api/observability/traces/score`, {
2813
+ method: "POST",
2814
+ body: { ...params }
2815
+ });
2816
+ }
2817
+ };
2818
+
2819
+ // src/resources/network-memory-thread.ts
2820
+ var NetworkMemoryThread = class extends BaseResource {
2821
+ constructor(options, threadId, networkId) {
2822
+ super(options);
2823
+ this.threadId = threadId;
2824
+ this.networkId = networkId;
2825
+ }
2826
+ /**
2827
+ * Retrieves the memory thread details
2828
+ * @returns Promise containing thread details including title and metadata
2829
+ */
2830
+ get() {
2831
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
2832
+ }
2833
+ /**
2834
+ * Updates the memory thread properties
2835
+ * @param params - Update parameters including title and metadata
2836
+ * @returns Promise containing updated thread details
2837
+ */
2838
+ update(params) {
2839
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2840
+ method: "PATCH",
2841
+ body: params
2842
+ });
2843
+ }
2844
+ /**
2845
+ * Deletes the memory thread
2846
+ * @returns Promise containing deletion result
2847
+ */
2848
+ delete() {
2849
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2850
+ method: "DELETE"
2851
+ });
2852
+ }
2853
+ /**
2854
+ * Retrieves messages associated with the thread
2855
+ * @param params - Optional parameters including limit for number of messages to retrieve
2856
+ * @returns Promise containing thread messages and UI messages
2857
+ */
2858
+ getMessages(params) {
2859
+ const query = new URLSearchParams({
2860
+ networkId: this.networkId,
2861
+ ...params?.limit ? { limit: params.limit.toString() } : {}
2862
+ });
2863
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
2864
+ }
2865
+ /**
2866
+ * Deletes one or more messages from the thread
2867
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2868
+ * message object with id property, or array of message objects
2869
+ * @returns Promise containing deletion result
2870
+ */
2871
+ deleteMessages(messageIds) {
2872
+ const query = new URLSearchParams({
2873
+ networkId: this.networkId
2874
+ });
2875
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
2876
+ method: "POST",
2877
+ body: { messageIds }
2878
+ });
2879
+ }
2880
+ };
2881
+
2882
+ // src/client.ts
2883
+ var MastraClient = class extends BaseResource {
2884
+ observability;
2885
+ constructor(options) {
2886
+ super(options);
2887
+ this.observability = new Observability(options);
2888
+ }
2889
+ /**
2890
+ * Retrieves all available agents
2891
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2892
+ * @returns Promise containing map of agent IDs to agent details
2893
+ */
2894
+ getAgents(runtimeContext) {
2895
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2896
+ const searchParams = new URLSearchParams();
2897
+ if (runtimeContextParam) {
2898
+ searchParams.set("runtimeContext", runtimeContextParam);
2899
+ }
2900
+ const queryString = searchParams.toString();
2901
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
2902
+ }
2903
+ getAgentsModelProviders() {
2904
+ return this.request(`/api/agents/providers`);
2905
+ }
2906
+ /**
2907
+ * Gets an agent instance by ID
2908
+ * @param agentId - ID of the agent to retrieve
2909
+ * @returns Agent instance
2910
+ */
2911
+ getAgent(agentId) {
2912
+ return new Agent(this.options, agentId);
2913
+ }
2914
+ /**
2915
+ * Retrieves memory threads for a resource
2916
+ * @param params - Parameters containing the resource ID and optional runtime context
2917
+ * @returns Promise containing array of memory threads
2918
+ */
2919
+ getMemoryThreads(params) {
2920
+ return this.request(
2921
+ `/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`
2922
+ );
2923
+ }
2924
+ /**
2925
+ * Retrieves memory config for a resource
2926
+ * @param params - Parameters containing the resource ID and optional runtime context
2927
+ * @returns Promise containing memory configuration
2928
+ */
2929
+ getMemoryConfig(params) {
2930
+ return this.request(
2931
+ `/api/memory/config?agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`
2932
+ );
2933
+ }
2934
+ /**
2935
+ * Creates a new memory thread
2936
+ * @param params - Parameters for creating the memory thread including optional runtime context
2937
+ * @returns Promise containing the created memory thread
2938
+ */
2939
+ createMemoryThread(params) {
2940
+ return this.request(
2941
+ `/api/memory/threads?agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`,
2942
+ { method: "POST", body: params }
2943
+ );
2944
+ }
2945
+ /**
2946
+ * Gets a memory thread instance by ID
2947
+ * @param threadId - ID of the memory thread to retrieve
2948
+ * @returns MemoryThread instance
2949
+ */
2950
+ getMemoryThread(threadId, agentId) {
2951
+ return new MemoryThread(this.options, threadId, agentId);
2952
+ }
2953
+ getThreadMessages(threadId, opts = {}) {
2954
+ let url = "";
2955
+ if (opts.agentId) {
2956
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2957
+ } else if (opts.networkId) {
2958
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2959
+ }
2960
+ return this.request(url);
2961
+ }
2962
+ deleteThread(threadId, opts = {}) {
2963
+ let url = "";
2964
+ if (opts.agentId) {
2965
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2966
+ } else if (opts.networkId) {
2967
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2968
+ }
2969
+ return this.request(url, { method: "DELETE" });
2970
+ }
2971
+ /**
2972
+ * Saves messages to memory
2973
+ * @param params - Parameters containing messages to save and optional runtime context
2974
+ * @returns Promise containing the saved messages
2975
+ */
2976
+ saveMessageToMemory(params) {
2977
+ return this.request(
2978
+ `/api/memory/save-messages?agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`,
2979
+ {
2980
+ method: "POST",
2981
+ body: params
2982
+ }
2983
+ );
2984
+ }
2985
+ /**
2986
+ * Gets the status of the memory system
2987
+ * @param agentId - The agent ID
2988
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2989
+ * @returns Promise containing memory system status
2990
+ */
2991
+ getMemoryStatus(agentId, runtimeContext) {
2992
+ return this.request(`/api/memory/status?agentId=${agentId}${runtimeContextQueryString(runtimeContext, "&")}`);
2993
+ }
2994
+ /**
2995
+ * Retrieves memory threads for a resource
2996
+ * @param params - Parameters containing the resource ID
2997
+ * @returns Promise containing array of memory threads
2998
+ */
2999
+ getNetworkMemoryThreads(params) {
3000
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
3001
+ }
3002
+ /**
3003
+ * Creates a new memory thread
3004
+ * @param params - Parameters for creating the memory thread
3005
+ * @returns Promise containing the created memory thread
3006
+ */
3007
+ createNetworkMemoryThread(params) {
3008
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
3009
+ }
3010
+ /**
3011
+ * Gets a memory thread instance by ID
3012
+ * @param threadId - ID of the memory thread to retrieve
3013
+ * @returns MemoryThread instance
3014
+ */
3015
+ getNetworkMemoryThread(threadId, networkId) {
3016
+ return new NetworkMemoryThread(this.options, threadId, networkId);
3017
+ }
3018
+ /**
3019
+ * Saves messages to memory
3020
+ * @param params - Parameters containing messages to save
3021
+ * @returns Promise containing the saved messages
3022
+ */
3023
+ saveNetworkMessageToMemory(params) {
3024
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
3025
+ method: "POST",
3026
+ body: params
3027
+ });
3028
+ }
3029
+ /**
3030
+ * Gets the status of the memory system
3031
+ * @returns Promise containing memory system status
3032
+ */
3033
+ getNetworkMemoryStatus(networkId) {
3034
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
3035
+ }
3036
+ /**
3037
+ * Retrieves all available tools
3038
+ * @param runtimeContext - Optional runtime context to pass as query parameter
3039
+ * @returns Promise containing map of tool IDs to tool details
3040
+ */
3041
+ getTools(runtimeContext) {
3042
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
3043
+ const searchParams = new URLSearchParams();
3044
+ if (runtimeContextParam) {
3045
+ searchParams.set("runtimeContext", runtimeContextParam);
3046
+ }
3047
+ const queryString = searchParams.toString();
3048
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
621
3049
  }
622
3050
  /**
623
3051
  * Gets a tool instance by ID
@@ -629,10 +3057,17 @@ var MastraClient = class extends BaseResource {
629
3057
  }
630
3058
  /**
631
3059
  * Retrieves all available workflows
3060
+ * @param runtimeContext - Optional runtime context to pass as query parameter
632
3061
  * @returns Promise containing map of workflow IDs to workflow details
633
3062
  */
634
- getWorkflows() {
635
- return this.request("/api/workflows");
3063
+ getWorkflows(runtimeContext) {
3064
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
3065
+ const searchParams = new URLSearchParams();
3066
+ if (runtimeContextParam) {
3067
+ searchParams.set("runtimeContext", runtimeContextParam);
3068
+ }
3069
+ const queryString = searchParams.toString();
3070
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
636
3071
  }
637
3072
  /**
638
3073
  * Gets a workflow instance by ID
@@ -642,6 +3077,20 @@ var MastraClient = class extends BaseResource {
642
3077
  getWorkflow(workflowId) {
643
3078
  return new Workflow(this.options, workflowId);
644
3079
  }
3080
+ /**
3081
+ * Gets all available agent builder actions
3082
+ * @returns Promise containing map of action IDs to action details
3083
+ */
3084
+ getAgentBuilderActions() {
3085
+ return this.request("/api/agent-builder/");
3086
+ }
3087
+ /**
3088
+ * Gets an agent builder instance for executing agent-builder workflows
3089
+ * @returns AgentBuilder instance
3090
+ */
3091
+ getAgentBuilderAction(actionId) {
3092
+ return new AgentBuilder(this.options, actionId);
3093
+ }
645
3094
  /**
646
3095
  * Gets a vector instance by name
647
3096
  * @param vectorName - Name of the vector to retrieve
@@ -656,7 +3105,41 @@ var MastraClient = class extends BaseResource {
656
3105
  * @returns Promise containing array of log messages
657
3106
  */
658
3107
  getLogs(params) {
659
- return this.request(`/api/logs?transportId=${params.transportId}`);
3108
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
3109
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
3110
+ const searchParams = new URLSearchParams();
3111
+ if (transportId) {
3112
+ searchParams.set("transportId", transportId);
3113
+ }
3114
+ if (fromDate) {
3115
+ searchParams.set("fromDate", fromDate.toISOString());
3116
+ }
3117
+ if (toDate) {
3118
+ searchParams.set("toDate", toDate.toISOString());
3119
+ }
3120
+ if (logLevel) {
3121
+ searchParams.set("logLevel", logLevel);
3122
+ }
3123
+ if (page) {
3124
+ searchParams.set("page", String(page));
3125
+ }
3126
+ if (perPage) {
3127
+ searchParams.set("perPage", String(perPage));
3128
+ }
3129
+ if (_filters) {
3130
+ if (Array.isArray(_filters)) {
3131
+ for (const filter of _filters) {
3132
+ searchParams.append("filters", filter);
3133
+ }
3134
+ } else {
3135
+ searchParams.set("filters", _filters);
3136
+ }
3137
+ }
3138
+ if (searchParams.size) {
3139
+ return this.request(`/api/logs?${searchParams}`);
3140
+ } else {
3141
+ return this.request(`/api/logs`);
3142
+ }
660
3143
  }
661
3144
  /**
662
3145
  * Gets logs for a specific run
@@ -664,7 +3147,44 @@ var MastraClient = class extends BaseResource {
664
3147
  * @returns Promise containing array of log messages
665
3148
  */
666
3149
  getLogForRun(params) {
667
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
3150
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
3151
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
3152
+ const searchParams = new URLSearchParams();
3153
+ if (runId) {
3154
+ searchParams.set("runId", runId);
3155
+ }
3156
+ if (transportId) {
3157
+ searchParams.set("transportId", transportId);
3158
+ }
3159
+ if (fromDate) {
3160
+ searchParams.set("fromDate", fromDate.toISOString());
3161
+ }
3162
+ if (toDate) {
3163
+ searchParams.set("toDate", toDate.toISOString());
3164
+ }
3165
+ if (logLevel) {
3166
+ searchParams.set("logLevel", logLevel);
3167
+ }
3168
+ if (page) {
3169
+ searchParams.set("page", String(page));
3170
+ }
3171
+ if (perPage) {
3172
+ searchParams.set("perPage", String(perPage));
3173
+ }
3174
+ if (_filters) {
3175
+ if (Array.isArray(_filters)) {
3176
+ for (const filter of _filters) {
3177
+ searchParams.append("filters", filter);
3178
+ }
3179
+ } else {
3180
+ searchParams.set("filters", _filters);
3181
+ }
3182
+ }
3183
+ if (searchParams.size) {
3184
+ return this.request(`/api/logs/${runId}?${searchParams}`);
3185
+ } else {
3186
+ return this.request(`/api/logs/${runId}`);
3187
+ }
668
3188
  }
669
3189
  /**
670
3190
  * List of all log transports
@@ -674,56 +3194,246 @@ var MastraClient = class extends BaseResource {
674
3194
  return this.request("/api/logs/transports");
675
3195
  }
676
3196
  /**
677
- * List of all traces (paged)
678
- * @param params - Parameters for filtering traces
679
- * @returns Promise containing telemetry data
3197
+ * Retrieves a list of available MCP servers.
3198
+ * @param params - Optional parameters for pagination (limit, offset).
3199
+ * @returns Promise containing the list of MCP servers and pagination info.
680
3200
  */
681
- getTelemetry(params) {
682
- const { name, scope, page, perPage, attribute } = params || {};
683
- const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
3201
+ getMcpServers(params) {
684
3202
  const searchParams = new URLSearchParams();
685
- if (name) {
686
- searchParams.set("name", name);
3203
+ if (params?.limit !== void 0) {
3204
+ searchParams.set("limit", String(params.limit));
687
3205
  }
688
- if (scope) {
689
- searchParams.set("scope", scope);
3206
+ if (params?.offset !== void 0) {
3207
+ searchParams.set("offset", String(params.offset));
690
3208
  }
691
- if (page) {
692
- searchParams.set("page", String(page));
3209
+ const queryString = searchParams.toString();
3210
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
3211
+ }
3212
+ /**
3213
+ * Retrieves detailed information for a specific MCP server.
3214
+ * @param serverId - The ID of the MCP server to retrieve.
3215
+ * @param params - Optional parameters, e.g., specific version.
3216
+ * @returns Promise containing the detailed MCP server information.
3217
+ */
3218
+ getMcpServerDetails(serverId, params) {
3219
+ const searchParams = new URLSearchParams();
3220
+ if (params?.version) {
3221
+ searchParams.set("version", params.version);
693
3222
  }
694
- if (perPage) {
695
- searchParams.set("perPage", String(perPage));
3223
+ const queryString = searchParams.toString();
3224
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
3225
+ }
3226
+ /**
3227
+ * Retrieves a list of tools for a specific MCP server.
3228
+ * @param serverId - The ID of the MCP server.
3229
+ * @returns Promise containing the list of tools.
3230
+ */
3231
+ getMcpServerTools(serverId) {
3232
+ return this.request(`/api/mcp/${serverId}/tools`);
3233
+ }
3234
+ /**
3235
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
3236
+ * This instance can then be used to fetch details or execute the tool.
3237
+ * @param serverId - The ID of the MCP server.
3238
+ * @param toolId - The ID of the tool.
3239
+ * @returns MCPTool instance.
3240
+ */
3241
+ getMcpServerTool(serverId, toolId) {
3242
+ return new MCPTool(this.options, serverId, toolId);
3243
+ }
3244
+ /**
3245
+ * Gets an A2A client for interacting with an agent via the A2A protocol
3246
+ * @param agentId - ID of the agent to interact with
3247
+ * @returns A2A client instance
3248
+ */
3249
+ getA2A(agentId) {
3250
+ return new A2A(this.options, agentId);
3251
+ }
3252
+ /**
3253
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3254
+ * @param agentId - ID of the agent.
3255
+ * @param threadId - ID of the thread.
3256
+ * @param resourceId - Optional ID of the resource.
3257
+ * @returns Working memory for the specified thread or resource.
3258
+ */
3259
+ getWorkingMemory({
3260
+ agentId,
3261
+ threadId,
3262
+ resourceId,
3263
+ runtimeContext
3264
+ }) {
3265
+ return this.request(
3266
+ `/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}${runtimeContextQueryString(runtimeContext, "&")}`
3267
+ );
3268
+ }
3269
+ searchMemory({
3270
+ agentId,
3271
+ resourceId,
3272
+ threadId,
3273
+ searchQuery,
3274
+ memoryConfig,
3275
+ runtimeContext
3276
+ }) {
3277
+ const params = new URLSearchParams({
3278
+ searchQuery,
3279
+ resourceId,
3280
+ agentId
3281
+ });
3282
+ if (threadId) {
3283
+ params.append("threadId", threadId);
696
3284
  }
697
- if (_attribute) {
698
- if (Array.isArray(_attribute)) {
699
- for (const attr of _attribute) {
700
- searchParams.append("attribute", attr);
3285
+ if (memoryConfig) {
3286
+ params.append("memoryConfig", JSON.stringify(memoryConfig));
3287
+ }
3288
+ return this.request(`/api/memory/search?${params}${runtimeContextQueryString(runtimeContext, "&")}`);
3289
+ }
3290
+ /**
3291
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3292
+ * @param agentId - ID of the agent.
3293
+ * @param threadId - ID of the thread.
3294
+ * @param workingMemory - The new working memory content.
3295
+ * @param resourceId - Optional ID of the resource.
3296
+ */
3297
+ updateWorkingMemory({
3298
+ agentId,
3299
+ threadId,
3300
+ workingMemory,
3301
+ resourceId,
3302
+ runtimeContext
3303
+ }) {
3304
+ return this.request(
3305
+ `/api/memory/threads/${threadId}/working-memory?agentId=${agentId}${runtimeContextQueryString(runtimeContext, "&")}`,
3306
+ {
3307
+ method: "POST",
3308
+ body: {
3309
+ workingMemory,
3310
+ resourceId
701
3311
  }
702
- } else {
703
- searchParams.set("attribute", _attribute);
704
3312
  }
3313
+ );
3314
+ }
3315
+ /**
3316
+ * Retrieves all available scorers
3317
+ * @returns Promise containing list of available scorers
3318
+ */
3319
+ getScorers() {
3320
+ return this.request("/api/scores/scorers");
3321
+ }
3322
+ /**
3323
+ * Retrieves a scorer by ID
3324
+ * @param scorerId - ID of the scorer to retrieve
3325
+ * @returns Promise containing the scorer
3326
+ */
3327
+ getScorer(scorerId) {
3328
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3329
+ }
3330
+ getScoresByScorerId(params) {
3331
+ const { page, perPage, scorerId, entityId, entityType } = params;
3332
+ const searchParams = new URLSearchParams();
3333
+ if (entityId) {
3334
+ searchParams.set("entityId", entityId);
705
3335
  }
706
- if (searchParams.size) {
707
- return this.request(`/api/telemetry?${searchParams}`);
708
- } else {
709
- return this.request(`/api/telemetry`);
3336
+ if (entityType) {
3337
+ searchParams.set("entityType", entityType);
3338
+ }
3339
+ if (page !== void 0) {
3340
+ searchParams.set("page", String(page));
3341
+ }
3342
+ if (perPage !== void 0) {
3343
+ searchParams.set("perPage", String(perPage));
3344
+ }
3345
+ const queryString = searchParams.toString();
3346
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3347
+ }
3348
+ /**
3349
+ * Retrieves scores by run ID
3350
+ * @param params - Parameters containing run ID and pagination options
3351
+ * @returns Promise containing scores and pagination info
3352
+ */
3353
+ getScoresByRunId(params) {
3354
+ const { runId, page, perPage } = params;
3355
+ const searchParams = new URLSearchParams();
3356
+ if (page !== void 0) {
3357
+ searchParams.set("page", String(page));
3358
+ }
3359
+ if (perPage !== void 0) {
3360
+ searchParams.set("perPage", String(perPage));
3361
+ }
3362
+ const queryString = searchParams.toString();
3363
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
3364
+ }
3365
+ /**
3366
+ * Retrieves scores by entity ID and type
3367
+ * @param params - Parameters containing entity ID, type, and pagination options
3368
+ * @returns Promise containing scores and pagination info
3369
+ */
3370
+ getScoresByEntityId(params) {
3371
+ const { entityId, entityType, page, perPage } = params;
3372
+ const searchParams = new URLSearchParams();
3373
+ if (page !== void 0) {
3374
+ searchParams.set("page", String(page));
710
3375
  }
3376
+ if (perPage !== void 0) {
3377
+ searchParams.set("perPage", String(perPage));
3378
+ }
3379
+ const queryString = searchParams.toString();
3380
+ return this.request(
3381
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3382
+ );
711
3383
  }
712
3384
  /**
713
- * Retrieves all available networks
714
- * @returns Promise containing map of network IDs to network details
3385
+ * Saves a score
3386
+ * @param params - Parameters containing the score data to save
3387
+ * @returns Promise containing the saved score
715
3388
  */
716
- getNetworks() {
717
- return this.request("/api/networks");
3389
+ saveScore(params) {
3390
+ return this.request("/api/scores", {
3391
+ method: "POST",
3392
+ body: params
3393
+ });
718
3394
  }
719
3395
  /**
720
- * Gets a network instance by ID
721
- * @param networkId - ID of the network to retrieve
722
- * @returns Network instance
3396
+ * Retrieves model providers with available keys
3397
+ * @returns Promise containing model providers with available keys
723
3398
  */
724
- getNetwork(networkId) {
725
- return new Network(this.options, networkId);
3399
+ getModelProviders() {
3400
+ return this.request(`/api/model-providers`);
3401
+ }
3402
+ getAITrace(traceId) {
3403
+ return this.observability.getTrace(traceId);
3404
+ }
3405
+ getAITraces(params) {
3406
+ return this.observability.getTraces(params);
3407
+ }
3408
+ getScoresBySpan(params) {
3409
+ return this.observability.getScoresBySpan(params);
3410
+ }
3411
+ score(params) {
3412
+ return this.observability.score(params);
3413
+ }
3414
+ };
3415
+
3416
+ // src/tools.ts
3417
+ var ClientTool = class {
3418
+ id;
3419
+ description;
3420
+ inputSchema;
3421
+ outputSchema;
3422
+ execute;
3423
+ constructor(opts) {
3424
+ this.id = opts.id;
3425
+ this.description = opts.description;
3426
+ this.inputSchema = opts.inputSchema;
3427
+ this.outputSchema = opts.outputSchema;
3428
+ this.execute = opts.execute;
726
3429
  }
727
3430
  };
3431
+ function createTool(opts) {
3432
+ return new ClientTool(opts);
3433
+ }
728
3434
 
3435
+ exports.ClientTool = ClientTool;
729
3436
  exports.MastraClient = MastraClient;
3437
+ exports.createTool = createTool;
3438
+ //# sourceMappingURL=index.cjs.map
3439
+ //# sourceMappingURL=index.cjs.map