@mastra/client-js 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-remove-unused-import-20250909212718

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