@mastra/client-js 0.0.0-commonjs-20250227130920 → 0.0.0-configure-project-root-for-private-packages-20250919100548

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +2818 -4
  2. package/LICENSE.md +15 -0
  3. package/README.md +12 -10
  4. package/dist/client.d.ts +273 -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 +3059 -84
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +5 -405
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +3055 -86
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources/a2a.d.ts +41 -0
  15. package/dist/resources/a2a.d.ts.map +1 -0
  16. package/dist/resources/agent-builder.d.ts +160 -0
  17. package/dist/resources/agent-builder.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +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 +12 -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/observability.d.ts +19 -0
  33. package/dist/resources/observability.d.ts.map +1 -0
  34. package/dist/resources/tool.d.ts +24 -0
  35. package/dist/resources/tool.d.ts.map +1 -0
  36. package/dist/resources/vNextNetwork.d.ts +43 -0
  37. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  38. package/dist/resources/vector.d.ts +51 -0
  39. package/dist/resources/vector.d.ts.map +1 -0
  40. package/dist/resources/workflow.d.ts +254 -0
  41. package/dist/resources/workflow.d.ts.map +1 -0
  42. package/dist/tools.d.ts +22 -0
  43. package/dist/tools.d.ts.map +1 -0
  44. package/dist/types.d.ts +460 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/utils/index.d.ts +5 -0
  47. package/dist/utils/index.d.ts.map +1 -0
  48. package/dist/utils/process-client-tools.d.ts +3 -0
  49. package/dist/utils/process-client-tools.d.ts.map +1 -0
  50. package/dist/utils/process-mastra-stream.d.ts +11 -0
  51. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  52. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  53. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  54. package/package.json +40 -17
  55. package/.turbo/turbo-build.log +0 -19
  56. package/LICENSE +0 -44
  57. package/dist/index.d.cts +0 -405
  58. package/eslint.config.js +0 -6
  59. package/src/client.ts +0 -205
  60. package/src/example.ts +0 -43
  61. package/src/index.test.ts +0 -597
  62. package/src/index.ts +0 -2
  63. package/src/resources/agent.ts +0 -116
  64. package/src/resources/base.ts +0 -68
  65. package/src/resources/index.ts +0 -6
  66. package/src/resources/memory-thread.ts +0 -60
  67. package/src/resources/tool.ts +0 -32
  68. package/src/resources/vector.ts +0 -83
  69. package/src/resources/workflow.ts +0 -68
  70. package/src/types.ts +0 -163
  71. package/tsconfig.json +0 -5
  72. package/vitest.config.js +0 -8
package/dist/index.js CHANGED
@@ -1,7 +1,130 @@
1
- import { ZodSchema } from 'zod';
2
- import { zodToJsonSchema } from 'zod-to-json-schema';
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';
3
7
 
4
8
  // src/resources/agent.ts
9
+ function parseClientRuntimeContext(runtimeContext) {
10
+ if (runtimeContext) {
11
+ if (runtimeContext instanceof RuntimeContext) {
12
+ return Object.fromEntries(runtimeContext.entries());
13
+ }
14
+ return runtimeContext;
15
+ }
16
+ return void 0;
17
+ }
18
+ function base64RuntimeContext(runtimeContext) {
19
+ if (runtimeContext) {
20
+ return btoa(JSON.stringify(runtimeContext));
21
+ }
22
+ return void 0;
23
+ }
24
+ function runtimeContextQueryString(runtimeContext) {
25
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
26
+ if (!runtimeContextParam) return "";
27
+ const searchParams = new URLSearchParams();
28
+ searchParams.set("runtimeContext", runtimeContextParam);
29
+ const queryString = searchParams.toString();
30
+ return queryString ? `?${queryString}` : "";
31
+ }
32
+ function isZodType(value) {
33
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
34
+ }
35
+ function zodToJsonSchema(zodSchema) {
36
+ if (!isZodType(zodSchema)) {
37
+ return zodSchema;
38
+ }
39
+ if ("toJSONSchema" in z) {
40
+ const fn = "toJSONSchema";
41
+ return z[fn].call(z, zodSchema);
42
+ }
43
+ return originalZodToJsonSchema(zodSchema, { $refStrategy: "relative" });
44
+ }
45
+
46
+ // src/utils/process-client-tools.ts
47
+ function processClientTools(clientTools) {
48
+ if (!clientTools) {
49
+ return void 0;
50
+ }
51
+ return Object.fromEntries(
52
+ Object.entries(clientTools).map(([key, value]) => {
53
+ if (isVercelTool(value)) {
54
+ return [
55
+ key,
56
+ {
57
+ ...value,
58
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
59
+ }
60
+ ];
61
+ } else {
62
+ return [
63
+ key,
64
+ {
65
+ ...value,
66
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
67
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
68
+ }
69
+ ];
70
+ }
71
+ })
72
+ );
73
+ }
74
+
75
+ // src/utils/process-mastra-stream.ts
76
+ async function sharedProcessMastraStream({
77
+ stream,
78
+ onChunk
79
+ }) {
80
+ const reader = stream.getReader();
81
+ const decoder = new TextDecoder();
82
+ let buffer = "";
83
+ try {
84
+ while (true) {
85
+ const { done, value } = await reader.read();
86
+ if (done) break;
87
+ buffer += decoder.decode(value, { stream: true });
88
+ const lines = buffer.split("\n\n");
89
+ buffer = lines.pop() || "";
90
+ for (const line of lines) {
91
+ if (line.startsWith("data: ")) {
92
+ const data = line.slice(6);
93
+ if (data === "[DONE]") {
94
+ console.info("\u{1F3C1} Stream finished");
95
+ return;
96
+ }
97
+ try {
98
+ const json = JSON.parse(data);
99
+ await onChunk(json);
100
+ } catch (error) {
101
+ console.error("\u274C JSON parse error:", error, "Data:", data);
102
+ }
103
+ }
104
+ }
105
+ }
106
+ } finally {
107
+ reader.releaseLock();
108
+ }
109
+ }
110
+ async function processMastraNetworkStream({
111
+ stream,
112
+ onChunk
113
+ }) {
114
+ return sharedProcessMastraStream({
115
+ stream,
116
+ onChunk
117
+ });
118
+ }
119
+ async function processMastraStream({
120
+ stream,
121
+ onChunk
122
+ }) {
123
+ return sharedProcessMastraStream({
124
+ stream,
125
+ onChunk
126
+ });
127
+ }
5
128
 
6
129
  // src/resources/base.ts
7
130
  var BaseResource = class {
@@ -17,18 +140,22 @@ var BaseResource = class {
17
140
  */
18
141
  async request(path, options = {}) {
19
142
  let lastError = null;
20
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
143
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
21
144
  let delay = backoffMs;
22
145
  for (let attempt = 0; attempt <= retries; attempt++) {
23
146
  try {
24
- const response = await fetch(`${baseUrl}${path}`, {
147
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
25
148
  ...options,
26
149
  headers: {
27
- "Content-Type": "application/json",
150
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
28
151
  ...headers,
29
152
  ...options.headers
153
+ // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
154
+ // 'x-mastra-client-type': 'js',
30
155
  },
31
- body: options.body ? JSON.stringify(options.body) : void 0
156
+ signal: this.options.abortSignal,
157
+ credentials: options.credentials ?? credentials,
158
+ body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
32
159
  });
33
160
  if (!response.ok) {
34
161
  const errorBody = await response.text();
@@ -62,70 +189,1147 @@ var BaseResource = class {
62
189
  };
63
190
 
64
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
+ }
249
+ var AgentVoice = class extends BaseResource {
250
+ constructor(options, agentId) {
251
+ super(options);
252
+ this.agentId = agentId;
253
+ this.agentId = agentId;
254
+ }
255
+ /**
256
+ * Convert text to speech using the agent's voice provider
257
+ * @param text - Text to convert to speech
258
+ * @param options - Optional provider-specific options for speech generation
259
+ * @returns Promise containing the audio data
260
+ */
261
+ async speak(text, options) {
262
+ return this.request(`/api/agents/${this.agentId}/voice/speak`, {
263
+ method: "POST",
264
+ headers: {
265
+ "Content-Type": "application/json"
266
+ },
267
+ body: { input: text, options },
268
+ stream: true
269
+ });
270
+ }
271
+ /**
272
+ * Convert speech to text using the agent's voice provider
273
+ * @param audio - Audio data to transcribe
274
+ * @param options - Optional provider-specific options
275
+ * @returns Promise containing the transcribed text
276
+ */
277
+ listen(audio, options) {
278
+ const formData = new FormData();
279
+ formData.append("audio", audio);
280
+ if (options) {
281
+ formData.append("options", JSON.stringify(options));
282
+ }
283
+ return this.request(`/api/agents/${this.agentId}/voice/listen`, {
284
+ method: "POST",
285
+ body: formData
286
+ });
287
+ }
288
+ /**
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
292
+ * @returns Promise containing list of available speakers
293
+ */
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)}`);
305
+ }
306
+ };
65
307
  var Agent = class extends BaseResource {
66
308
  constructor(options, agentId) {
67
309
  super(options);
68
310
  this.agentId = agentId;
311
+ this.voice = new AgentVoice(options, this.agentId);
69
312
  }
313
+ voice;
70
314
  /**
71
315
  * Retrieves details about the agent
316
+ * @param runtimeContext - Optional runtime context to pass as query parameter
72
317
  * @returns Promise containing agent details including model and instructions
73
318
  */
74
- details() {
75
- return this.request(`/api/agents/${this.agentId}`);
319
+ details(runtimeContext) {
320
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
76
321
  }
77
- /**
78
- * Generates a response from the agent
79
- * @param params - Generation parameters including prompt
80
- * @returns Promise containing the generated response
81
- */
82
- 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) {
83
329
  const processedParams = {
84
330
  ...params,
85
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.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)
86
335
  };
87
- return this.request(`/api/agents/${this.agentId}/generate`, {
88
- method: "POST",
89
- 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
+ }
90
693
  });
694
+ onFinish?.({ message, finishReason, usage });
91
695
  }
92
696
  /**
93
697
  * Streams a response from the agent
94
698
  * @param params - Stream parameters including prompt
95
- * @returns Promise containing the streamed response
699
+ * @returns Promise containing the enhanced Response object with processDataStream method
96
700
  */
97
- stream(params) {
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) {
713
+ const processedParams = {
714
+ ...params,
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
778
+ };
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`, {
990
+ method: "POST",
991
+ body: processedParams,
992
+ stream: true
993
+ });
994
+ if (!response.body) {
995
+ throw new Error("No response body");
996
+ }
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,
1138
+ ...options
1139
+ };
1140
+ }
98
1141
  const processedParams = {
99
1142
  ...params,
100
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output
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
1164
+ });
101
1165
  };
102
- return this.request(`/api/agents/${this.agentId}/stream`, {
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`, {
103
1173
  method: "POST",
104
1174
  body: processedParams,
105
1175
  stream: true
106
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
+ }
1280
+ return response;
107
1281
  }
108
1282
  /**
109
1283
  * Gets details about a specific tool available to the agent
110
1284
  * @param toolId - ID of the tool to retrieve
1285
+ * @param runtimeContext - Optional runtime context to pass as query parameter
111
1286
  * @returns Promise containing tool details
112
1287
  */
113
- getTool(toolId) {
114
- 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
+ });
115
1306
  }
116
1307
  /**
117
1308
  * Retrieves evaluation results for the agent
1309
+ * @param runtimeContext - Optional runtime context to pass as query parameter
118
1310
  * @returns Promise containing agent evaluations
119
1311
  */
120
- evals() {
121
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1312
+ evals(runtimeContext) {
1313
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
122
1314
  }
123
1315
  /**
124
1316
  * Retrieves live evaluation results for the agent
1317
+ * @param runtimeContext - Optional runtime context to pass as query parameter
125
1318
  * @returns Promise containing live agent evaluations
126
1319
  */
127
- liveEvals() {
128
- 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
+ });
129
1333
  }
130
1334
  };
131
1335
 
@@ -165,10 +1369,45 @@ var MemoryThread = class extends BaseResource {
165
1369
  }
166
1370
  /**
167
1371
  * Retrieves messages associated with the thread
1372
+ * @param params - Optional parameters including limit for number of messages to retrieve
168
1373
  * @returns Promise containing thread messages and UI messages
169
1374
  */
170
- getMessages() {
171
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
1375
+ getMessages(params) {
1376
+ const query = new URLSearchParams({
1377
+ agentId: this.agentId,
1378
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1379
+ });
1380
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
1381
+ }
1382
+ /**
1383
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1384
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1385
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1386
+ */
1387
+ getMessagesPaginated({
1388
+ selectBy,
1389
+ ...rest
1390
+ }) {
1391
+ const query = new URLSearchParams({
1392
+ ...rest,
1393
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1394
+ });
1395
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1396
+ }
1397
+ /**
1398
+ * Deletes one or more messages from the thread
1399
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1400
+ * message object with id property, or array of message objects
1401
+ * @returns Promise containing deletion result
1402
+ */
1403
+ deleteMessages(messageIds) {
1404
+ const query = new URLSearchParams({
1405
+ agentId: this.agentId
1406
+ });
1407
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1408
+ method: "POST",
1409
+ body: { messageIds }
1410
+ });
172
1411
  }
173
1412
  };
174
1413
 
@@ -181,10 +1420,13 @@ var Vector = class extends BaseResource {
181
1420
  /**
182
1421
  * Retrieves details about a specific vector index
183
1422
  * @param indexName - Name of the index to get details for
1423
+ * @param runtimeContext - Optional runtime context to pass as query parameter
184
1424
  * @returns Promise containing vector index details
185
1425
  */
186
- details(indexName) {
187
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1426
+ details(indexName, runtimeContext) {
1427
+ return this.request(
1428
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1429
+ );
188
1430
  }
189
1431
  /**
190
1432
  * Deletes a vector index
@@ -198,10 +1440,11 @@ var Vector = class extends BaseResource {
198
1440
  }
199
1441
  /**
200
1442
  * Retrieves a list of all available indexes
1443
+ * @param runtimeContext - Optional runtime context to pass as query parameter
201
1444
  * @returns Promise containing array of index names
202
1445
  */
203
- getIndexes() {
204
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1446
+ getIndexes(runtimeContext) {
1447
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
205
1448
  }
206
1449
  /**
207
1450
  * Creates a new vector index
@@ -238,99 +1481,1448 @@ var Vector = class extends BaseResource {
238
1481
  }
239
1482
  };
240
1483
 
241
- // src/resources/workflow.ts
242
- var Workflow = class extends BaseResource {
1484
+ // src/resources/legacy-workflow.ts
1485
+ var RECORD_SEPARATOR = "";
1486
+ var LegacyWorkflow = class extends BaseResource {
243
1487
  constructor(options, workflowId) {
244
1488
  super(options);
245
1489
  this.workflowId = workflowId;
246
1490
  }
247
1491
  /**
248
- * Retrieves details about the workflow
249
- * @returns Promise containing workflow details including steps and graphs
1492
+ * Retrieves details about the legacy workflow
1493
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1494
+ * @returns Promise containing legacy workflow details including steps and graphs
250
1495
  */
251
- details() {
252
- return this.request(`/api/workflows/${this.workflowId}`);
1496
+ details(runtimeContext) {
1497
+ return this.request(`/api/workflows/legacy/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
253
1498
  }
254
1499
  /**
255
- * Executes the workflow with the provided parameters
256
- * @param params - Parameters required for workflow execution
257
- * @returns Promise containing the workflow execution results
1500
+ * Retrieves all runs for a legacy workflow
1501
+ * @param params - Parameters for filtering runs
1502
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1503
+ * @returns Promise containing legacy workflow runs array
258
1504
  */
259
- execute(params) {
260
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
1505
+ runs(params, runtimeContext) {
1506
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1507
+ const searchParams = new URLSearchParams();
1508
+ if (params?.fromDate) {
1509
+ searchParams.set("fromDate", params.fromDate.toISOString());
1510
+ }
1511
+ if (params?.toDate) {
1512
+ searchParams.set("toDate", params.toDate.toISOString());
1513
+ }
1514
+ if (params?.limit) {
1515
+ searchParams.set("limit", String(params.limit));
1516
+ }
1517
+ if (params?.offset) {
1518
+ searchParams.set("offset", String(params.offset));
1519
+ }
1520
+ if (params?.resourceId) {
1521
+ searchParams.set("resourceId", params.resourceId);
1522
+ }
1523
+ if (runtimeContextParam) {
1524
+ searchParams.set("runtimeContext", runtimeContextParam);
1525
+ }
1526
+ if (searchParams.size) {
1527
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1528
+ } else {
1529
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1530
+ }
1531
+ }
1532
+ /**
1533
+ * Creates a new legacy workflow run
1534
+ * @returns Promise containing the generated run ID
1535
+ */
1536
+ createRun(params) {
1537
+ const searchParams = new URLSearchParams();
1538
+ if (!!params?.runId) {
1539
+ searchParams.set("runId", params.runId);
1540
+ }
1541
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1542
+ method: "POST"
1543
+ });
1544
+ }
1545
+ /**
1546
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1547
+ * @param params - Object containing the runId and triggerData
1548
+ * @returns Promise containing success message
1549
+ */
1550
+ start(params) {
1551
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
261
1552
  method: "POST",
262
- body: params
1553
+ body: params?.triggerData
263
1554
  });
264
1555
  }
265
1556
  /**
266
- * Resumes a suspended workflow step
1557
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
267
1558
  * @param stepId - ID of the step to resume
268
- * @param runId - ID of the workflow run
269
- * @param context - Context to resume the workflow with
270
- * @returns Promise containing the workflow resume results
1559
+ * @param runId - ID of the legacy workflow run
1560
+ * @param context - Context to resume the legacy workflow with
1561
+ * @returns Promise containing the legacy workflow resume results
271
1562
  */
272
1563
  resume({
273
1564
  stepId,
274
1565
  runId,
275
1566
  context
276
1567
  }) {
277
- return this.request(`/api/workflows/${this.workflowId}/resume`, {
1568
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
278
1569
  method: "POST",
279
1570
  body: {
280
1571
  stepId,
281
- runId,
282
1572
  context
283
1573
  }
284
1574
  });
285
1575
  }
286
1576
  /**
287
- * Watches workflow transitions in real-time
288
- * @returns Promise containing the workflow watch stream
1577
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1578
+ * @param params - Object containing the optional runId and triggerData
1579
+ * @returns Promise containing the workflow execution results
289
1580
  */
290
- watch() {
291
- return this.request(`/api/workflows/${this.workflowId}/watch`, {
292
- stream: true
1581
+ startAsync(params) {
1582
+ const searchParams = new URLSearchParams();
1583
+ if (!!params?.runId) {
1584
+ searchParams.set("runId", params.runId);
1585
+ }
1586
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1587
+ method: "POST",
1588
+ body: params?.triggerData
293
1589
  });
294
1590
  }
295
- };
296
-
297
- // src/resources/tool.ts
298
- var Tool = class extends BaseResource {
299
- constructor(options, toolId) {
300
- super(options);
301
- this.toolId = toolId;
302
- }
1591
+ /**
1592
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1593
+ * @param params - Object containing the runId, stepId, and context
1594
+ * @returns Promise containing the workflow resume results
1595
+ */
1596
+ resumeAsync(params) {
1597
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1598
+ method: "POST",
1599
+ body: {
1600
+ stepId: params.stepId,
1601
+ context: params.context
1602
+ }
1603
+ });
1604
+ }
1605
+ /**
1606
+ * Creates an async generator that processes a readable stream and yields records
1607
+ * separated by the Record Separator character (\x1E)
1608
+ *
1609
+ * @param stream - The readable stream to process
1610
+ * @returns An async generator that yields parsed records
1611
+ */
1612
+ async *streamProcessor(stream) {
1613
+ const reader = stream.getReader();
1614
+ let doneReading = false;
1615
+ let buffer = "";
1616
+ try {
1617
+ while (!doneReading) {
1618
+ const { done, value } = await reader.read();
1619
+ doneReading = done;
1620
+ if (done && !value) continue;
1621
+ try {
1622
+ const decoded = value ? new TextDecoder().decode(value) : "";
1623
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1624
+ buffer = chunks.pop() || "";
1625
+ for (const chunk of chunks) {
1626
+ if (chunk) {
1627
+ if (typeof chunk === "string") {
1628
+ try {
1629
+ const parsedChunk = JSON.parse(chunk);
1630
+ yield parsedChunk;
1631
+ } catch {
1632
+ }
1633
+ }
1634
+ }
1635
+ }
1636
+ } catch {
1637
+ }
1638
+ }
1639
+ if (buffer) {
1640
+ try {
1641
+ yield JSON.parse(buffer);
1642
+ } catch {
1643
+ }
1644
+ }
1645
+ } finally {
1646
+ reader.cancel().catch(() => {
1647
+ });
1648
+ }
1649
+ }
1650
+ /**
1651
+ * Watches legacy workflow transitions in real-time
1652
+ * @param runId - Optional run ID to filter the watch stream
1653
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1654
+ */
1655
+ async watch({ runId }, onRecord) {
1656
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1657
+ stream: true
1658
+ });
1659
+ if (!response.ok) {
1660
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1661
+ }
1662
+ if (!response.body) {
1663
+ throw new Error("Response body is null");
1664
+ }
1665
+ for await (const record of this.streamProcessor(response.body)) {
1666
+ onRecord(record);
1667
+ }
1668
+ }
1669
+ };
1670
+
1671
+ // src/resources/tool.ts
1672
+ var Tool = class extends BaseResource {
1673
+ constructor(options, toolId) {
1674
+ super(options);
1675
+ this.toolId = toolId;
1676
+ }
303
1677
  /**
304
1678
  * Retrieves details about the tool
1679
+ * @param runtimeContext - Optional runtime context to pass as query parameter
305
1680
  * @returns Promise containing tool details including description and schemas
306
1681
  */
307
- details() {
308
- return this.request(`/api/tools/${this.toolId}`);
1682
+ details(runtimeContext) {
1683
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1684
+ }
1685
+ /**
1686
+ * Executes the tool with the provided parameters
1687
+ * @param params - Parameters required for tool execution
1688
+ * @returns Promise containing the tool execution results
1689
+ */
1690
+ execute(params) {
1691
+ const url = new URLSearchParams();
1692
+ if (params.runId) {
1693
+ url.set("runId", params.runId);
1694
+ }
1695
+ const body = {
1696
+ data: params.data,
1697
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1698
+ };
1699
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1700
+ method: "POST",
1701
+ body
1702
+ });
1703
+ }
1704
+ };
1705
+
1706
+ // src/resources/workflow.ts
1707
+ var RECORD_SEPARATOR2 = "";
1708
+ var Workflow = class extends BaseResource {
1709
+ constructor(options, workflowId) {
1710
+ super(options);
1711
+ this.workflowId = workflowId;
1712
+ }
1713
+ /**
1714
+ * Creates an async generator that processes a readable stream and yields workflow records
1715
+ * separated by the Record Separator character (\x1E)
1716
+ *
1717
+ * @param stream - The readable stream to process
1718
+ * @returns An async generator that yields parsed records
1719
+ */
1720
+ async *streamProcessor(stream) {
1721
+ const reader = stream.getReader();
1722
+ let doneReading = false;
1723
+ let buffer = "";
1724
+ try {
1725
+ while (!doneReading) {
1726
+ const { done, value } = await reader.read();
1727
+ doneReading = done;
1728
+ if (done && !value) continue;
1729
+ try {
1730
+ const decoded = value ? new TextDecoder().decode(value) : "";
1731
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1732
+ buffer = chunks.pop() || "";
1733
+ for (const chunk of chunks) {
1734
+ if (chunk) {
1735
+ if (typeof chunk === "string") {
1736
+ try {
1737
+ const parsedChunk = JSON.parse(chunk);
1738
+ yield parsedChunk;
1739
+ } catch {
1740
+ }
1741
+ }
1742
+ }
1743
+ }
1744
+ } catch {
1745
+ }
1746
+ }
1747
+ if (buffer) {
1748
+ try {
1749
+ yield JSON.parse(buffer);
1750
+ } catch {
1751
+ }
1752
+ }
1753
+ } finally {
1754
+ reader.cancel().catch(() => {
1755
+ });
1756
+ }
1757
+ }
1758
+ /**
1759
+ * Retrieves details about the workflow
1760
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1761
+ * @returns Promise containing workflow details including steps and graphs
1762
+ */
1763
+ details(runtimeContext) {
1764
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1765
+ }
1766
+ /**
1767
+ * Retrieves all runs for a workflow
1768
+ * @param params - Parameters for filtering runs
1769
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1770
+ * @returns Promise containing workflow runs array
1771
+ */
1772
+ runs(params, runtimeContext) {
1773
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1774
+ const searchParams = new URLSearchParams();
1775
+ if (params?.fromDate) {
1776
+ searchParams.set("fromDate", params.fromDate.toISOString());
1777
+ }
1778
+ if (params?.toDate) {
1779
+ searchParams.set("toDate", params.toDate.toISOString());
1780
+ }
1781
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1782
+ searchParams.set("limit", String(params.limit));
1783
+ }
1784
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1785
+ searchParams.set("offset", String(params.offset));
1786
+ }
1787
+ if (params?.resourceId) {
1788
+ searchParams.set("resourceId", params.resourceId);
1789
+ }
1790
+ if (runtimeContextParam) {
1791
+ searchParams.set("runtimeContext", runtimeContextParam);
1792
+ }
1793
+ if (searchParams.size) {
1794
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1795
+ } else {
1796
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1797
+ }
1798
+ }
1799
+ /**
1800
+ * Retrieves a specific workflow run by its ID
1801
+ * @param runId - The ID of the workflow run to retrieve
1802
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1803
+ * @returns Promise containing the workflow run details
1804
+ */
1805
+ runById(runId, runtimeContext) {
1806
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1807
+ }
1808
+ /**
1809
+ * Retrieves the execution result for a specific workflow run by its ID
1810
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1811
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1812
+ * @returns Promise containing the workflow run execution result
1813
+ */
1814
+ runExecutionResult(runId, runtimeContext) {
1815
+ return this.request(
1816
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1817
+ );
1818
+ }
1819
+ /**
1820
+ * Cancels a specific workflow run by its ID
1821
+ * @param runId - The ID of the workflow run to cancel
1822
+ * @returns Promise containing a success message
1823
+ */
1824
+ cancelRun(runId) {
1825
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1826
+ method: "POST"
1827
+ });
1828
+ }
1829
+ /**
1830
+ * Sends an event to a specific workflow run by its ID
1831
+ * @param params - Object containing the runId, event and data
1832
+ * @returns Promise containing a success message
1833
+ */
1834
+ sendRunEvent(params) {
1835
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1836
+ method: "POST",
1837
+ body: { event: params.event, data: params.data }
1838
+ });
1839
+ }
1840
+ /**
1841
+ * @deprecated Use createRunAsync() instead.
1842
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1843
+ */
1844
+ async createRun(_params) {
1845
+ throw new Error(
1846
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = workflow.createRun();\n After: const run = await workflow.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
1847
+ );
1848
+ }
1849
+ /**
1850
+ * Creates a new workflow run
1851
+ * @param params - Optional object containing the optional runId
1852
+ * @returns Promise containing the runId of the created run with methods to control execution
1853
+ */
1854
+ async createRunAsync(params) {
1855
+ const searchParams = new URLSearchParams();
1856
+ if (!!params?.runId) {
1857
+ searchParams.set("runId", params.runId);
1858
+ }
1859
+ const res = await this.request(
1860
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1861
+ {
1862
+ method: "POST"
1863
+ }
1864
+ );
1865
+ const runId = res.runId;
1866
+ return {
1867
+ runId,
1868
+ start: async (p) => {
1869
+ return this.start({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1870
+ },
1871
+ startAsync: async (p) => {
1872
+ return this.startAsync({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1873
+ },
1874
+ watch: async (onRecord) => {
1875
+ return this.watch({ runId }, onRecord);
1876
+ },
1877
+ stream: async (p) => {
1878
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1879
+ },
1880
+ resume: async (p) => {
1881
+ return this.resume({ runId, step: p.step, resumeData: p.resumeData, runtimeContext: p.runtimeContext });
1882
+ },
1883
+ resumeAsync: async (p) => {
1884
+ return this.resumeAsync({ runId, step: p.step, resumeData: p.resumeData, runtimeContext: p.runtimeContext });
1885
+ },
1886
+ resumeStreamVNext: async (p) => {
1887
+ return this.resumeStreamVNext({
1888
+ runId,
1889
+ step: p.step,
1890
+ resumeData: p.resumeData,
1891
+ runtimeContext: p.runtimeContext
1892
+ });
1893
+ }
1894
+ };
1895
+ }
1896
+ /**
1897
+ * Starts a workflow run synchronously without waiting for the workflow to complete
1898
+ * @param params - Object containing the runId, inputData and runtimeContext
1899
+ * @returns Promise containing success message
1900
+ */
1901
+ start(params) {
1902
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1903
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1904
+ method: "POST",
1905
+ body: { inputData: params?.inputData, runtimeContext }
1906
+ });
1907
+ }
1908
+ /**
1909
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1910
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1911
+ * @returns Promise containing success message
1912
+ */
1913
+ resume({
1914
+ step,
1915
+ runId,
1916
+ resumeData,
1917
+ ...rest
1918
+ }) {
1919
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1920
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1921
+ method: "POST",
1922
+ body: {
1923
+ step,
1924
+ resumeData,
1925
+ runtimeContext
1926
+ }
1927
+ });
1928
+ }
1929
+ /**
1930
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1931
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1932
+ * @returns Promise containing the workflow execution results
1933
+ */
1934
+ startAsync(params) {
1935
+ const searchParams = new URLSearchParams();
1936
+ if (!!params?.runId) {
1937
+ searchParams.set("runId", params.runId);
1938
+ }
1939
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1940
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1941
+ method: "POST",
1942
+ body: { inputData: params.inputData, runtimeContext }
1943
+ });
1944
+ }
1945
+ /**
1946
+ * Starts a workflow run and returns a stream
1947
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1948
+ * @returns Promise containing the workflow execution results
1949
+ */
1950
+ async stream(params) {
1951
+ const searchParams = new URLSearchParams();
1952
+ if (!!params?.runId) {
1953
+ searchParams.set("runId", params.runId);
1954
+ }
1955
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1956
+ const response = await this.request(
1957
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1958
+ {
1959
+ method: "POST",
1960
+ body: { inputData: params.inputData, runtimeContext },
1961
+ stream: true
1962
+ }
1963
+ );
1964
+ if (!response.ok) {
1965
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1966
+ }
1967
+ if (!response.body) {
1968
+ throw new Error("Response body is null");
1969
+ }
1970
+ let failedChunk = void 0;
1971
+ const transformStream = new TransformStream({
1972
+ start() {
1973
+ },
1974
+ async transform(chunk, controller) {
1975
+ try {
1976
+ const decoded = new TextDecoder().decode(chunk);
1977
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1978
+ for (const chunk2 of chunks) {
1979
+ if (chunk2) {
1980
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1981
+ try {
1982
+ const parsedChunk = JSON.parse(newChunk);
1983
+ controller.enqueue(parsedChunk);
1984
+ failedChunk = void 0;
1985
+ } catch {
1986
+ failedChunk = newChunk;
1987
+ }
1988
+ }
1989
+ }
1990
+ } catch {
1991
+ }
1992
+ }
1993
+ });
1994
+ return response.body.pipeThrough(transformStream);
1995
+ }
1996
+ /**
1997
+ * Observes workflow stream for a workflow run
1998
+ * @param params - Object containing the runId
1999
+ * @returns Promise containing the workflow execution results
2000
+ */
2001
+ async observeStream(params) {
2002
+ const searchParams = new URLSearchParams();
2003
+ searchParams.set("runId", params.runId);
2004
+ const response = await this.request(
2005
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
2006
+ {
2007
+ method: "POST",
2008
+ stream: true
2009
+ }
2010
+ );
2011
+ if (!response.ok) {
2012
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
2013
+ }
2014
+ if (!response.body) {
2015
+ throw new Error("Response body is null");
2016
+ }
2017
+ let failedChunk = void 0;
2018
+ const transformStream = new TransformStream({
2019
+ start() {
2020
+ },
2021
+ async transform(chunk, controller) {
2022
+ try {
2023
+ const decoded = new TextDecoder().decode(chunk);
2024
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2025
+ for (const chunk2 of chunks) {
2026
+ if (chunk2) {
2027
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2028
+ try {
2029
+ const parsedChunk = JSON.parse(newChunk);
2030
+ controller.enqueue(parsedChunk);
2031
+ failedChunk = void 0;
2032
+ } catch {
2033
+ failedChunk = newChunk;
2034
+ }
2035
+ }
2036
+ }
2037
+ } catch {
2038
+ }
2039
+ }
2040
+ });
2041
+ return response.body.pipeThrough(transformStream);
2042
+ }
2043
+ /**
2044
+ * Starts a workflow run and returns a stream
2045
+ * @param params - Object containing the optional runId, inputData and runtimeContext
2046
+ * @returns Promise containing the workflow execution results
2047
+ */
2048
+ async streamVNext(params) {
2049
+ const searchParams = new URLSearchParams();
2050
+ if (!!params?.runId) {
2051
+ searchParams.set("runId", params.runId);
2052
+ }
2053
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2054
+ const response = await this.request(
2055
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
2056
+ {
2057
+ method: "POST",
2058
+ body: { inputData: params.inputData, runtimeContext, closeOnSuspend: params.closeOnSuspend },
2059
+ stream: true
2060
+ }
2061
+ );
2062
+ if (!response.ok) {
2063
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2064
+ }
2065
+ if (!response.body) {
2066
+ throw new Error("Response body is null");
2067
+ }
2068
+ let failedChunk = void 0;
2069
+ const transformStream = new TransformStream({
2070
+ start() {
2071
+ },
2072
+ async transform(chunk, controller) {
2073
+ try {
2074
+ const decoded = new TextDecoder().decode(chunk);
2075
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2076
+ for (const chunk2 of chunks) {
2077
+ if (chunk2) {
2078
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2079
+ try {
2080
+ const parsedChunk = JSON.parse(newChunk);
2081
+ controller.enqueue(parsedChunk);
2082
+ failedChunk = void 0;
2083
+ } catch {
2084
+ failedChunk = newChunk;
2085
+ }
2086
+ }
2087
+ }
2088
+ } catch {
2089
+ }
2090
+ }
2091
+ });
2092
+ return response.body.pipeThrough(transformStream);
2093
+ }
2094
+ /**
2095
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2096
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2097
+ * @returns Promise containing the workflow resume results
2098
+ */
2099
+ resumeAsync(params) {
2100
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2101
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2102
+ method: "POST",
2103
+ body: {
2104
+ step: params.step,
2105
+ resumeData: params.resumeData,
2106
+ runtimeContext
2107
+ }
2108
+ });
2109
+ }
2110
+ /**
2111
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2112
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2113
+ * @returns Promise containing the workflow resume results
2114
+ */
2115
+ resumeStreamVNext(params) {
2116
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2117
+ return this.request(`/api/workflows/${this.workflowId}/resume-stream?runId=${params.runId}`, {
2118
+ method: "POST",
2119
+ body: {
2120
+ step: params.step,
2121
+ resumeData: params.resumeData,
2122
+ runtimeContext
2123
+ }
2124
+ });
2125
+ }
2126
+ /**
2127
+ * Watches workflow transitions in real-time
2128
+ * @param runId - Optional run ID to filter the watch stream
2129
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2130
+ */
2131
+ async watch({ runId }, onRecord) {
2132
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2133
+ stream: true
2134
+ });
2135
+ if (!response.ok) {
2136
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
2137
+ }
2138
+ if (!response.body) {
2139
+ throw new Error("Response body is null");
2140
+ }
2141
+ for await (const record of this.streamProcessor(response.body)) {
2142
+ if (typeof record === "string") {
2143
+ onRecord(JSON.parse(record));
2144
+ } else {
2145
+ onRecord(record);
2146
+ }
2147
+ }
2148
+ }
2149
+ /**
2150
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2151
+ * serializing each as JSON and separating them with the record separator (\x1E).
2152
+ *
2153
+ * @param records - An iterable or async iterable of objects to stream
2154
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2155
+ */
2156
+ static createRecordStream(records) {
2157
+ const encoder = new TextEncoder();
2158
+ return new ReadableStream({
2159
+ async start(controller) {
2160
+ try {
2161
+ for await (const record of records) {
2162
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2163
+ controller.enqueue(encoder.encode(json));
2164
+ }
2165
+ controller.close();
2166
+ } catch (err) {
2167
+ controller.error(err);
2168
+ }
2169
+ }
2170
+ });
2171
+ }
2172
+ };
2173
+
2174
+ // src/resources/a2a.ts
2175
+ var A2A = class extends BaseResource {
2176
+ constructor(options, agentId) {
2177
+ super(options);
2178
+ this.agentId = agentId;
2179
+ }
2180
+ /**
2181
+ * Get the agent card with metadata about the agent
2182
+ * @returns Promise containing the agent card information
2183
+ */
2184
+ async getCard() {
2185
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2186
+ }
2187
+ /**
2188
+ * Send a message to the agent and gets a message or task response
2189
+ * @param params - Parameters for the task
2190
+ * @returns Promise containing the response
2191
+ */
2192
+ async sendMessage(params) {
2193
+ const response = await this.request(`/a2a/${this.agentId}`, {
2194
+ method: "POST",
2195
+ body: {
2196
+ method: "message/send",
2197
+ params
2198
+ }
2199
+ });
2200
+ return response;
2201
+ }
2202
+ /**
2203
+ * Sends a message to an agent to initiate/continue a task and subscribes
2204
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2205
+ * @param params - Parameters for the task
2206
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2207
+ */
2208
+ async sendStreamingMessage(params) {
2209
+ const response = await this.request(`/a2a/${this.agentId}`, {
2210
+ method: "POST",
2211
+ body: {
2212
+ method: "message/stream",
2213
+ params
2214
+ }
2215
+ });
2216
+ return response;
2217
+ }
2218
+ /**
2219
+ * Get the status and result of a task
2220
+ * @param params - Parameters for querying the task
2221
+ * @returns Promise containing the task response
2222
+ */
2223
+ async getTask(params) {
2224
+ const response = await this.request(`/a2a/${this.agentId}`, {
2225
+ method: "POST",
2226
+ body: {
2227
+ method: "tasks/get",
2228
+ params
2229
+ }
2230
+ });
2231
+ return response;
2232
+ }
2233
+ /**
2234
+ * Cancel a running task
2235
+ * @param params - Parameters identifying the task to cancel
2236
+ * @returns Promise containing the task response
2237
+ */
2238
+ async cancelTask(params) {
2239
+ return this.request(`/a2a/${this.agentId}`, {
2240
+ method: "POST",
2241
+ body: {
2242
+ method: "tasks/cancel",
2243
+ params
2244
+ }
2245
+ });
2246
+ }
2247
+ };
2248
+
2249
+ // src/resources/mcp-tool.ts
2250
+ var MCPTool = class extends BaseResource {
2251
+ serverId;
2252
+ toolId;
2253
+ constructor(options, serverId, toolId) {
2254
+ super(options);
2255
+ this.serverId = serverId;
2256
+ this.toolId = toolId;
2257
+ }
2258
+ /**
2259
+ * Retrieves details about this specific tool from the MCP server.
2260
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2261
+ * @returns Promise containing the tool's information (name, description, schema).
2262
+ */
2263
+ details(runtimeContext) {
2264
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2265
+ }
2266
+ /**
2267
+ * Executes this specific tool on the MCP server.
2268
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2269
+ * @returns Promise containing the result of the tool execution.
2270
+ */
2271
+ execute(params) {
2272
+ const body = {};
2273
+ if (params.data !== void 0) body.data = params.data;
2274
+ if (params.runtimeContext !== void 0) {
2275
+ body.runtimeContext = params.runtimeContext;
2276
+ }
2277
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2278
+ method: "POST",
2279
+ body: Object.keys(body).length > 0 ? body : void 0
2280
+ });
2281
+ }
2282
+ };
2283
+
2284
+ // src/resources/agent-builder.ts
2285
+ var RECORD_SEPARATOR3 = "";
2286
+ var AgentBuilder = class extends BaseResource {
2287
+ constructor(options, actionId) {
2288
+ super(options);
2289
+ this.actionId = actionId;
2290
+ }
2291
+ // Helper function to transform workflow result to action result
2292
+ transformWorkflowResult(result) {
2293
+ if (result.status === "success") {
2294
+ return {
2295
+ success: result.result.success || false,
2296
+ applied: result.result.applied || false,
2297
+ branchName: result.result.branchName,
2298
+ message: result.result.message || "Agent builder action completed",
2299
+ validationResults: result.result.validationResults,
2300
+ error: result.result.error,
2301
+ errors: result.result.errors,
2302
+ stepResults: result.result.stepResults
2303
+ };
2304
+ } else if (result.status === "failed") {
2305
+ return {
2306
+ success: false,
2307
+ applied: false,
2308
+ message: `Agent builder action failed: ${result.error.message}`,
2309
+ error: result.error.message
2310
+ };
2311
+ } else {
2312
+ return {
2313
+ success: false,
2314
+ applied: false,
2315
+ message: "Agent builder action was suspended",
2316
+ error: "Workflow suspended - manual intervention required"
2317
+ };
2318
+ }
2319
+ }
2320
+ /**
2321
+ * @deprecated Use createRunAsync() instead.
2322
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2323
+ */
2324
+ async createRun(_params) {
2325
+ throw new Error(
2326
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = agentBuilder.createRun();\n After: const run = await agentBuilder.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
2327
+ );
2328
+ }
2329
+ /**
2330
+ * Creates a new agent builder action run and returns the runId.
2331
+ * This calls `/api/agent-builder/:actionId/create-run`.
2332
+ */
2333
+ async createRunAsync(params) {
2334
+ const searchParams = new URLSearchParams();
2335
+ if (!!params?.runId) {
2336
+ searchParams.set("runId", params.runId);
2337
+ }
2338
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2339
+ return this.request(url, {
2340
+ method: "POST"
2341
+ });
2342
+ }
2343
+ /**
2344
+ * Starts agent builder action asynchronously and waits for completion.
2345
+ * This calls `/api/agent-builder/:actionId/start-async`.
2346
+ */
2347
+ async startAsync(params, runId) {
2348
+ const searchParams = new URLSearchParams();
2349
+ if (runId) {
2350
+ searchParams.set("runId", runId);
2351
+ }
2352
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2353
+ const { runtimeContext: _, ...actionParams } = params;
2354
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2355
+ const result = await this.request(url, {
2356
+ method: "POST",
2357
+ body: { ...actionParams, runtimeContext }
2358
+ });
2359
+ return this.transformWorkflowResult(result);
2360
+ }
2361
+ /**
2362
+ * Starts an existing agent builder action run.
2363
+ * This calls `/api/agent-builder/:actionId/start`.
2364
+ */
2365
+ async startActionRun(params, runId) {
2366
+ const searchParams = new URLSearchParams();
2367
+ searchParams.set("runId", runId);
2368
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2369
+ const { runtimeContext: _, ...actionParams } = params;
2370
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2371
+ return this.request(url, {
2372
+ method: "POST",
2373
+ body: { ...actionParams, runtimeContext }
2374
+ });
2375
+ }
2376
+ /**
2377
+ * Resumes a suspended agent builder action step.
2378
+ * This calls `/api/agent-builder/:actionId/resume`.
2379
+ */
2380
+ async resume(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?${searchParams.toString()}`;
2386
+ return this.request(url, {
2387
+ method: "POST",
2388
+ body: { ...resumeParams, runtimeContext }
2389
+ });
2390
+ }
2391
+ /**
2392
+ * Resumes a suspended agent builder action step asynchronously.
2393
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2394
+ */
2395
+ async resumeAsync(params, runId) {
2396
+ const searchParams = new URLSearchParams();
2397
+ searchParams.set("runId", runId);
2398
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2399
+ const { runtimeContext: _, ...resumeParams } = params;
2400
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2401
+ const result = await this.request(url, {
2402
+ method: "POST",
2403
+ body: { ...resumeParams, runtimeContext }
2404
+ });
2405
+ return this.transformWorkflowResult(result);
2406
+ }
2407
+ /**
2408
+ * Creates an async generator that processes a readable stream and yields action records
2409
+ * separated by the Record Separator character (\x1E)
2410
+ *
2411
+ * @param stream - The readable stream to process
2412
+ * @returns An async generator that yields parsed records
2413
+ */
2414
+ async *streamProcessor(stream) {
2415
+ const reader = stream.getReader();
2416
+ let doneReading = false;
2417
+ let buffer = "";
2418
+ try {
2419
+ while (!doneReading) {
2420
+ const { done, value } = await reader.read();
2421
+ doneReading = done;
2422
+ if (done && !value) continue;
2423
+ try {
2424
+ const decoded = value ? new TextDecoder().decode(value) : "";
2425
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2426
+ buffer = chunks.pop() || "";
2427
+ for (const chunk of chunks) {
2428
+ if (chunk) {
2429
+ if (typeof chunk === "string") {
2430
+ try {
2431
+ const parsedChunk = JSON.parse(chunk);
2432
+ yield parsedChunk;
2433
+ } catch {
2434
+ }
2435
+ }
2436
+ }
2437
+ }
2438
+ } catch {
2439
+ }
2440
+ }
2441
+ if (buffer) {
2442
+ try {
2443
+ yield JSON.parse(buffer);
2444
+ } catch {
2445
+ }
2446
+ }
2447
+ } finally {
2448
+ reader.cancel().catch(() => {
2449
+ });
2450
+ }
2451
+ }
2452
+ /**
2453
+ * Streams agent builder action progress in real-time.
2454
+ * This calls `/api/agent-builder/:actionId/stream`.
2455
+ */
2456
+ async stream(params, runId) {
2457
+ const searchParams = new URLSearchParams();
2458
+ if (runId) {
2459
+ searchParams.set("runId", runId);
2460
+ }
2461
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2462
+ const { runtimeContext: _, ...actionParams } = params;
2463
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2464
+ const response = await this.request(url, {
2465
+ method: "POST",
2466
+ body: { ...actionParams, runtimeContext },
2467
+ stream: true
2468
+ });
2469
+ if (!response.ok) {
2470
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2471
+ }
2472
+ if (!response.body) {
2473
+ throw new Error("Response body is null");
2474
+ }
2475
+ let failedChunk = void 0;
2476
+ const transformStream = new TransformStream({
2477
+ start() {
2478
+ },
2479
+ async transform(chunk, controller) {
2480
+ try {
2481
+ const decoded = new TextDecoder().decode(chunk);
2482
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2483
+ for (const chunk2 of chunks) {
2484
+ if (chunk2) {
2485
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2486
+ try {
2487
+ const parsedChunk = JSON.parse(newChunk);
2488
+ controller.enqueue(parsedChunk);
2489
+ failedChunk = void 0;
2490
+ } catch {
2491
+ failedChunk = newChunk;
2492
+ }
2493
+ }
2494
+ }
2495
+ } catch {
2496
+ }
2497
+ }
2498
+ });
2499
+ return response.body.pipeThrough(transformStream);
2500
+ }
2501
+ /**
2502
+ * Streams agent builder action progress in real-time using VNext streaming.
2503
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2504
+ */
2505
+ async streamVNext(params, runId) {
2506
+ const searchParams = new URLSearchParams();
2507
+ if (runId) {
2508
+ searchParams.set("runId", runId);
2509
+ }
2510
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2511
+ const { runtimeContext: _, ...actionParams } = params;
2512
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2513
+ const response = await this.request(url, {
2514
+ method: "POST",
2515
+ body: { ...actionParams, runtimeContext },
2516
+ stream: true
2517
+ });
2518
+ if (!response.ok) {
2519
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2520
+ }
2521
+ if (!response.body) {
2522
+ throw new Error("Response body is null");
2523
+ }
2524
+ let failedChunk = void 0;
2525
+ const transformStream = new TransformStream({
2526
+ start() {
2527
+ },
2528
+ async transform(chunk, controller) {
2529
+ try {
2530
+ const decoded = new TextDecoder().decode(chunk);
2531
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2532
+ for (const chunk2 of chunks) {
2533
+ if (chunk2) {
2534
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2535
+ try {
2536
+ const parsedChunk = JSON.parse(newChunk);
2537
+ controller.enqueue(parsedChunk);
2538
+ failedChunk = void 0;
2539
+ } catch {
2540
+ failedChunk = newChunk;
2541
+ }
2542
+ }
2543
+ }
2544
+ } catch {
2545
+ }
2546
+ }
2547
+ });
2548
+ return response.body.pipeThrough(transformStream);
2549
+ }
2550
+ /**
2551
+ * Watches an existing agent builder action run by runId.
2552
+ * This is used for hot reload recovery - it loads the existing run state
2553
+ * and streams any remaining progress.
2554
+ * This calls `/api/agent-builder/:actionId/watch`.
2555
+ */
2556
+ async watch({ runId, eventType }, onRecord) {
2557
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2558
+ const response = await this.request(url, {
2559
+ method: "GET",
2560
+ stream: true
2561
+ });
2562
+ if (!response.ok) {
2563
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2564
+ }
2565
+ if (!response.body) {
2566
+ throw new Error("Response body is null");
2567
+ }
2568
+ for await (const record of this.streamProcessor(response.body)) {
2569
+ if (typeof record === "string") {
2570
+ onRecord(JSON.parse(record));
2571
+ } else {
2572
+ onRecord(record);
2573
+ }
2574
+ }
2575
+ }
2576
+ /**
2577
+ * Gets a specific action run by its ID.
2578
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2579
+ */
2580
+ async runById(runId) {
2581
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2582
+ return this.request(url, {
2583
+ method: "GET"
2584
+ });
2585
+ }
2586
+ /**
2587
+ * Gets details about this agent builder action.
2588
+ * This calls `/api/agent-builder/:actionId`.
2589
+ */
2590
+ async details() {
2591
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2592
+ return result;
2593
+ }
2594
+ /**
2595
+ * Gets all runs for this agent builder action.
2596
+ * This calls `/api/agent-builder/:actionId/runs`.
2597
+ */
2598
+ async runs(params) {
2599
+ const searchParams = new URLSearchParams();
2600
+ if (params?.fromDate) {
2601
+ searchParams.set("fromDate", params.fromDate.toISOString());
2602
+ }
2603
+ if (params?.toDate) {
2604
+ searchParams.set("toDate", params.toDate.toISOString());
2605
+ }
2606
+ if (params?.limit !== void 0) {
2607
+ searchParams.set("limit", String(params.limit));
2608
+ }
2609
+ if (params?.offset !== void 0) {
2610
+ searchParams.set("offset", String(params.offset));
2611
+ }
2612
+ if (params?.resourceId) {
2613
+ searchParams.set("resourceId", params.resourceId);
2614
+ }
2615
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2616
+ return this.request(url, {
2617
+ method: "GET"
2618
+ });
2619
+ }
2620
+ /**
2621
+ * Gets the execution result of an agent builder action run.
2622
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2623
+ */
2624
+ async runExecutionResult(runId) {
2625
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2626
+ return this.request(url, {
2627
+ method: "GET"
2628
+ });
2629
+ }
2630
+ /**
2631
+ * Cancels an agent builder action run.
2632
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2633
+ */
2634
+ async cancelRun(runId) {
2635
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2636
+ return this.request(url, {
2637
+ method: "POST"
2638
+ });
2639
+ }
2640
+ /**
2641
+ * Sends an event to an agent builder action run.
2642
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2643
+ */
2644
+ async sendRunEvent(params) {
2645
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2646
+ return this.request(url, {
2647
+ method: "POST",
2648
+ body: { event: params.event, data: params.data }
2649
+ });
2650
+ }
2651
+ };
2652
+
2653
+ // src/resources/observability.ts
2654
+ var Observability = class extends BaseResource {
2655
+ constructor(options) {
2656
+ super(options);
2657
+ }
2658
+ /**
2659
+ * Retrieves a specific AI trace by ID
2660
+ * @param traceId - ID of the trace to retrieve
2661
+ * @returns Promise containing the AI trace with all its spans
2662
+ */
2663
+ getTrace(traceId) {
2664
+ return this.request(`/api/observability/traces/${traceId}`);
2665
+ }
2666
+ /**
2667
+ * Retrieves paginated list of AI traces with optional filtering
2668
+ * @param params - Parameters for pagination and filtering
2669
+ * @returns Promise containing paginated traces and pagination info
2670
+ */
2671
+ getTraces(params) {
2672
+ const { pagination, filters } = params;
2673
+ const { page, perPage, dateRange } = pagination || {};
2674
+ const { name, spanType, entityId, entityType } = filters || {};
2675
+ const searchParams = new URLSearchParams();
2676
+ if (page !== void 0) {
2677
+ searchParams.set("page", String(page));
2678
+ }
2679
+ if (perPage !== void 0) {
2680
+ searchParams.set("perPage", String(perPage));
2681
+ }
2682
+ if (name) {
2683
+ searchParams.set("name", name);
2684
+ }
2685
+ if (spanType !== void 0) {
2686
+ searchParams.set("spanType", String(spanType));
2687
+ }
2688
+ if (entityId && entityType) {
2689
+ searchParams.set("entityId", entityId);
2690
+ searchParams.set("entityType", entityType);
2691
+ }
2692
+ if (dateRange) {
2693
+ const dateRangeStr = JSON.stringify({
2694
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2695
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2696
+ });
2697
+ searchParams.set("dateRange", dateRangeStr);
2698
+ }
2699
+ const queryString = searchParams.toString();
2700
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2701
+ }
2702
+ };
2703
+
2704
+ // src/resources/network-memory-thread.ts
2705
+ var NetworkMemoryThread = class extends BaseResource {
2706
+ constructor(options, threadId, networkId) {
2707
+ super(options);
2708
+ this.threadId = threadId;
2709
+ this.networkId = networkId;
2710
+ }
2711
+ /**
2712
+ * Retrieves the memory thread details
2713
+ * @returns Promise containing thread details including title and metadata
2714
+ */
2715
+ get() {
2716
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
2717
+ }
2718
+ /**
2719
+ * Updates the memory thread properties
2720
+ * @param params - Update parameters including title and metadata
2721
+ * @returns Promise containing updated thread details
2722
+ */
2723
+ update(params) {
2724
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2725
+ method: "PATCH",
2726
+ body: params
2727
+ });
309
2728
  }
310
2729
  /**
311
- * Executes the tool with the provided parameters
312
- * @param params - Parameters required for tool execution
313
- * @returns Promise containing the tool execution results
2730
+ * Deletes the memory thread
2731
+ * @returns Promise containing deletion result
314
2732
  */
315
- execute(params) {
316
- return this.request(`/api/tools/${this.toolId}/execute`, {
2733
+ delete() {
2734
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2735
+ method: "DELETE"
2736
+ });
2737
+ }
2738
+ /**
2739
+ * Retrieves messages associated with the thread
2740
+ * @param params - Optional parameters including limit for number of messages to retrieve
2741
+ * @returns Promise containing thread messages and UI messages
2742
+ */
2743
+ getMessages(params) {
2744
+ const query = new URLSearchParams({
2745
+ networkId: this.networkId,
2746
+ ...params?.limit ? { limit: params.limit.toString() } : {}
2747
+ });
2748
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
2749
+ }
2750
+ /**
2751
+ * Deletes one or more messages from the thread
2752
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2753
+ * message object with id property, or array of message objects
2754
+ * @returns Promise containing deletion result
2755
+ */
2756
+ deleteMessages(messageIds) {
2757
+ const query = new URLSearchParams({
2758
+ networkId: this.networkId
2759
+ });
2760
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
317
2761
  method: "POST",
318
- body: params
2762
+ body: { messageIds }
2763
+ });
2764
+ }
2765
+ };
2766
+
2767
+ // src/resources/vNextNetwork.ts
2768
+ var RECORD_SEPARATOR4 = "";
2769
+ var VNextNetwork = class extends BaseResource {
2770
+ constructor(options, networkId) {
2771
+ super(options);
2772
+ this.networkId = networkId;
2773
+ }
2774
+ /**
2775
+ * Retrieves details about the network
2776
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2777
+ * @returns Promise containing vNext network details
2778
+ */
2779
+ details(runtimeContext) {
2780
+ return this.request(`/api/networks/v-next/${this.networkId}${runtimeContextQueryString(runtimeContext)}`);
2781
+ }
2782
+ /**
2783
+ * Generates a response from the v-next network
2784
+ * @param params - Generation parameters including message
2785
+ * @returns Promise containing the generated response
2786
+ */
2787
+ generate(params) {
2788
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
2789
+ method: "POST",
2790
+ body: {
2791
+ ...params,
2792
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2793
+ }
2794
+ });
2795
+ }
2796
+ /**
2797
+ * Generates a response from the v-next network using multiple primitives
2798
+ * @param params - Generation parameters including message
2799
+ * @returns Promise containing the generated response
2800
+ */
2801
+ loop(params) {
2802
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
2803
+ method: "POST",
2804
+ body: {
2805
+ ...params,
2806
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2807
+ }
2808
+ });
2809
+ }
2810
+ async *streamProcessor(stream) {
2811
+ const reader = stream.getReader();
2812
+ let doneReading = false;
2813
+ let buffer = "";
2814
+ try {
2815
+ while (!doneReading) {
2816
+ const { done, value } = await reader.read();
2817
+ doneReading = done;
2818
+ if (done && !value) continue;
2819
+ try {
2820
+ const decoded = value ? new TextDecoder().decode(value) : "";
2821
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
2822
+ buffer = chunks.pop() || "";
2823
+ for (const chunk of chunks) {
2824
+ if (chunk) {
2825
+ if (typeof chunk === "string") {
2826
+ try {
2827
+ const parsedChunk = JSON.parse(chunk);
2828
+ yield parsedChunk;
2829
+ } catch {
2830
+ }
2831
+ }
2832
+ }
2833
+ }
2834
+ } catch {
2835
+ }
2836
+ }
2837
+ if (buffer) {
2838
+ try {
2839
+ yield JSON.parse(buffer);
2840
+ } catch {
2841
+ }
2842
+ }
2843
+ } finally {
2844
+ reader.cancel().catch(() => {
2845
+ });
2846
+ }
2847
+ }
2848
+ /**
2849
+ * Streams a response from the v-next network
2850
+ * @param params - Stream parameters including message
2851
+ * @returns Promise containing the results
2852
+ */
2853
+ async stream(params, onRecord) {
2854
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
2855
+ method: "POST",
2856
+ body: {
2857
+ ...params,
2858
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2859
+ },
2860
+ stream: true
2861
+ });
2862
+ if (!response.ok) {
2863
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2864
+ }
2865
+ if (!response.body) {
2866
+ throw new Error("Response body is null");
2867
+ }
2868
+ for await (const record of this.streamProcessor(response.body)) {
2869
+ if (typeof record === "string") {
2870
+ onRecord(JSON.parse(record));
2871
+ } else {
2872
+ onRecord(record);
2873
+ }
2874
+ }
2875
+ }
2876
+ /**
2877
+ * Streams a response from the v-next network loop
2878
+ * @param params - Stream parameters including message
2879
+ * @returns Promise containing the results
2880
+ */
2881
+ async loopStream(params, onRecord) {
2882
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
2883
+ method: "POST",
2884
+ body: {
2885
+ ...params,
2886
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2887
+ },
2888
+ stream: true
319
2889
  });
2890
+ if (!response.ok) {
2891
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2892
+ }
2893
+ if (!response.body) {
2894
+ throw new Error("Response body is null");
2895
+ }
2896
+ for await (const record of this.streamProcessor(response.body)) {
2897
+ if (typeof record === "string") {
2898
+ onRecord(JSON.parse(record));
2899
+ } else {
2900
+ onRecord(record);
2901
+ }
2902
+ }
320
2903
  }
321
2904
  };
322
2905
 
323
2906
  // src/client.ts
324
2907
  var MastraClient = class extends BaseResource {
2908
+ observability;
325
2909
  constructor(options) {
326
2910
  super(options);
2911
+ this.observability = new Observability(options);
327
2912
  }
328
2913
  /**
329
2914
  * Retrieves all available agents
2915
+ * @param runtimeContext - Optional runtime context to pass as query parameter
330
2916
  * @returns Promise containing map of agent IDs to agent details
331
2917
  */
332
- getAgents() {
333
- return this.request("/api/agents");
2918
+ getAgents(runtimeContext) {
2919
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2920
+ const searchParams = new URLSearchParams();
2921
+ if (runtimeContextParam) {
2922
+ searchParams.set("runtimeContext", runtimeContextParam);
2923
+ }
2924
+ const queryString = searchParams.toString();
2925
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
334
2926
  }
335
2927
  /**
336
2928
  * Gets an agent instance by ID
@@ -382,12 +2974,61 @@ var MastraClient = class extends BaseResource {
382
2974
  getMemoryStatus(agentId) {
383
2975
  return this.request(`/api/memory/status?agentId=${agentId}`);
384
2976
  }
2977
+ /**
2978
+ * Retrieves memory threads for a resource
2979
+ * @param params - Parameters containing the resource ID
2980
+ * @returns Promise containing array of memory threads
2981
+ */
2982
+ getNetworkMemoryThreads(params) {
2983
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
2984
+ }
2985
+ /**
2986
+ * Creates a new memory thread
2987
+ * @param params - Parameters for creating the memory thread
2988
+ * @returns Promise containing the created memory thread
2989
+ */
2990
+ createNetworkMemoryThread(params) {
2991
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
2992
+ }
2993
+ /**
2994
+ * Gets a memory thread instance by ID
2995
+ * @param threadId - ID of the memory thread to retrieve
2996
+ * @returns MemoryThread instance
2997
+ */
2998
+ getNetworkMemoryThread(threadId, networkId) {
2999
+ return new NetworkMemoryThread(this.options, threadId, networkId);
3000
+ }
3001
+ /**
3002
+ * Saves messages to memory
3003
+ * @param params - Parameters containing messages to save
3004
+ * @returns Promise containing the saved messages
3005
+ */
3006
+ saveNetworkMessageToMemory(params) {
3007
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
3008
+ method: "POST",
3009
+ body: params
3010
+ });
3011
+ }
3012
+ /**
3013
+ * Gets the status of the memory system
3014
+ * @returns Promise containing memory system status
3015
+ */
3016
+ getNetworkMemoryStatus(networkId) {
3017
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
3018
+ }
385
3019
  /**
386
3020
  * Retrieves all available tools
3021
+ * @param runtimeContext - Optional runtime context to pass as query parameter
387
3022
  * @returns Promise containing map of tool IDs to tool details
388
3023
  */
389
- getTools() {
390
- return this.request("/api/tools");
3024
+ getTools(runtimeContext) {
3025
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
3026
+ const searchParams = new URLSearchParams();
3027
+ if (runtimeContextParam) {
3028
+ searchParams.set("runtimeContext", runtimeContextParam);
3029
+ }
3030
+ const queryString = searchParams.toString();
3031
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
391
3032
  }
392
3033
  /**
393
3034
  * Gets a tool instance by ID
@@ -397,12 +3038,34 @@ var MastraClient = class extends BaseResource {
397
3038
  getTool(toolId) {
398
3039
  return new Tool(this.options, toolId);
399
3040
  }
3041
+ /**
3042
+ * Retrieves all available legacy workflows
3043
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
3044
+ */
3045
+ getLegacyWorkflows() {
3046
+ return this.request("/api/workflows/legacy");
3047
+ }
3048
+ /**
3049
+ * Gets a legacy workflow instance by ID
3050
+ * @param workflowId - ID of the legacy workflow to retrieve
3051
+ * @returns Legacy Workflow instance
3052
+ */
3053
+ getLegacyWorkflow(workflowId) {
3054
+ return new LegacyWorkflow(this.options, workflowId);
3055
+ }
400
3056
  /**
401
3057
  * Retrieves all available workflows
3058
+ * @param runtimeContext - Optional runtime context to pass as query parameter
402
3059
  * @returns Promise containing map of workflow IDs to workflow details
403
3060
  */
404
- getWorkflows() {
405
- return this.request("/api/workflows");
3061
+ getWorkflows(runtimeContext) {
3062
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
3063
+ const searchParams = new URLSearchParams();
3064
+ if (runtimeContextParam) {
3065
+ searchParams.set("runtimeContext", runtimeContextParam);
3066
+ }
3067
+ const queryString = searchParams.toString();
3068
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
406
3069
  }
407
3070
  /**
408
3071
  * Gets a workflow instance by ID
@@ -412,6 +3075,20 @@ var MastraClient = class extends BaseResource {
412
3075
  getWorkflow(workflowId) {
413
3076
  return new Workflow(this.options, workflowId);
414
3077
  }
3078
+ /**
3079
+ * Gets all available agent builder actions
3080
+ * @returns Promise containing map of action IDs to action details
3081
+ */
3082
+ getAgentBuilderActions() {
3083
+ return this.request("/api/agent-builder/");
3084
+ }
3085
+ /**
3086
+ * Gets an agent builder instance for executing agent-builder workflows
3087
+ * @returns AgentBuilder instance
3088
+ */
3089
+ getAgentBuilderAction(actionId) {
3090
+ return new AgentBuilder(this.options, actionId);
3091
+ }
415
3092
  /**
416
3093
  * Gets a vector instance by name
417
3094
  * @param vectorName - Name of the vector to retrieve
@@ -426,7 +3103,41 @@ var MastraClient = class extends BaseResource {
426
3103
  * @returns Promise containing array of log messages
427
3104
  */
428
3105
  getLogs(params) {
429
- return this.request(`/api/logs?transportId=${params.transportId}`);
3106
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
3107
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
3108
+ const searchParams = new URLSearchParams();
3109
+ if (transportId) {
3110
+ searchParams.set("transportId", transportId);
3111
+ }
3112
+ if (fromDate) {
3113
+ searchParams.set("fromDate", fromDate.toISOString());
3114
+ }
3115
+ if (toDate) {
3116
+ searchParams.set("toDate", toDate.toISOString());
3117
+ }
3118
+ if (logLevel) {
3119
+ searchParams.set("logLevel", logLevel);
3120
+ }
3121
+ if (page) {
3122
+ searchParams.set("page", String(page));
3123
+ }
3124
+ if (perPage) {
3125
+ searchParams.set("perPage", String(perPage));
3126
+ }
3127
+ if (_filters) {
3128
+ if (Array.isArray(_filters)) {
3129
+ for (const filter of _filters) {
3130
+ searchParams.append("filters", filter);
3131
+ }
3132
+ } else {
3133
+ searchParams.set("filters", _filters);
3134
+ }
3135
+ }
3136
+ if (searchParams.size) {
3137
+ return this.request(`/api/logs?${searchParams}`);
3138
+ } else {
3139
+ return this.request(`/api/logs`);
3140
+ }
430
3141
  }
431
3142
  /**
432
3143
  * Gets logs for a specific run
@@ -434,7 +3145,44 @@ var MastraClient = class extends BaseResource {
434
3145
  * @returns Promise containing array of log messages
435
3146
  */
436
3147
  getLogForRun(params) {
437
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
3148
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
3149
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
3150
+ const searchParams = new URLSearchParams();
3151
+ if (runId) {
3152
+ searchParams.set("runId", runId);
3153
+ }
3154
+ if (transportId) {
3155
+ searchParams.set("transportId", transportId);
3156
+ }
3157
+ if (fromDate) {
3158
+ searchParams.set("fromDate", fromDate.toISOString());
3159
+ }
3160
+ if (toDate) {
3161
+ searchParams.set("toDate", toDate.toISOString());
3162
+ }
3163
+ if (logLevel) {
3164
+ searchParams.set("logLevel", logLevel);
3165
+ }
3166
+ if (page) {
3167
+ searchParams.set("page", String(page));
3168
+ }
3169
+ if (perPage) {
3170
+ searchParams.set("perPage", String(perPage));
3171
+ }
3172
+ if (_filters) {
3173
+ if (Array.isArray(_filters)) {
3174
+ for (const filter of _filters) {
3175
+ searchParams.append("filters", filter);
3176
+ }
3177
+ } else {
3178
+ searchParams.set("filters", _filters);
3179
+ }
3180
+ }
3181
+ if (searchParams.size) {
3182
+ return this.request(`/api/logs/${runId}?${searchParams}`);
3183
+ } else {
3184
+ return this.request(`/api/logs/${runId}`);
3185
+ }
438
3186
  }
439
3187
  /**
440
3188
  * List of all log transports
@@ -449,11 +3197,8 @@ var MastraClient = class extends BaseResource {
449
3197
  * @returns Promise containing telemetry data
450
3198
  */
451
3199
  getTelemetry(params) {
452
- const { name, scope, page, perPage, attribute } = params || {};
3200
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
453
3201
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
454
- ({
455
- ..._attribute?.length ? { attribute: _attribute } : {}
456
- });
457
3202
  const searchParams = new URLSearchParams();
458
3203
  if (name) {
459
3204
  searchParams.set("name", name);
@@ -476,12 +3221,236 @@ var MastraClient = class extends BaseResource {
476
3221
  searchParams.set("attribute", _attribute);
477
3222
  }
478
3223
  }
3224
+ if (fromDate) {
3225
+ searchParams.set("fromDate", fromDate.toISOString());
3226
+ }
3227
+ if (toDate) {
3228
+ searchParams.set("toDate", toDate.toISOString());
3229
+ }
479
3230
  if (searchParams.size) {
480
3231
  return this.request(`/api/telemetry?${searchParams}`);
481
3232
  } else {
482
3233
  return this.request(`/api/telemetry`);
483
3234
  }
484
3235
  }
3236
+ /**
3237
+ * Retrieves all available vNext networks
3238
+ * @returns Promise containing map of vNext network IDs to vNext network details
3239
+ */
3240
+ getVNextNetworks() {
3241
+ return this.request("/api/networks/v-next");
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
+ }
485
3449
  };
3450
+ function createTool(opts) {
3451
+ return new ClientTool(opts);
3452
+ }
486
3453
 
487
- export { MastraClient };
3454
+ export { ClientTool, MastraClient, createTool };
3455
+ //# sourceMappingURL=index.js.map
3456
+ //# sourceMappingURL=index.js.map