@mastra/client-js 0.0.0-llamaindex-switch-core-20250424001624 → 0.0.0-main-test-20251105183450

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