@mastra/client-js 0.0.0-revert-schema-20250416221206 → 0.0.0-scorers-ui-refactored-20250916094952

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