@mastra/client-js 0.0.0-bundle-dynamic-imports-20250424001248 → 0.0.0-chore-core-swap-aiv5-ai-package-naming-20251009203931

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