@mastra/client-js 0.0.0-expose-more-playground-ui-20250502141824 → 0.0.0-extract-tool-ui-inp-playground-ui-20251023135343

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