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