@mastra/client-js 0.0.0-afterToolExecute-20250414225911 → 0.0.0-agent-error-handling-20251023180025

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