@mastra/client-js 0.0.0-extend-clickhouse-20250418135620 → 0.0.0-extract-tool-ui-inp-playground-ui-20251024041825

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