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