@mastra/client-js 0.0.0-default-storage-virtual-file-20250410035748 → 0.0.0-dynamic-model-router-20251009231604

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