@mastra/client-js 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-remove-unused-model-providers-api-20251030210744

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