@mastra/client-js 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-remove-unused-model-providers-api-20251030210744

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 (66) hide show
  1. package/CHANGELOG.md +2411 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +14 -15
  4. package/dist/client.d.ts +253 -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 +2810 -382
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +5 -691
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +2809 -387
  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 +199 -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/observability.d.ts +35 -0
  29. package/dist/resources/observability.d.ts.map +1 -0
  30. package/dist/resources/tool.d.ts +24 -0
  31. package/dist/resources/tool.d.ts.map +1 -0
  32. package/dist/resources/vector.d.ts +51 -0
  33. package/dist/resources/vector.d.ts.map +1 -0
  34. package/dist/resources/workflow.d.ts +269 -0
  35. package/dist/resources/workflow.d.ts.map +1 -0
  36. package/dist/tools.d.ts +22 -0
  37. package/dist/tools.d.ts.map +1 -0
  38. package/dist/types.d.ts +460 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/utils/index.d.ts +11 -0
  41. package/dist/utils/index.d.ts.map +1 -0
  42. package/dist/utils/process-client-tools.d.ts +3 -0
  43. package/dist/utils/process-client-tools.d.ts.map +1 -0
  44. package/dist/utils/process-mastra-stream.d.ts +11 -0
  45. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  46. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  47. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  48. package/package.json +39 -19
  49. package/dist/index.d.cts +0 -691
  50. package/eslint.config.js +0 -6
  51. package/src/client.ts +0 -232
  52. package/src/example.ts +0 -65
  53. package/src/index.test.ts +0 -710
  54. package/src/index.ts +0 -2
  55. package/src/resources/agent.ts +0 -205
  56. package/src/resources/base.ts +0 -70
  57. package/src/resources/index.ts +0 -8
  58. package/src/resources/memory-thread.ts +0 -53
  59. package/src/resources/network.ts +0 -92
  60. package/src/resources/tool.ts +0 -32
  61. package/src/resources/vector.ts +0 -83
  62. package/src/resources/vnext-workflow.ts +0 -225
  63. package/src/resources/workflow.ts +0 -215
  64. package/src/types.ts +0 -237
  65. package/tsconfig.json +0 -5
  66. 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 { RequestContext } from '@mastra/core/request-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 parseClientRequestContext(requestContext) {
11
+ if (requestContext) {
12
+ if (requestContext instanceof RequestContext) {
13
+ return Object.fromEntries(requestContext.entries());
14
+ }
15
+ return requestContext;
16
+ }
17
+ return void 0;
18
+ }
19
+ function base64RequestContext(requestContext) {
20
+ if (requestContext) {
21
+ return btoa(JSON.stringify(requestContext));
22
+ }
23
+ return void 0;
24
+ }
25
+ function requestContextQueryString(requestContext, delimiter = "?") {
26
+ const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
27
+ if (!requestContextParam) return "";
28
+ const searchParams = new URLSearchParams();
29
+ searchParams.set("requestContext", requestContextParam);
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
+ requestContext,
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
+ requestContext,
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 requestContext - Optional request context to pass as query parameter
294
+ * @param requestContext - Optional request 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(requestContext) {
298
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${requestContextQueryString(requestContext)}`);
299
+ }
300
+ /**
301
+ * Get the listener configuration for the agent's voice provider
302
+ * @param requestContext - Optional request context to pass as query parameter
303
+ * @param requestContext - Optional request context to pass as query parameter
304
+ * @returns Promise containing a check if the agent has listening capabilities
305
+ */
306
+ getListener(requestContext) {
307
+ return this.request(`/api/agents/${this.agentId}/voice/listener${requestContextQueryString(requestContext)}`);
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 requestContext - Optional request 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(requestContext) {
323
+ return this.request(`/api/agents/${this.agentId}${requestContextQueryString(requestContext)}`);
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
+ requestContext: parseClientRequestContext(params.requestContext),
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, requestContext } = 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
+ requestContext,
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
+ requestContext: parseClientRequestContext(params.requestContext),
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, requestContext } = 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
+ requestContext,
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
+ requestContext: parseClientRequestContext(params.requestContext),
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
+ });
721
+ };
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
154
767
  };
155
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
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,404 @@ 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
+ requestContext: processedParams.requestContext,
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
+ requestContext: parseClientRequestContext(params.requestContext),
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
+ requestContext: processedParams.requestContext,
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 requestContext - Optional request 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, requestContext) {
1330
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${requestContextQueryString(requestContext)}`);
178
1331
  }
179
1332
  /**
180
- * Retrieves evaluation results for the agent
181
- * @returns Promise containing agent evaluations
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
182
1337
  */
183
- evals() {
184
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1338
+ executeTool(toolId, params) {
1339
+ const body = {
1340
+ data: params.data,
1341
+ requestContext: parseClientRequestContext(params.requestContext)
1342
+ };
1343
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1344
+ method: "POST",
1345
+ body
1346
+ });
185
1347
  }
186
1348
  /**
187
- * Retrieves live evaluation results for the agent
188
- * @returns Promise containing live agent evaluations
1349
+ * Updates the model for the agent
1350
+ * @param params - Parameters for updating the model
1351
+ * @returns Promise containing the updated model
189
1352
  */
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;
1353
+ updateModel(params) {
1354
+ return this.request(`/api/agents/${this.agentId}/model`, {
1355
+ method: "POST",
1356
+ body: params
1357
+ });
198
1358
  }
199
1359
  /**
200
- * Retrieves details about the network
201
- * @returns Promise containing network details
1360
+ * Resets the agent's model to the original model that was set during construction
1361
+ * @returns Promise containing a success message
202
1362
  */
203
- details() {
204
- return this.request(`/api/networks/${this.networkId}`);
1363
+ resetModel() {
1364
+ return this.request(`/api/agents/${this.agentId}/model/reset`, {
1365
+ method: "POST"
1366
+ });
205
1367
  }
206
1368
  /**
207
- * Generates a response from the agent
208
- * @param params - Generation parameters including prompt
209
- * @returns Promise containing the generated response
1369
+ * Updates the model for the agent in the model list
1370
+ * @param params - Parameters for updating the model
1371
+ * @returns Promise containing the updated model
210
1372
  */
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`, {
1373
+ updateModelInModelList({ modelConfigId, ...params }) {
1374
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
218
1375
  method: "POST",
219
- body: processedParams
1376
+ body: params
220
1377
  });
221
1378
  }
222
1379
  /**
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
1380
+ * Reorders the models for the agent
1381
+ * @param params - Parameters for reordering the model list
1382
+ * @returns Promise containing the updated model list
226
1383
  */
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`, {
1384
+ reorderModelList(params) {
1385
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
234
1386
  method: "POST",
235
- body: processedParams,
236
- stream: true
1387
+ body: params
237
1388
  });
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;
1389
+ }
1390
+ async generateVNext(_messagesOrParams, _options) {
1391
+ throw new Error("generateVNext has been renamed to generate. Please use generate instead.");
1392
+ }
1393
+ async streamVNext(_messagesOrParams, _options) {
1394
+ throw new Error("streamVNext has been renamed to stream. Please use stream instead.");
248
1395
  }
249
1396
  };
250
1397
 
@@ -257,39 +1404,93 @@ var MemoryThread = class extends BaseResource {
257
1404
  }
258
1405
  /**
259
1406
  * Retrieves the memory thread details
1407
+ * @param requestContext - Optional request context to pass as query parameter
260
1408
  * @returns Promise containing thread details including title and metadata
261
1409
  */
262
- get() {
263
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`);
1410
+ get(requestContext) {
1411
+ return this.request(
1412
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${requestContextQueryString(requestContext, "&")}`
1413
+ );
264
1414
  }
265
1415
  /**
266
1416
  * Updates the memory thread properties
267
- * @param params - Update parameters including title and metadata
1417
+ * @param params - Update parameters including title, metadata, and optional request context
268
1418
  * @returns Promise containing updated thread details
269
1419
  */
270
1420
  update(params) {
271
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
272
- method: "PATCH",
273
- body: params
274
- });
1421
+ return this.request(
1422
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${requestContextQueryString(params.requestContext, "&")}`,
1423
+ {
1424
+ method: "PATCH",
1425
+ body: params
1426
+ }
1427
+ );
275
1428
  }
276
1429
  /**
277
1430
  * Deletes the memory thread
1431
+ * @param requestContext - Optional request context to pass as query parameter
278
1432
  * @returns Promise containing deletion result
279
1433
  */
280
- delete() {
281
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
282
- method: "DELETE"
283
- });
1434
+ delete(requestContext) {
1435
+ return this.request(
1436
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${requestContextQueryString(requestContext, "&")}`,
1437
+ {
1438
+ method: "DELETE"
1439
+ }
1440
+ );
284
1441
  }
285
1442
  /**
286
1443
  * Retrieves messages associated with the thread
1444
+ * @param params - Optional parameters including limit for number of messages to retrieve and request context
287
1445
  * @returns Promise containing thread messages and UI messages
288
1446
  */
289
- getMessages() {
290
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
1447
+ getMessages(params) {
1448
+ const query = new URLSearchParams({
1449
+ agentId: this.agentId,
1450
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1451
+ });
1452
+ return this.request(
1453
+ `/api/memory/threads/${this.threadId}/messages?${query.toString()}${requestContextQueryString(params?.requestContext, "&")}`
1454
+ );
291
1455
  }
292
- };
1456
+ /**
1457
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1458
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, message inclusion options, and request context
1459
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1460
+ */
1461
+ getMessagesPaginated({
1462
+ selectBy,
1463
+ requestContext,
1464
+ ...rest
1465
+ }) {
1466
+ const query = new URLSearchParams({
1467
+ ...rest,
1468
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1469
+ });
1470
+ return this.request(
1471
+ `/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}${requestContextQueryString(requestContext, "&")}`
1472
+ );
1473
+ }
1474
+ /**
1475
+ * Deletes one or more messages from the thread
1476
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1477
+ * message object with id property, or array of message objects
1478
+ * @param requestContext - Optional request context to pass as query parameter
1479
+ * @returns Promise containing deletion result
1480
+ */
1481
+ deleteMessages(messageIds, requestContext) {
1482
+ const query = new URLSearchParams({
1483
+ agentId: this.agentId
1484
+ });
1485
+ return this.request(
1486
+ `/api/memory/messages/delete?${query.toString()}${requestContextQueryString(requestContext, "&")}`,
1487
+ {
1488
+ method: "POST",
1489
+ body: { messageIds }
1490
+ }
1491
+ );
1492
+ }
1493
+ };
293
1494
 
294
1495
  // src/resources/vector.ts
295
1496
  var Vector = class extends BaseResource {
@@ -300,10 +1501,13 @@ var Vector = class extends BaseResource {
300
1501
  /**
301
1502
  * Retrieves details about a specific vector index
302
1503
  * @param indexName - Name of the index to get details for
1504
+ * @param requestContext - Optional request context to pass as query parameter
303
1505
  * @returns Promise containing vector index details
304
1506
  */
305
- details(indexName) {
306
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1507
+ details(indexName, requestContext) {
1508
+ return this.request(
1509
+ `/api/vector/${this.vectorName}/indexes/${indexName}${requestContextQueryString(requestContext)}`
1510
+ );
307
1511
  }
308
1512
  /**
309
1513
  * Deletes a vector index
@@ -317,10 +1521,11 @@ var Vector = class extends BaseResource {
317
1521
  }
318
1522
  /**
319
1523
  * Retrieves a list of all available indexes
1524
+ * @param requestContext - Optional request context to pass as query parameter
320
1525
  * @returns Promise containing array of index names
321
1526
  */
322
- getIndexes() {
323
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1527
+ getIndexes(requestContext) {
1528
+ return this.request(`/api/vector/${this.vectorName}/indexes${requestContextQueryString(requestContext)}`);
324
1529
  }
325
1530
  /**
326
1531
  * Creates a new vector index
@@ -357,107 +1562,50 @@ var Vector = class extends BaseResource {
357
1562
  }
358
1563
  };
359
1564
 
360
- // src/resources/workflow.ts
361
- var RECORD_SEPARATOR = "";
362
- var Workflow = class extends BaseResource {
363
- constructor(options, workflowId) {
1565
+ // src/resources/tool.ts
1566
+ var Tool = class extends BaseResource {
1567
+ constructor(options, toolId) {
364
1568
  super(options);
365
- this.workflowId = workflowId;
1569
+ this.toolId = toolId;
366
1570
  }
367
1571
  /**
368
- * Retrieves details about the workflow
369
- * @returns Promise containing workflow details including steps and graphs
1572
+ * Retrieves details about the tool
1573
+ * @param requestContext - Optional request context to pass as query parameter
1574
+ * @returns Promise containing tool details including description and schemas
370
1575
  */
371
- details() {
372
- return this.request(`/api/workflows/${this.workflowId}`);
1576
+ details(requestContext) {
1577
+ return this.request(`/api/tools/${this.toolId}${requestContextQueryString(requestContext)}`);
373
1578
  }
374
1579
  /**
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
1580
+ * Executes the tool with the provided parameters
1581
+ * @param params - Parameters required for tool execution
1582
+ * @returns Promise containing the tool execution results
379
1583
  */
380
1584
  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);
1585
+ const url = new URLSearchParams();
1586
+ if (params.runId) {
1587
+ url.set("runId", params.runId);
439
1588
  }
440
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1589
+ const body = {
1590
+ data: params.data,
1591
+ requestContext: parseClientRequestContext(params.requestContext)
1592
+ };
1593
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
441
1594
  method: "POST",
442
- body: params?.triggerData
1595
+ body
443
1596
  });
444
1597
  }
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
- });
1598
+ };
1599
+
1600
+ // src/resources/workflow.ts
1601
+ var RECORD_SEPARATOR = "";
1602
+ var Workflow = class extends BaseResource {
1603
+ constructor(options, workflowId) {
1604
+ super(options);
1605
+ this.workflowId = workflowId;
458
1606
  }
459
1607
  /**
460
- * Creates an async generator that processes a readable stream and yields records
1608
+ * Creates an async generator that processes a readable stream and yields workflow records
461
1609
  * separated by the Record Separator character (\x1E)
462
1610
  *
463
1611
  * @param stream - The readable stream to process
@@ -487,7 +1635,7 @@ var Workflow = class extends BaseResource {
487
1635
  }
488
1636
  }
489
1637
  }
490
- } catch (error) {
1638
+ } catch {
491
1639
  }
492
1640
  }
493
1641
  if (buffer) {
@@ -502,219 +1650,1182 @@ var Workflow = class extends BaseResource {
502
1650
  }
503
1651
  }
504
1652
  /**
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
1653
+ * Retrieves details about the workflow
1654
+ * @param requestContext - Optional request context to pass as query parameter
1655
+ * @returns Promise containing workflow details including steps and graphs
508
1656
  */
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}`);
1657
+ details(requestContext) {
1658
+ return this.request(`/api/workflows/${this.workflowId}${requestContextQueryString(requestContext)}`);
1659
+ }
1660
+ /**
1661
+ * Retrieves all runs for a workflow
1662
+ * @param params - Parameters for filtering runs
1663
+ * @param requestContext - Optional request context to pass as query parameter
1664
+ * @returns Promise containing workflow runs array
1665
+ */
1666
+ runs(params, requestContext) {
1667
+ const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
1668
+ const searchParams = new URLSearchParams();
1669
+ if (params?.fromDate) {
1670
+ searchParams.set("fromDate", params.fromDate.toISOString());
515
1671
  }
516
- if (!response.body) {
517
- throw new Error("Response body is null");
1672
+ if (params?.toDate) {
1673
+ searchParams.set("toDate", params.toDate.toISOString());
518
1674
  }
519
- for await (const record of this.streamProcessor(response.body)) {
520
- onRecord(record);
1675
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1676
+ searchParams.set("limit", String(params.limit));
1677
+ }
1678
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1679
+ searchParams.set("offset", String(params.offset));
1680
+ }
1681
+ if (params?.resourceId) {
1682
+ searchParams.set("resourceId", params.resourceId);
1683
+ }
1684
+ if (requestContextParam) {
1685
+ searchParams.set("requestContext", requestContextParam);
1686
+ }
1687
+ if (searchParams.size) {
1688
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1689
+ } else {
1690
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
521
1691
  }
522
1692
  }
523
- };
524
-
525
- // src/resources/tool.ts
526
- var Tool = class extends BaseResource {
527
- constructor(options, toolId) {
528
- super(options);
529
- this.toolId = toolId;
1693
+ /**
1694
+ * Retrieves a specific workflow run by its ID
1695
+ * @param runId - The ID of the workflow run to retrieve
1696
+ * @param requestContext - Optional request context to pass as query parameter
1697
+ * @returns Promise containing the workflow run details
1698
+ */
1699
+ runById(runId, requestContext) {
1700
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${requestContextQueryString(requestContext)}`);
530
1701
  }
531
1702
  /**
532
- * Retrieves details about the tool
533
- * @returns Promise containing tool details including description and schemas
1703
+ * Retrieves the execution result for a specific workflow run by its ID
1704
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1705
+ * @param requestContext - Optional request context to pass as query parameter
1706
+ * @returns Promise containing the workflow run execution result
534
1707
  */
535
- details() {
536
- return this.request(`/api/tools/${this.toolId}`);
1708
+ runExecutionResult(runId, requestContext) {
1709
+ return this.request(
1710
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${requestContextQueryString(requestContext)}`
1711
+ );
537
1712
  }
538
1713
  /**
539
- * Executes the tool with the provided parameters
540
- * @param params - Parameters required for tool execution
541
- * @returns Promise containing the tool execution results
1714
+ * Cancels a specific workflow run by its ID
1715
+ * @param runId - The ID of the workflow run to cancel
1716
+ * @returns Promise containing a success message
542
1717
  */
543
- execute(params) {
544
- return this.request(`/api/tools/${this.toolId}/execute`, {
545
- method: "POST",
546
- body: params
1718
+ cancelRun(runId) {
1719
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1720
+ method: "POST"
547
1721
  });
548
1722
  }
549
- };
550
-
551
- // src/resources/vnext-workflow.ts
552
- var RECORD_SEPARATOR2 = "";
553
- var VNextWorkflow = class extends BaseResource {
554
- constructor(options, workflowId) {
555
- super(options);
556
- this.workflowId = workflowId;
557
- }
558
1723
  /**
559
- * Creates an async generator that processes a readable stream and yields vNext workflow records
560
- * separated by the Record Separator character (\x1E)
561
- *
562
- * @param stream - The readable stream to process
563
- * @returns An async generator that yields parsed records
1724
+ * Sends an event to a specific workflow run by its ID
1725
+ * @param params - Object containing the runId, event and data
1726
+ * @returns Promise containing a success message
564
1727
  */
565
- async *streamProcessor(stream) {
566
- const reader = stream.getReader();
567
- let doneReading = false;
568
- let buffer = "";
569
- try {
570
- while (!doneReading) {
571
- const { done, value } = await reader.read();
572
- doneReading = done;
573
- if (done && !value) continue;
574
- try {
575
- const decoded = value ? new TextDecoder().decode(value) : "";
576
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
577
- buffer = chunks.pop() || "";
578
- for (const chunk of chunks) {
579
- if (chunk) {
580
- if (typeof chunk === "string") {
581
- try {
582
- const parsedChunk = JSON.parse(chunk);
583
- yield parsedChunk;
584
- } catch {
585
- }
586
- }
587
- }
588
- }
589
- } catch (error) {
590
- }
591
- }
592
- if (buffer) {
593
- try {
594
- yield JSON.parse(buffer);
595
- } catch {
596
- }
597
- }
598
- } finally {
599
- reader.cancel().catch(() => {
600
- });
601
- }
1728
+ sendRunEvent(params) {
1729
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1730
+ method: "POST",
1731
+ body: { event: params.event, data: params.data }
1732
+ });
602
1733
  }
603
1734
  /**
604
- * Retrieves details about the vNext workflow
605
- * @returns Promise containing vNext workflow details including steps and graphs
1735
+ * @deprecated Use createRunAsync() instead.
1736
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
606
1737
  */
607
- details() {
608
- return this.request(`/api/workflows/v-next/${this.workflowId}`);
1738
+ async createRun(_params) {
1739
+ throw new Error(
1740
+ "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."
1741
+ );
609
1742
  }
610
1743
  /**
611
- * Creates a new vNext workflow run
1744
+ * Creates a new workflow run
612
1745
  * @param params - Optional object containing the optional runId
613
- * @returns Promise containing the runId of the created run
1746
+ * @returns Promise containing the runId of the created run with methods to control execution
614
1747
  */
615
- createRun(params) {
1748
+ async createRunAsync(params) {
616
1749
  const searchParams = new URLSearchParams();
617
1750
  if (!!params?.runId) {
618
1751
  searchParams.set("runId", params.runId);
619
1752
  }
620
- return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
621
- method: "POST"
622
- });
1753
+ const res = await this.request(
1754
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1755
+ {
1756
+ method: "POST"
1757
+ }
1758
+ );
1759
+ const runId = res.runId;
1760
+ return {
1761
+ runId,
1762
+ start: async (p) => {
1763
+ return this.start({
1764
+ runId,
1765
+ inputData: p.inputData,
1766
+ requestContext: p.requestContext,
1767
+ tracingOptions: p.tracingOptions
1768
+ });
1769
+ },
1770
+ startAsync: async (p) => {
1771
+ return this.startAsync({
1772
+ runId,
1773
+ inputData: p.inputData,
1774
+ requestContext: p.requestContext,
1775
+ tracingOptions: p.tracingOptions
1776
+ });
1777
+ },
1778
+ watch: async (onRecord) => {
1779
+ return this.watch({ runId }, onRecord);
1780
+ },
1781
+ stream: async (p) => {
1782
+ return this.stream({ runId, inputData: p.inputData, requestContext: p.requestContext });
1783
+ },
1784
+ resume: async (p) => {
1785
+ return this.resume({
1786
+ runId,
1787
+ step: p.step,
1788
+ resumeData: p.resumeData,
1789
+ requestContext: p.requestContext,
1790
+ tracingOptions: p.tracingOptions
1791
+ });
1792
+ },
1793
+ resumeAsync: async (p) => {
1794
+ return this.resumeAsync({
1795
+ runId,
1796
+ step: p.step,
1797
+ resumeData: p.resumeData,
1798
+ requestContext: p.requestContext,
1799
+ tracingOptions: p.tracingOptions
1800
+ });
1801
+ },
1802
+ resumeStreamVNext: async (p) => {
1803
+ return this.resumeStreamVNext({
1804
+ runId,
1805
+ step: p.step,
1806
+ resumeData: p.resumeData,
1807
+ requestContext: p.requestContext
1808
+ });
1809
+ }
1810
+ };
623
1811
  }
624
1812
  /**
625
- * Starts a vNext workflow run synchronously without waiting for the workflow to complete
626
- * @param params - Object containing the runId, inputData and runtimeContext
1813
+ * Starts a workflow run synchronously without waiting for the workflow to complete
1814
+ * @param params - Object containing the runId, inputData and requestContext
627
1815
  * @returns Promise containing success message
628
1816
  */
629
1817
  start(params) {
630
- return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
1818
+ const requestContext = parseClientRequestContext(params.requestContext);
1819
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
631
1820
  method: "POST",
632
- body: { inputData: params?.inputData, runtimeContext: params.runtimeContext }
1821
+ body: { inputData: params?.inputData, requestContext, tracingOptions: params.tracingOptions }
633
1822
  });
634
1823
  }
635
1824
  /**
636
- * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
637
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1825
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1826
+ * @param params - Object containing the runId, step, resumeData and requestContext
638
1827
  * @returns Promise containing success message
639
1828
  */
640
1829
  resume({
641
1830
  step,
642
1831
  runId,
643
1832
  resumeData,
644
- runtimeContext
1833
+ tracingOptions,
1834
+ ...rest
645
1835
  }) {
646
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
1836
+ const requestContext = parseClientRequestContext(rest.requestContext);
1837
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
647
1838
  method: "POST",
648
- stream: true,
649
1839
  body: {
650
1840
  step,
651
1841
  resumeData,
652
- runtimeContext
1842
+ requestContext,
1843
+ tracingOptions
653
1844
  }
654
1845
  });
655
1846
  }
656
1847
  /**
657
- * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
658
- * @param params - Object containing the optional runId, inputData and runtimeContext
659
- * @returns Promise containing the vNext workflow execution results
1848
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1849
+ * @param params - Object containing the optional runId, inputData and requestContext
1850
+ * @returns Promise containing the workflow execution results
660
1851
  */
661
1852
  startAsync(params) {
662
1853
  const searchParams = new URLSearchParams();
663
1854
  if (!!params?.runId) {
664
1855
  searchParams.set("runId", params.runId);
665
1856
  }
666
- return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
1857
+ const requestContext = parseClientRequestContext(params.requestContext);
1858
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
667
1859
  method: "POST",
668
- body: { inputData: params.inputData, runtimeContext: params.runtimeContext }
1860
+ body: { inputData: params.inputData, requestContext, tracingOptions: params.tracingOptions }
669
1861
  });
670
1862
  }
671
1863
  /**
672
- * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
673
- * @param params - Object containing the runId, step, resumeData and runtimeContext
674
- * @returns Promise containing the vNext workflow resume results
1864
+ * Starts a workflow run and returns a stream
1865
+ * @param params - Object containing the optional runId, inputData and requestContext
1866
+ * @returns Promise containing the workflow execution results
675
1867
  */
676
- resumeAsync(params) {
677
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
678
- method: "POST",
679
- body: {
680
- step: params.step,
681
- resumeData: params.resumeData,
682
- runtimeContext: params.runtimeContext
1868
+ async stream(params) {
1869
+ const searchParams = new URLSearchParams();
1870
+ if (!!params?.runId) {
1871
+ searchParams.set("runId", params.runId);
1872
+ }
1873
+ const requestContext = parseClientRequestContext(params.requestContext);
1874
+ const response = await this.request(
1875
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1876
+ {
1877
+ method: "POST",
1878
+ body: { inputData: params.inputData, requestContext, tracingOptions: params.tracingOptions },
1879
+ stream: true
1880
+ }
1881
+ );
1882
+ if (!response.ok) {
1883
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1884
+ }
1885
+ if (!response.body) {
1886
+ throw new Error("Response body is null");
1887
+ }
1888
+ let failedChunk = void 0;
1889
+ const transformStream = new TransformStream({
1890
+ start() {
1891
+ },
1892
+ async transform(chunk, controller) {
1893
+ try {
1894
+ const decoded = new TextDecoder().decode(chunk);
1895
+ const chunks = decoded.split(RECORD_SEPARATOR);
1896
+ for (const chunk2 of chunks) {
1897
+ if (chunk2) {
1898
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1899
+ try {
1900
+ const parsedChunk = JSON.parse(newChunk);
1901
+ controller.enqueue(parsedChunk);
1902
+ failedChunk = void 0;
1903
+ } catch {
1904
+ failedChunk = newChunk;
1905
+ }
1906
+ }
1907
+ }
1908
+ } catch {
1909
+ }
683
1910
  }
684
1911
  });
1912
+ return response.body.pipeThrough(transformStream);
685
1913
  }
686
1914
  /**
687
- * Watches vNext workflow transitions in real-time
688
- * @param runId - Optional run ID to filter the watch stream
689
- * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
1915
+ * Observes workflow stream for a workflow run
1916
+ * @param params - Object containing the runId
1917
+ * @returns Promise containing the workflow execution results
690
1918
  */
691
- async watch({ runId }, onRecord) {
692
- const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
693
- stream: true
694
- });
1919
+ async observeStream(params) {
1920
+ const searchParams = new URLSearchParams();
1921
+ searchParams.set("runId", params.runId);
1922
+ const response = await this.request(
1923
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1924
+ {
1925
+ method: "POST",
1926
+ stream: true
1927
+ }
1928
+ );
695
1929
  if (!response.ok) {
696
- throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
1930
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
697
1931
  }
698
1932
  if (!response.body) {
699
1933
  throw new Error("Response body is null");
700
1934
  }
701
- for await (const record of this.streamProcessor(response.body)) {
702
- onRecord(record);
703
- }
1935
+ let failedChunk = void 0;
1936
+ const transformStream = new TransformStream({
1937
+ start() {
1938
+ },
1939
+ async transform(chunk, controller) {
1940
+ try {
1941
+ const decoded = new TextDecoder().decode(chunk);
1942
+ const chunks = decoded.split(RECORD_SEPARATOR);
1943
+ for (const chunk2 of chunks) {
1944
+ if (chunk2) {
1945
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1946
+ try {
1947
+ const parsedChunk = JSON.parse(newChunk);
1948
+ controller.enqueue(parsedChunk);
1949
+ failedChunk = void 0;
1950
+ } catch {
1951
+ failedChunk = newChunk;
1952
+ }
1953
+ }
1954
+ }
1955
+ } catch {
1956
+ }
1957
+ }
1958
+ });
1959
+ return response.body.pipeThrough(transformStream);
704
1960
  }
705
- };
706
-
707
- // src/client.ts
708
- var MastraClient = class extends BaseResource {
709
- constructor(options) {
1961
+ /**
1962
+ * Starts a workflow run and returns a stream
1963
+ * @param params - Object containing the optional runId, inputData and requestContext
1964
+ * @returns Promise containing the workflow execution results
1965
+ */
1966
+ async streamVNext(params) {
1967
+ const searchParams = new URLSearchParams();
1968
+ if (!!params?.runId) {
1969
+ searchParams.set("runId", params.runId);
1970
+ }
1971
+ const requestContext = parseClientRequestContext(params.requestContext);
1972
+ const response = await this.request(
1973
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1974
+ {
1975
+ method: "POST",
1976
+ body: {
1977
+ inputData: params.inputData,
1978
+ requestContext,
1979
+ closeOnSuspend: params.closeOnSuspend,
1980
+ tracingOptions: params.tracingOptions
1981
+ },
1982
+ stream: true
1983
+ }
1984
+ );
1985
+ if (!response.ok) {
1986
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1987
+ }
1988
+ if (!response.body) {
1989
+ throw new Error("Response body is null");
1990
+ }
1991
+ let failedChunk = void 0;
1992
+ const transformStream = new TransformStream({
1993
+ start() {
1994
+ },
1995
+ async transform(chunk, controller) {
1996
+ try {
1997
+ const decoded = new TextDecoder().decode(chunk);
1998
+ const chunks = decoded.split(RECORD_SEPARATOR);
1999
+ for (const chunk2 of chunks) {
2000
+ if (chunk2) {
2001
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2002
+ try {
2003
+ const parsedChunk = JSON.parse(newChunk);
2004
+ controller.enqueue(parsedChunk);
2005
+ failedChunk = void 0;
2006
+ } catch {
2007
+ failedChunk = newChunk;
2008
+ }
2009
+ }
2010
+ }
2011
+ } catch {
2012
+ }
2013
+ }
2014
+ });
2015
+ return response.body.pipeThrough(transformStream);
2016
+ }
2017
+ /**
2018
+ * Observes workflow vNext stream for a workflow run
2019
+ * @param params - Object containing the runId
2020
+ * @returns Promise containing the workflow execution results
2021
+ */
2022
+ async observeStreamVNext(params) {
2023
+ const searchParams = new URLSearchParams();
2024
+ searchParams.set("runId", params.runId);
2025
+ const response = await this.request(
2026
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
2027
+ {
2028
+ method: "POST",
2029
+ stream: true
2030
+ }
2031
+ );
2032
+ if (!response.ok) {
2033
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
2034
+ }
2035
+ if (!response.body) {
2036
+ throw new Error("Response body is null");
2037
+ }
2038
+ let failedChunk = void 0;
2039
+ const transformStream = new TransformStream({
2040
+ start() {
2041
+ },
2042
+ async transform(chunk, controller) {
2043
+ try {
2044
+ const decoded = new TextDecoder().decode(chunk);
2045
+ const chunks = decoded.split(RECORD_SEPARATOR);
2046
+ for (const chunk2 of chunks) {
2047
+ if (chunk2) {
2048
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2049
+ try {
2050
+ const parsedChunk = JSON.parse(newChunk);
2051
+ controller.enqueue(parsedChunk);
2052
+ failedChunk = void 0;
2053
+ } catch {
2054
+ failedChunk = newChunk;
2055
+ }
2056
+ }
2057
+ }
2058
+ } catch {
2059
+ }
2060
+ }
2061
+ });
2062
+ return response.body.pipeThrough(transformStream);
2063
+ }
2064
+ /**
2065
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2066
+ * @param params - Object containing the runId, step, resumeData and requestContext
2067
+ * @returns Promise containing the workflow resume results
2068
+ */
2069
+ resumeAsync(params) {
2070
+ const requestContext = parseClientRequestContext(params.requestContext);
2071
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2072
+ method: "POST",
2073
+ body: {
2074
+ step: params.step,
2075
+ resumeData: params.resumeData,
2076
+ requestContext,
2077
+ tracingOptions: params.tracingOptions
2078
+ }
2079
+ });
2080
+ }
2081
+ /**
2082
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2083
+ * @param params - Object containing the runId, step, resumeData and requestContext
2084
+ * @returns Promise containing the workflow resume results
2085
+ */
2086
+ async resumeStreamVNext(params) {
2087
+ const searchParams = new URLSearchParams();
2088
+ searchParams.set("runId", params.runId);
2089
+ const requestContext = parseClientRequestContext(params.requestContext);
2090
+ const response = await this.request(
2091
+ `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
2092
+ {
2093
+ method: "POST",
2094
+ body: {
2095
+ step: params.step,
2096
+ resumeData: params.resumeData,
2097
+ requestContext,
2098
+ tracingOptions: params.tracingOptions
2099
+ },
2100
+ stream: true
2101
+ }
2102
+ );
2103
+ if (!response.ok) {
2104
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2105
+ }
2106
+ if (!response.body) {
2107
+ throw new Error("Response body is null");
2108
+ }
2109
+ let failedChunk = void 0;
2110
+ const transformStream = new TransformStream({
2111
+ start() {
2112
+ },
2113
+ async transform(chunk, controller) {
2114
+ try {
2115
+ const decoded = new TextDecoder().decode(chunk);
2116
+ const chunks = decoded.split(RECORD_SEPARATOR);
2117
+ for (const chunk2 of chunks) {
2118
+ if (chunk2) {
2119
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2120
+ try {
2121
+ const parsedChunk = JSON.parse(newChunk);
2122
+ controller.enqueue(parsedChunk);
2123
+ failedChunk = void 0;
2124
+ } catch {
2125
+ failedChunk = newChunk;
2126
+ }
2127
+ }
2128
+ }
2129
+ } catch {
2130
+ }
2131
+ }
2132
+ });
2133
+ return response.body.pipeThrough(transformStream);
2134
+ }
2135
+ /**
2136
+ * Watches workflow transitions in real-time
2137
+ * @param runId - Optional run ID to filter the watch stream
2138
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2139
+ */
2140
+ async watch({ runId }, onRecord) {
2141
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2142
+ stream: true
2143
+ });
2144
+ if (!response.ok) {
2145
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
2146
+ }
2147
+ if (!response.body) {
2148
+ throw new Error("Response body is null");
2149
+ }
2150
+ for await (const record of this.streamProcessor(response.body)) {
2151
+ if (typeof record === "string") {
2152
+ onRecord(JSON.parse(record));
2153
+ } else {
2154
+ onRecord(record);
2155
+ }
2156
+ }
2157
+ }
2158
+ /**
2159
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2160
+ * serializing each as JSON and separating them with the record separator (\x1E).
2161
+ *
2162
+ * @param records - An iterable or async iterable of objects to stream
2163
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2164
+ */
2165
+ static createRecordStream(records) {
2166
+ const encoder = new TextEncoder();
2167
+ return new ReadableStream({
2168
+ async start(controller) {
2169
+ try {
2170
+ for await (const record of records) {
2171
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
2172
+ controller.enqueue(encoder.encode(json));
2173
+ }
2174
+ controller.close();
2175
+ } catch (err) {
2176
+ controller.error(err);
2177
+ }
2178
+ }
2179
+ });
2180
+ }
2181
+ };
2182
+
2183
+ // src/resources/a2a.ts
2184
+ var A2A = class extends BaseResource {
2185
+ constructor(options, agentId) {
2186
+ super(options);
2187
+ this.agentId = agentId;
2188
+ }
2189
+ /**
2190
+ * Get the agent card with metadata about the agent
2191
+ * @returns Promise containing the agent card information
2192
+ */
2193
+ async getCard() {
2194
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2195
+ }
2196
+ /**
2197
+ * Send a message to the agent and gets a message or task response
2198
+ * @param params - Parameters for the task
2199
+ * @returns Promise containing the response
2200
+ */
2201
+ async sendMessage(params) {
2202
+ const response = await this.request(`/a2a/${this.agentId}`, {
2203
+ method: "POST",
2204
+ body: {
2205
+ method: "message/send",
2206
+ params
2207
+ }
2208
+ });
2209
+ return response;
2210
+ }
2211
+ /**
2212
+ * Sends a message to an agent to initiate/continue a task and subscribes
2213
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2214
+ * @param params - Parameters for the task
2215
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2216
+ */
2217
+ async sendStreamingMessage(params) {
2218
+ const response = await this.request(`/a2a/${this.agentId}`, {
2219
+ method: "POST",
2220
+ body: {
2221
+ method: "message/stream",
2222
+ params
2223
+ }
2224
+ });
2225
+ return response;
2226
+ }
2227
+ /**
2228
+ * Get the status and result of a task
2229
+ * @param params - Parameters for querying the task
2230
+ * @returns Promise containing the task response
2231
+ */
2232
+ async getTask(params) {
2233
+ const response = await this.request(`/a2a/${this.agentId}`, {
2234
+ method: "POST",
2235
+ body: {
2236
+ method: "tasks/get",
2237
+ params
2238
+ }
2239
+ });
2240
+ return response;
2241
+ }
2242
+ /**
2243
+ * Cancel a running task
2244
+ * @param params - Parameters identifying the task to cancel
2245
+ * @returns Promise containing the task response
2246
+ */
2247
+ async cancelTask(params) {
2248
+ return this.request(`/a2a/${this.agentId}`, {
2249
+ method: "POST",
2250
+ body: {
2251
+ method: "tasks/cancel",
2252
+ params
2253
+ }
2254
+ });
2255
+ }
2256
+ };
2257
+
2258
+ // src/resources/mcp-tool.ts
2259
+ var MCPTool = class extends BaseResource {
2260
+ serverId;
2261
+ toolId;
2262
+ constructor(options, serverId, toolId) {
2263
+ super(options);
2264
+ this.serverId = serverId;
2265
+ this.toolId = toolId;
2266
+ }
2267
+ /**
2268
+ * Retrieves details about this specific tool from the MCP server.
2269
+ * @param requestContext - Optional request context to pass as query parameter
2270
+ * @returns Promise containing the tool's information (name, description, schema).
2271
+ */
2272
+ details(requestContext) {
2273
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${requestContextQueryString(requestContext)}`);
2274
+ }
2275
+ /**
2276
+ * Executes this specific tool on the MCP server.
2277
+ * @param params - Parameters for tool execution, including data/args and optional requestContext.
2278
+ * @returns Promise containing the result of the tool execution.
2279
+ */
2280
+ execute(params) {
2281
+ const body = {};
2282
+ if (params.data !== void 0) body.data = params.data;
2283
+ if (params.requestContext !== void 0) {
2284
+ body.requestContext = params.requestContext;
2285
+ }
2286
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2287
+ method: "POST",
2288
+ body: Object.keys(body).length > 0 ? body : void 0
2289
+ });
2290
+ }
2291
+ };
2292
+
2293
+ // src/resources/agent-builder.ts
2294
+ var RECORD_SEPARATOR2 = "";
2295
+ var AgentBuilder = class extends BaseResource {
2296
+ constructor(options, actionId) {
2297
+ super(options);
2298
+ this.actionId = actionId;
2299
+ }
2300
+ // Helper function to transform workflow result to action result
2301
+ transformWorkflowResult(result) {
2302
+ if (result.status === "success") {
2303
+ return {
2304
+ success: result.result.success || false,
2305
+ applied: result.result.applied || false,
2306
+ branchName: result.result.branchName,
2307
+ message: result.result.message || "Agent builder action completed",
2308
+ validationResults: result.result.validationResults,
2309
+ error: result.result.error,
2310
+ errors: result.result.errors,
2311
+ stepResults: result.result.stepResults
2312
+ };
2313
+ } else if (result.status === "failed") {
2314
+ return {
2315
+ success: false,
2316
+ applied: false,
2317
+ message: `Agent builder action failed: ${result.error.message}`,
2318
+ error: result.error.message
2319
+ };
2320
+ } else {
2321
+ return {
2322
+ success: false,
2323
+ applied: false,
2324
+ message: "Agent builder action was suspended",
2325
+ error: "Workflow suspended - manual intervention required"
2326
+ };
2327
+ }
2328
+ }
2329
+ /**
2330
+ * Creates a transform stream that parses binary chunks into JSON records.
2331
+ */
2332
+ createRecordParserTransform() {
2333
+ let failedChunk = void 0;
2334
+ return new TransformStream({
2335
+ start() {
2336
+ },
2337
+ async transform(chunk, controller) {
2338
+ try {
2339
+ const decoded = new TextDecoder().decode(chunk);
2340
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2341
+ for (const chunk2 of chunks) {
2342
+ if (chunk2) {
2343
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2344
+ try {
2345
+ const parsedChunk = JSON.parse(newChunk);
2346
+ controller.enqueue(parsedChunk);
2347
+ failedChunk = void 0;
2348
+ } catch {
2349
+ failedChunk = newChunk;
2350
+ }
2351
+ }
2352
+ }
2353
+ } catch {
2354
+ }
2355
+ }
2356
+ });
2357
+ }
2358
+ /**
2359
+ * @deprecated Use createRunAsync() instead.
2360
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2361
+ */
2362
+ async createRun(_params) {
2363
+ throw new Error(
2364
+ "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."
2365
+ );
2366
+ }
2367
+ /**
2368
+ * Creates a new agent builder action run and returns the runId.
2369
+ * This calls `/api/agent-builder/:actionId/create-run`.
2370
+ */
2371
+ async createRunAsync(params) {
2372
+ const searchParams = new URLSearchParams();
2373
+ if (!!params?.runId) {
2374
+ searchParams.set("runId", params.runId);
2375
+ }
2376
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2377
+ return this.request(url, {
2378
+ method: "POST"
2379
+ });
2380
+ }
2381
+ /**
2382
+ * Starts agent builder action asynchronously and waits for completion.
2383
+ * This calls `/api/agent-builder/:actionId/start-async`.
2384
+ */
2385
+ async startAsync(params, runId) {
2386
+ const searchParams = new URLSearchParams();
2387
+ if (runId) {
2388
+ searchParams.set("runId", runId);
2389
+ }
2390
+ const requestContext = parseClientRequestContext(params.requestContext);
2391
+ const { requestContext: _, ...actionParams } = params;
2392
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2393
+ const result = await this.request(url, {
2394
+ method: "POST",
2395
+ body: { ...actionParams, requestContext }
2396
+ });
2397
+ return this.transformWorkflowResult(result);
2398
+ }
2399
+ /**
2400
+ * Starts an existing agent builder action run.
2401
+ * This calls `/api/agent-builder/:actionId/start`.
2402
+ */
2403
+ async startActionRun(params, runId) {
2404
+ const searchParams = new URLSearchParams();
2405
+ searchParams.set("runId", runId);
2406
+ const requestContext = parseClientRequestContext(params.requestContext);
2407
+ const { requestContext: _, ...actionParams } = params;
2408
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2409
+ return this.request(url, {
2410
+ method: "POST",
2411
+ body: { ...actionParams, requestContext }
2412
+ });
2413
+ }
2414
+ /**
2415
+ * Resumes a suspended agent builder action step.
2416
+ * This calls `/api/agent-builder/:actionId/resume`.
2417
+ */
2418
+ async resume(params, runId) {
2419
+ const searchParams = new URLSearchParams();
2420
+ searchParams.set("runId", runId);
2421
+ const requestContext = parseClientRequestContext(params.requestContext);
2422
+ const { requestContext: _, ...resumeParams } = params;
2423
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2424
+ return this.request(url, {
2425
+ method: "POST",
2426
+ body: { ...resumeParams, requestContext }
2427
+ });
2428
+ }
2429
+ /**
2430
+ * Resumes a suspended agent builder action step asynchronously.
2431
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2432
+ */
2433
+ async resumeAsync(params, runId) {
2434
+ const searchParams = new URLSearchParams();
2435
+ searchParams.set("runId", runId);
2436
+ const requestContext = parseClientRequestContext(params.requestContext);
2437
+ const { requestContext: _, ...resumeParams } = params;
2438
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2439
+ const result = await this.request(url, {
2440
+ method: "POST",
2441
+ body: { ...resumeParams, requestContext }
2442
+ });
2443
+ return this.transformWorkflowResult(result);
2444
+ }
2445
+ /**
2446
+ * Creates an async generator that processes a readable stream and yields action records
2447
+ * separated by the Record Separator character (\x1E)
2448
+ *
2449
+ * @param stream - The readable stream to process
2450
+ * @returns An async generator that yields parsed records
2451
+ */
2452
+ async *streamProcessor(stream) {
2453
+ const reader = stream.getReader();
2454
+ let doneReading = false;
2455
+ let buffer = "";
2456
+ try {
2457
+ while (!doneReading) {
2458
+ const { done, value } = await reader.read();
2459
+ doneReading = done;
2460
+ if (done && !value) continue;
2461
+ try {
2462
+ const decoded = value ? new TextDecoder().decode(value) : "";
2463
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2464
+ buffer = chunks.pop() || "";
2465
+ for (const chunk of chunks) {
2466
+ if (chunk) {
2467
+ if (typeof chunk === "string") {
2468
+ try {
2469
+ const parsedChunk = JSON.parse(chunk);
2470
+ yield parsedChunk;
2471
+ } catch {
2472
+ }
2473
+ }
2474
+ }
2475
+ }
2476
+ } catch {
2477
+ }
2478
+ }
2479
+ if (buffer) {
2480
+ try {
2481
+ yield JSON.parse(buffer);
2482
+ } catch {
2483
+ }
2484
+ }
2485
+ } finally {
2486
+ reader.cancel().catch(() => {
2487
+ });
2488
+ }
2489
+ }
2490
+ /**
2491
+ * Streams agent builder action progress in real-time.
2492
+ * This calls `/api/agent-builder/:actionId/stream`.
2493
+ */
2494
+ async stream(params, runId) {
2495
+ const searchParams = new URLSearchParams();
2496
+ if (runId) {
2497
+ searchParams.set("runId", runId);
2498
+ }
2499
+ const requestContext = parseClientRequestContext(params.requestContext);
2500
+ const { requestContext: _, ...actionParams } = params;
2501
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2502
+ const response = await this.request(url, {
2503
+ method: "POST",
2504
+ body: { ...actionParams, requestContext },
2505
+ stream: true
2506
+ });
2507
+ if (!response.ok) {
2508
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2509
+ }
2510
+ if (!response.body) {
2511
+ throw new Error("Response body is null");
2512
+ }
2513
+ return response.body.pipeThrough(this.createRecordParserTransform());
2514
+ }
2515
+ /**
2516
+ * Streams agent builder action progress in real-time using VNext streaming.
2517
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2518
+ */
2519
+ async streamVNext(params, runId) {
2520
+ const searchParams = new URLSearchParams();
2521
+ if (runId) {
2522
+ searchParams.set("runId", runId);
2523
+ }
2524
+ const requestContext = parseClientRequestContext(params.requestContext);
2525
+ const { requestContext: _, ...actionParams } = params;
2526
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2527
+ const response = await this.request(url, {
2528
+ method: "POST",
2529
+ body: { ...actionParams, requestContext },
2530
+ stream: true
2531
+ });
2532
+ if (!response.ok) {
2533
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2534
+ }
2535
+ if (!response.body) {
2536
+ throw new Error("Response body is null");
2537
+ }
2538
+ return response.body.pipeThrough(this.createRecordParserTransform());
2539
+ }
2540
+ /**
2541
+ * Watches an existing agent builder action run by runId.
2542
+ * This is used for hot reload recovery - it loads the existing run state
2543
+ * and streams any remaining progress.
2544
+ * This calls `/api/agent-builder/:actionId/watch`.
2545
+ */
2546
+ async watch({ runId, eventType }, onRecord) {
2547
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2548
+ const response = await this.request(url, {
2549
+ method: "GET",
2550
+ stream: true
2551
+ });
2552
+ if (!response.ok) {
2553
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2554
+ }
2555
+ if (!response.body) {
2556
+ throw new Error("Response body is null");
2557
+ }
2558
+ for await (const record of this.streamProcessor(response.body)) {
2559
+ if (typeof record === "string") {
2560
+ onRecord(JSON.parse(record));
2561
+ } else {
2562
+ onRecord(record);
2563
+ }
2564
+ }
2565
+ }
2566
+ /**
2567
+ * Observes an existing agent builder action run stream.
2568
+ * Replays cached execution from the beginning, then continues with live stream.
2569
+ * This is the recommended method for recovery after page refresh/hot reload.
2570
+ * This calls `/api/agent-builder/:actionId/observe` (which delegates to observeStreamVNext).
2571
+ */
2572
+ async observeStream(params) {
2573
+ const searchParams = new URLSearchParams();
2574
+ searchParams.set("runId", params.runId);
2575
+ const url = `/api/agent-builder/${this.actionId}/observe?${searchParams.toString()}`;
2576
+ const response = await this.request(url, {
2577
+ method: "POST",
2578
+ stream: true
2579
+ });
2580
+ if (!response.ok) {
2581
+ throw new Error(`Failed to observe agent builder action stream: ${response.statusText}`);
2582
+ }
2583
+ if (!response.body) {
2584
+ throw new Error("Response body is null");
2585
+ }
2586
+ return response.body.pipeThrough(this.createRecordParserTransform());
2587
+ }
2588
+ /**
2589
+ * Observes an existing agent builder action run stream using VNext streaming API.
2590
+ * Replays cached execution from the beginning, then continues with live stream.
2591
+ * This calls `/api/agent-builder/:actionId/observe-streamVNext`.
2592
+ */
2593
+ async observeStreamVNext(params) {
2594
+ const searchParams = new URLSearchParams();
2595
+ searchParams.set("runId", params.runId);
2596
+ const url = `/api/agent-builder/${this.actionId}/observe-streamVNext?${searchParams.toString()}`;
2597
+ const response = await this.request(url, {
2598
+ method: "POST",
2599
+ stream: true
2600
+ });
2601
+ if (!response.ok) {
2602
+ throw new Error(`Failed to observe agent builder action stream VNext: ${response.statusText}`);
2603
+ }
2604
+ if (!response.body) {
2605
+ throw new Error("Response body is null");
2606
+ }
2607
+ return response.body.pipeThrough(this.createRecordParserTransform());
2608
+ }
2609
+ /**
2610
+ * Observes an existing agent builder action run stream using legacy streaming API.
2611
+ * Replays cached execution from the beginning, then continues with live stream.
2612
+ * This calls `/api/agent-builder/:actionId/observe-stream-legacy`.
2613
+ */
2614
+ async observeStreamLegacy(params) {
2615
+ const searchParams = new URLSearchParams();
2616
+ searchParams.set("runId", params.runId);
2617
+ const url = `/api/agent-builder/${this.actionId}/observe-stream-legacy?${searchParams.toString()}`;
2618
+ const response = await this.request(url, {
2619
+ method: "POST",
2620
+ stream: true
2621
+ });
2622
+ if (!response.ok) {
2623
+ throw new Error(`Failed to observe agent builder action stream legacy: ${response.statusText}`);
2624
+ }
2625
+ if (!response.body) {
2626
+ throw new Error("Response body is null");
2627
+ }
2628
+ return response.body.pipeThrough(this.createRecordParserTransform());
2629
+ }
2630
+ /**
2631
+ * Resumes a suspended agent builder action and streams the results.
2632
+ * This calls `/api/agent-builder/:actionId/resume-stream`.
2633
+ */
2634
+ async resumeStream(params) {
2635
+ const searchParams = new URLSearchParams();
2636
+ searchParams.set("runId", params.runId);
2637
+ const requestContext = parseClientRequestContext(params.requestContext);
2638
+ const { runId: _, requestContext: __, ...resumeParams } = params;
2639
+ const url = `/api/agent-builder/${this.actionId}/resume-stream?${searchParams.toString()}`;
2640
+ const response = await this.request(url, {
2641
+ method: "POST",
2642
+ body: { ...resumeParams, requestContext },
2643
+ stream: true
2644
+ });
2645
+ if (!response.ok) {
2646
+ throw new Error(`Failed to resume agent builder action stream: ${response.statusText}`);
2647
+ }
2648
+ if (!response.body) {
2649
+ throw new Error("Response body is null");
2650
+ }
2651
+ return response.body.pipeThrough(this.createRecordParserTransform());
2652
+ }
2653
+ /**
2654
+ * Gets a specific action run by its ID.
2655
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2656
+ */
2657
+ async runById(runId) {
2658
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2659
+ return this.request(url, {
2660
+ method: "GET"
2661
+ });
2662
+ }
2663
+ /**
2664
+ * Gets details about this agent builder action.
2665
+ * This calls `/api/agent-builder/:actionId`.
2666
+ */
2667
+ async details() {
2668
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2669
+ return result;
2670
+ }
2671
+ /**
2672
+ * Gets all runs for this agent builder action.
2673
+ * This calls `/api/agent-builder/:actionId/runs`.
2674
+ */
2675
+ async runs(params) {
2676
+ const searchParams = new URLSearchParams();
2677
+ if (params?.fromDate) {
2678
+ searchParams.set("fromDate", params.fromDate.toISOString());
2679
+ }
2680
+ if (params?.toDate) {
2681
+ searchParams.set("toDate", params.toDate.toISOString());
2682
+ }
2683
+ if (params?.limit !== void 0) {
2684
+ searchParams.set("limit", String(params.limit));
2685
+ }
2686
+ if (params?.offset !== void 0) {
2687
+ searchParams.set("offset", String(params.offset));
2688
+ }
2689
+ if (params?.resourceId) {
2690
+ searchParams.set("resourceId", params.resourceId);
2691
+ }
2692
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2693
+ return this.request(url, {
2694
+ method: "GET"
2695
+ });
2696
+ }
2697
+ /**
2698
+ * Gets the execution result of an agent builder action run.
2699
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2700
+ */
2701
+ async runExecutionResult(runId) {
2702
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2703
+ return this.request(url, {
2704
+ method: "GET"
2705
+ });
2706
+ }
2707
+ /**
2708
+ * Cancels an agent builder action run.
2709
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2710
+ */
2711
+ async cancelRun(runId) {
2712
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2713
+ return this.request(url, {
2714
+ method: "POST"
2715
+ });
2716
+ }
2717
+ /**
2718
+ * Sends an event to an agent builder action run.
2719
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2720
+ */
2721
+ async sendRunEvent(params) {
2722
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2723
+ return this.request(url, {
2724
+ method: "POST",
2725
+ body: { event: params.event, data: params.data }
2726
+ });
2727
+ }
2728
+ };
2729
+
2730
+ // src/resources/observability.ts
2731
+ var Observability = class extends BaseResource {
2732
+ constructor(options) {
2733
+ super(options);
2734
+ }
2735
+ /**
2736
+ * Retrieves a specific AI trace by ID
2737
+ * @param traceId - ID of the trace to retrieve
2738
+ * @returns Promise containing the AI trace with all its spans
2739
+ */
2740
+ getTrace(traceId) {
2741
+ return this.request(`/api/observability/traces/${traceId}`);
2742
+ }
2743
+ /**
2744
+ * Retrieves paginated list of AI traces with optional filtering
2745
+ * @param params - Parameters for pagination and filtering
2746
+ * @returns Promise containing paginated traces and pagination info
2747
+ */
2748
+ getTraces(params) {
2749
+ const { pagination, filters } = params;
2750
+ const { page, perPage, dateRange } = pagination || {};
2751
+ const { name, spanType, entityId, entityType } = filters || {};
2752
+ const searchParams = new URLSearchParams();
2753
+ if (page !== void 0) {
2754
+ searchParams.set("page", String(page));
2755
+ }
2756
+ if (perPage !== void 0) {
2757
+ searchParams.set("perPage", String(perPage));
2758
+ }
2759
+ if (name) {
2760
+ searchParams.set("name", name);
2761
+ }
2762
+ if (spanType !== void 0) {
2763
+ searchParams.set("spanType", String(spanType));
2764
+ }
2765
+ if (entityId && entityType) {
2766
+ searchParams.set("entityId", entityId);
2767
+ searchParams.set("entityType", entityType);
2768
+ }
2769
+ if (dateRange) {
2770
+ const dateRangeStr = JSON.stringify({
2771
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2772
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2773
+ });
2774
+ searchParams.set("dateRange", dateRangeStr);
2775
+ }
2776
+ const queryString = searchParams.toString();
2777
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2778
+ }
2779
+ /**
2780
+ * Retrieves scores by trace ID and span ID
2781
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2782
+ * @returns Promise containing scores and pagination info
2783
+ */
2784
+ getScoresBySpan(params) {
2785
+ const { traceId, spanId, page, perPage } = params;
2786
+ const searchParams = new URLSearchParams();
2787
+ if (page !== void 0) {
2788
+ searchParams.set("page", String(page));
2789
+ }
2790
+ if (perPage !== void 0) {
2791
+ searchParams.set("perPage", String(perPage));
2792
+ }
2793
+ const queryString = searchParams.toString();
2794
+ return this.request(
2795
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2796
+ );
2797
+ }
2798
+ score(params) {
2799
+ return this.request(`/api/observability/traces/score`, {
2800
+ method: "POST",
2801
+ body: { ...params }
2802
+ });
2803
+ }
2804
+ };
2805
+
2806
+ // src/client.ts
2807
+ var MastraClient = class extends BaseResource {
2808
+ observability;
2809
+ constructor(options) {
710
2810
  super(options);
2811
+ this.observability = new Observability(options);
711
2812
  }
712
2813
  /**
713
2814
  * Retrieves all available agents
2815
+ * @param requestContext - Optional request context to pass as query parameter
714
2816
  * @returns Promise containing map of agent IDs to agent details
715
2817
  */
716
- getAgents() {
717
- return this.request("/api/agents");
2818
+ listAgents(requestContext) {
2819
+ const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
2820
+ const searchParams = new URLSearchParams();
2821
+ if (requestContextParam) {
2822
+ searchParams.set("requestContext", requestContextParam);
2823
+ }
2824
+ const queryString = searchParams.toString();
2825
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
2826
+ }
2827
+ listAgentsModelProviders() {
2828
+ return this.request(`/api/agents/providers`);
718
2829
  }
719
2830
  /**
720
2831
  * Gets an agent instance by ID
@@ -725,53 +2836,106 @@ var MastraClient = class extends BaseResource {
725
2836
  return new Agent(this.options, agentId);
726
2837
  }
727
2838
  /**
728
- * Retrieves memory threads for a resource
729
- * @param params - Parameters containing the resource ID
730
- * @returns Promise containing array of memory threads
2839
+ * Lists memory threads for a resource with pagination support
2840
+ * @param params - Parameters containing resource ID, pagination options, and optional request context
2841
+ * @returns Promise containing paginated array of memory threads with metadata
731
2842
  */
732
- getMemoryThreads(params) {
733
- return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
2843
+ listMemoryThreads(params) {
2844
+ const queryParams = new URLSearchParams({
2845
+ resourceId: params.resourceId,
2846
+ agentId: params.agentId,
2847
+ ...params.offset !== void 0 && { offset: params.offset.toString() },
2848
+ ...params.limit !== void 0 && { limit: params.limit.toString() },
2849
+ ...params.orderBy && { orderBy: params.orderBy },
2850
+ ...params.sortDirection && { sortDirection: params.sortDirection }
2851
+ });
2852
+ return this.request(
2853
+ `/api/memory/threads?${queryParams.toString()}${requestContextQueryString(params.requestContext, "&")}`
2854
+ );
2855
+ }
2856
+ /**
2857
+ * Retrieves memory config for a resource
2858
+ * @param params - Parameters containing the resource ID and optional request context
2859
+ * @returns Promise containing memory configuration
2860
+ */
2861
+ getMemoryConfig(params) {
2862
+ return this.request(
2863
+ `/api/memory/config?agentId=${params.agentId}${requestContextQueryString(params.requestContext, "&")}`
2864
+ );
734
2865
  }
735
2866
  /**
736
2867
  * Creates a new memory thread
737
- * @param params - Parameters for creating the memory thread
2868
+ * @param params - Parameters for creating the memory thread including optional request context
738
2869
  * @returns Promise containing the created memory thread
739
2870
  */
740
2871
  createMemoryThread(params) {
741
- return this.request(`/api/memory/threads?agentId=${params.agentId}`, { method: "POST", body: params });
2872
+ return this.request(
2873
+ `/api/memory/threads?agentId=${params.agentId}${requestContextQueryString(params.requestContext, "&")}`,
2874
+ { method: "POST", body: params }
2875
+ );
742
2876
  }
743
2877
  /**
744
2878
  * Gets a memory thread instance by ID
745
2879
  * @param threadId - ID of the memory thread to retrieve
746
2880
  * @returns MemoryThread instance
747
2881
  */
748
- getMemoryThread(threadId, agentId) {
2882
+ getMemoryThread({ threadId, agentId }) {
749
2883
  return new MemoryThread(this.options, threadId, agentId);
750
2884
  }
2885
+ getThreadMessages(threadId, opts = {}) {
2886
+ let url = "";
2887
+ if (opts.agentId) {
2888
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}${requestContextQueryString(opts.requestContext, "&")}`;
2889
+ } else if (opts.networkId) {
2890
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}${requestContextQueryString(opts.requestContext, "&")}`;
2891
+ }
2892
+ return this.request(url);
2893
+ }
2894
+ deleteThread(threadId, opts = {}) {
2895
+ let url = "";
2896
+ if (opts.agentId) {
2897
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}${requestContextQueryString(opts.requestContext, "&")}`;
2898
+ } else if (opts.networkId) {
2899
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}${requestContextQueryString(opts.requestContext, "&")}`;
2900
+ }
2901
+ return this.request(url, { method: "DELETE" });
2902
+ }
751
2903
  /**
752
2904
  * Saves messages to memory
753
- * @param params - Parameters containing messages to save
2905
+ * @param params - Parameters containing messages to save and optional request context
754
2906
  * @returns Promise containing the saved messages
755
2907
  */
756
2908
  saveMessageToMemory(params) {
757
- return this.request(`/api/memory/save-messages?agentId=${params.agentId}`, {
758
- method: "POST",
759
- body: params
760
- });
2909
+ return this.request(
2910
+ `/api/memory/save-messages?agentId=${params.agentId}${requestContextQueryString(params.requestContext, "&")}`,
2911
+ {
2912
+ method: "POST",
2913
+ body: params
2914
+ }
2915
+ );
761
2916
  }
762
2917
  /**
763
2918
  * Gets the status of the memory system
2919
+ * @param agentId - The agent ID
2920
+ * @param requestContext - Optional request context to pass as query parameter
764
2921
  * @returns Promise containing memory system status
765
2922
  */
766
- getMemoryStatus(agentId) {
767
- return this.request(`/api/memory/status?agentId=${agentId}`);
2923
+ getMemoryStatus(agentId, requestContext) {
2924
+ return this.request(`/api/memory/status?agentId=${agentId}${requestContextQueryString(requestContext, "&")}`);
768
2925
  }
769
2926
  /**
770
2927
  * Retrieves all available tools
2928
+ * @param requestContext - Optional request context to pass as query parameter
771
2929
  * @returns Promise containing map of tool IDs to tool details
772
2930
  */
773
- getTools() {
774
- return this.request("/api/tools");
2931
+ listTools(requestContext) {
2932
+ const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
2933
+ const searchParams = new URLSearchParams();
2934
+ if (requestContextParam) {
2935
+ searchParams.set("requestContext", requestContextParam);
2936
+ }
2937
+ const queryString = searchParams.toString();
2938
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
775
2939
  }
776
2940
  /**
777
2941
  * Gets a tool instance by ID
@@ -783,10 +2947,17 @@ var MastraClient = class extends BaseResource {
783
2947
  }
784
2948
  /**
785
2949
  * Retrieves all available workflows
2950
+ * @param requestContext - Optional request context to pass as query parameter
786
2951
  * @returns Promise containing map of workflow IDs to workflow details
787
2952
  */
788
- getWorkflows() {
789
- return this.request("/api/workflows");
2953
+ listWorkflows(requestContext) {
2954
+ const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
2955
+ const searchParams = new URLSearchParams();
2956
+ if (requestContextParam) {
2957
+ searchParams.set("requestContext", requestContextParam);
2958
+ }
2959
+ const queryString = searchParams.toString();
2960
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
790
2961
  }
791
2962
  /**
792
2963
  * Gets a workflow instance by ID
@@ -797,19 +2968,18 @@ var MastraClient = class extends BaseResource {
797
2968
  return new Workflow(this.options, workflowId);
798
2969
  }
799
2970
  /**
800
- * Retrieves all available vNext workflows
801
- * @returns Promise containing map of vNext workflow IDs to vNext workflow details
2971
+ * Gets all available agent builder actions
2972
+ * @returns Promise containing map of action IDs to action details
802
2973
  */
803
- getVNextWorkflows() {
804
- return this.request("/api/workflows/v-next");
2974
+ getAgentBuilderActions() {
2975
+ return this.request("/api/agent-builder/");
805
2976
  }
806
2977
  /**
807
- * Gets a vNext workflow instance by ID
808
- * @param workflowId - ID of the vNext workflow to retrieve
809
- * @returns vNext Workflow instance
2978
+ * Gets an agent builder instance for executing agent-builder workflows
2979
+ * @returns AgentBuilder instance
810
2980
  */
811
- getVNextWorkflow(workflowId) {
812
- return new VNextWorkflow(this.options, workflowId);
2981
+ getAgentBuilderAction(actionId) {
2982
+ return new AgentBuilder(this.options, actionId);
813
2983
  }
814
2984
  /**
815
2985
  * Gets a vector instance by name
@@ -824,8 +2994,42 @@ var MastraClient = class extends BaseResource {
824
2994
  * @param params - Parameters for filtering logs
825
2995
  * @returns Promise containing array of log messages
826
2996
  */
827
- getLogs(params) {
828
- return this.request(`/api/logs?transportId=${params.transportId}`);
2997
+ listLogs(params) {
2998
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2999
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
3000
+ const searchParams = new URLSearchParams();
3001
+ if (transportId) {
3002
+ searchParams.set("transportId", transportId);
3003
+ }
3004
+ if (fromDate) {
3005
+ searchParams.set("fromDate", fromDate.toISOString());
3006
+ }
3007
+ if (toDate) {
3008
+ searchParams.set("toDate", toDate.toISOString());
3009
+ }
3010
+ if (logLevel) {
3011
+ searchParams.set("logLevel", logLevel);
3012
+ }
3013
+ if (page) {
3014
+ searchParams.set("page", String(page));
3015
+ }
3016
+ if (perPage) {
3017
+ searchParams.set("perPage", String(perPage));
3018
+ }
3019
+ if (_filters) {
3020
+ if (Array.isArray(_filters)) {
3021
+ for (const filter of _filters) {
3022
+ searchParams.append("filters", filter);
3023
+ }
3024
+ } else {
3025
+ searchParams.set("filters", _filters);
3026
+ }
3027
+ }
3028
+ if (searchParams.size) {
3029
+ return this.request(`/api/logs?${searchParams}`);
3030
+ } else {
3031
+ return this.request(`/api/logs`);
3032
+ }
829
3033
  }
830
3034
  /**
831
3035
  * Gets logs for a specific run
@@ -833,66 +3037,284 @@ var MastraClient = class extends BaseResource {
833
3037
  * @returns Promise containing array of log messages
834
3038
  */
835
3039
  getLogForRun(params) {
836
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
3040
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
3041
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
3042
+ const searchParams = new URLSearchParams();
3043
+ if (runId) {
3044
+ searchParams.set("runId", runId);
3045
+ }
3046
+ if (transportId) {
3047
+ searchParams.set("transportId", transportId);
3048
+ }
3049
+ if (fromDate) {
3050
+ searchParams.set("fromDate", fromDate.toISOString());
3051
+ }
3052
+ if (toDate) {
3053
+ searchParams.set("toDate", toDate.toISOString());
3054
+ }
3055
+ if (logLevel) {
3056
+ searchParams.set("logLevel", logLevel);
3057
+ }
3058
+ if (page) {
3059
+ searchParams.set("page", String(page));
3060
+ }
3061
+ if (perPage) {
3062
+ searchParams.set("perPage", String(perPage));
3063
+ }
3064
+ if (_filters) {
3065
+ if (Array.isArray(_filters)) {
3066
+ for (const filter of _filters) {
3067
+ searchParams.append("filters", filter);
3068
+ }
3069
+ } else {
3070
+ searchParams.set("filters", _filters);
3071
+ }
3072
+ }
3073
+ if (searchParams.size) {
3074
+ return this.request(`/api/logs/${runId}?${searchParams}`);
3075
+ } else {
3076
+ return this.request(`/api/logs/${runId}`);
3077
+ }
837
3078
  }
838
3079
  /**
839
3080
  * List of all log transports
840
3081
  * @returns Promise containing list of log transports
841
3082
  */
842
- getLogTransports() {
3083
+ listLogTransports() {
843
3084
  return this.request("/api/logs/transports");
844
3085
  }
845
3086
  /**
846
- * List of all traces (paged)
847
- * @param params - Parameters for filtering traces
848
- * @returns Promise containing telemetry data
3087
+ * Retrieves a list of available MCP servers.
3088
+ * @param params - Optional parameters for pagination (limit, offset).
3089
+ * @returns Promise containing the list of MCP servers and pagination info.
849
3090
  */
850
- getTelemetry(params) {
851
- const { name, scope, page, perPage, attribute } = params || {};
852
- const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
3091
+ getMcpServers(params) {
853
3092
  const searchParams = new URLSearchParams();
854
- if (name) {
855
- searchParams.set("name", name);
3093
+ if (params?.limit !== void 0) {
3094
+ searchParams.set("limit", String(params.limit));
856
3095
  }
857
- if (scope) {
858
- searchParams.set("scope", scope);
3096
+ if (params?.offset !== void 0) {
3097
+ searchParams.set("offset", String(params.offset));
859
3098
  }
860
- if (page) {
861
- searchParams.set("page", String(page));
3099
+ const queryString = searchParams.toString();
3100
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
3101
+ }
3102
+ /**
3103
+ * Retrieves detailed information for a specific MCP server.
3104
+ * @param serverId - The ID of the MCP server to retrieve.
3105
+ * @param params - Optional parameters, e.g., specific version.
3106
+ * @returns Promise containing the detailed MCP server information.
3107
+ */
3108
+ getMcpServerDetails(serverId, params) {
3109
+ const searchParams = new URLSearchParams();
3110
+ if (params?.version) {
3111
+ searchParams.set("version", params.version);
862
3112
  }
863
- if (perPage) {
864
- searchParams.set("perPage", String(perPage));
3113
+ const queryString = searchParams.toString();
3114
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
3115
+ }
3116
+ /**
3117
+ * Retrieves a list of tools for a specific MCP server.
3118
+ * @param serverId - The ID of the MCP server.
3119
+ * @returns Promise containing the list of tools.
3120
+ */
3121
+ getMcpServerTools(serverId) {
3122
+ return this.request(`/api/mcp/${serverId}/tools`);
3123
+ }
3124
+ /**
3125
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
3126
+ * This instance can then be used to fetch details or execute the tool.
3127
+ * @param serverId - The ID of the MCP server.
3128
+ * @param toolId - The ID of the tool.
3129
+ * @returns MCPTool instance.
3130
+ */
3131
+ getMcpServerTool(serverId, toolId) {
3132
+ return new MCPTool(this.options, serverId, toolId);
3133
+ }
3134
+ /**
3135
+ * Gets an A2A client for interacting with an agent via the A2A protocol
3136
+ * @param agentId - ID of the agent to interact with
3137
+ * @returns A2A client instance
3138
+ */
3139
+ getA2A(agentId) {
3140
+ return new A2A(this.options, agentId);
3141
+ }
3142
+ /**
3143
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3144
+ * @param agentId - ID of the agent.
3145
+ * @param threadId - ID of the thread.
3146
+ * @param resourceId - Optional ID of the resource.
3147
+ * @returns Working memory for the specified thread or resource.
3148
+ */
3149
+ getWorkingMemory({
3150
+ agentId,
3151
+ threadId,
3152
+ resourceId,
3153
+ requestContext
3154
+ }) {
3155
+ return this.request(
3156
+ `/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}${requestContextQueryString(requestContext, "&")}`
3157
+ );
3158
+ }
3159
+ searchMemory({
3160
+ agentId,
3161
+ resourceId,
3162
+ threadId,
3163
+ searchQuery,
3164
+ memoryConfig,
3165
+ requestContext
3166
+ }) {
3167
+ const params = new URLSearchParams({
3168
+ searchQuery,
3169
+ resourceId,
3170
+ agentId
3171
+ });
3172
+ if (threadId) {
3173
+ params.append("threadId", threadId);
3174
+ }
3175
+ if (memoryConfig) {
3176
+ params.append("memoryConfig", JSON.stringify(memoryConfig));
865
3177
  }
866
- if (_attribute) {
867
- if (Array.isArray(_attribute)) {
868
- for (const attr of _attribute) {
869
- searchParams.append("attribute", attr);
3178
+ return this.request(`/api/memory/search?${params}${requestContextQueryString(requestContext, "&")}`);
3179
+ }
3180
+ /**
3181
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3182
+ * @param agentId - ID of the agent.
3183
+ * @param threadId - ID of the thread.
3184
+ * @param workingMemory - The new working memory content.
3185
+ * @param resourceId - Optional ID of the resource.
3186
+ */
3187
+ updateWorkingMemory({
3188
+ agentId,
3189
+ threadId,
3190
+ workingMemory,
3191
+ resourceId,
3192
+ requestContext
3193
+ }) {
3194
+ return this.request(
3195
+ `/api/memory/threads/${threadId}/working-memory?agentId=${agentId}${requestContextQueryString(requestContext, "&")}`,
3196
+ {
3197
+ method: "POST",
3198
+ body: {
3199
+ workingMemory,
3200
+ resourceId
870
3201
  }
871
- } else {
872
- searchParams.set("attribute", _attribute);
873
3202
  }
3203
+ );
3204
+ }
3205
+ /**
3206
+ * Retrieves all available scorers
3207
+ * @returns Promise containing list of available scorers
3208
+ */
3209
+ listScorers() {
3210
+ return this.request("/api/scores/scorers");
3211
+ }
3212
+ /**
3213
+ * Retrieves a scorer by ID
3214
+ * @param scorerId - ID of the scorer to retrieve
3215
+ * @returns Promise containing the scorer
3216
+ */
3217
+ getScorer(scorerId) {
3218
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3219
+ }
3220
+ getScoresByScorerId(params) {
3221
+ const { page, perPage, scorerId, entityId, entityType } = params;
3222
+ const searchParams = new URLSearchParams();
3223
+ if (entityId) {
3224
+ searchParams.set("entityId", entityId);
874
3225
  }
875
- if (searchParams.size) {
876
- return this.request(`/api/telemetry?${searchParams}`);
877
- } else {
878
- return this.request(`/api/telemetry`);
3226
+ if (entityType) {
3227
+ searchParams.set("entityType", entityType);
3228
+ }
3229
+ if (page !== void 0) {
3230
+ searchParams.set("page", String(page));
3231
+ }
3232
+ if (perPage !== void 0) {
3233
+ searchParams.set("perPage", String(perPage));
3234
+ }
3235
+ const queryString = searchParams.toString();
3236
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3237
+ }
3238
+ /**
3239
+ * Retrieves scores by run ID
3240
+ * @param params - Parameters containing run ID and pagination options
3241
+ * @returns Promise containing scores and pagination info
3242
+ */
3243
+ getScoresByRunId(params) {
3244
+ const { runId, page, perPage } = params;
3245
+ const searchParams = new URLSearchParams();
3246
+ if (page !== void 0) {
3247
+ searchParams.set("page", String(page));
3248
+ }
3249
+ if (perPage !== void 0) {
3250
+ searchParams.set("perPage", String(perPage));
879
3251
  }
3252
+ const queryString = searchParams.toString();
3253
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
880
3254
  }
881
3255
  /**
882
- * Retrieves all available networks
883
- * @returns Promise containing map of network IDs to network details
3256
+ * Retrieves scores by entity ID and type
3257
+ * @param params - Parameters containing entity ID, type, and pagination options
3258
+ * @returns Promise containing scores and pagination info
884
3259
  */
885
- getNetworks() {
886
- return this.request("/api/networks");
3260
+ getScoresByEntityId(params) {
3261
+ const { entityId, entityType, page, perPage } = params;
3262
+ const searchParams = new URLSearchParams();
3263
+ if (page !== void 0) {
3264
+ searchParams.set("page", String(page));
3265
+ }
3266
+ if (perPage !== void 0) {
3267
+ searchParams.set("perPage", String(perPage));
3268
+ }
3269
+ const queryString = searchParams.toString();
3270
+ return this.request(
3271
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3272
+ );
887
3273
  }
888
3274
  /**
889
- * Gets a network instance by ID
890
- * @param networkId - ID of the network to retrieve
891
- * @returns Network instance
3275
+ * Saves a score
3276
+ * @param params - Parameters containing the score data to save
3277
+ * @returns Promise containing the saved score
892
3278
  */
893
- getNetwork(networkId) {
894
- return new Network(this.options, networkId);
3279
+ saveScore(params) {
3280
+ return this.request("/api/scores", {
3281
+ method: "POST",
3282
+ body: params
3283
+ });
3284
+ }
3285
+ getAITrace(traceId) {
3286
+ return this.observability.getTrace(traceId);
3287
+ }
3288
+ getAITraces(params) {
3289
+ return this.observability.getTraces(params);
3290
+ }
3291
+ getScoresBySpan(params) {
3292
+ return this.observability.getScoresBySpan(params);
3293
+ }
3294
+ score(params) {
3295
+ return this.observability.score(params);
3296
+ }
3297
+ };
3298
+
3299
+ // src/tools.ts
3300
+ var ClientTool = class {
3301
+ id;
3302
+ description;
3303
+ inputSchema;
3304
+ outputSchema;
3305
+ execute;
3306
+ constructor(opts) {
3307
+ this.id = opts.id;
3308
+ this.description = opts.description;
3309
+ this.inputSchema = opts.inputSchema;
3310
+ this.outputSchema = opts.outputSchema;
3311
+ this.execute = opts.execute;
895
3312
  }
896
3313
  };
3314
+ function createTool(opts) {
3315
+ return new ClientTool(opts);
3316
+ }
897
3317
 
898
- export { MastraClient };
3318
+ export { ClientTool, MastraClient, createTool };
3319
+ //# sourceMappingURL=index.js.map
3320
+ //# sourceMappingURL=index.js.map