@mastra/client-js 0.0.0-pg-pool-options-20250428183821 → 0.0.0-playground-studio-cloud-20251031080052

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