@mastra/client-js 0.0.0-1.x-tester-20251106055847

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