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