@mastra/client-js 0.0.0-share-agent-metadata-with-cloud-20250718110128 → 0.0.0-sidebar-window-undefined-fix-20251029233656

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 (77) hide show
  1. package/CHANGELOG.md +1359 -2
  2. package/README.md +6 -7
  3. package/dist/client.d.ts +287 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/example.d.ts +2 -0
  6. package/dist/example.d.ts.map +1 -0
  7. package/dist/index.cjs +2292 -1219
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.d.ts +5 -1194
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +2292 -1221
  12. package/dist/index.js.map +1 -0
  13. package/dist/resources/a2a.d.ts +41 -0
  14. package/dist/resources/a2a.d.ts.map +1 -0
  15. package/dist/resources/agent-builder.d.ts +160 -0
  16. package/dist/resources/agent-builder.d.ts.map +1 -0
  17. package/dist/resources/agent.d.ts +204 -0
  18. package/dist/resources/agent.d.ts.map +1 -0
  19. package/dist/resources/base.d.ts +13 -0
  20. package/dist/resources/base.d.ts.map +1 -0
  21. package/dist/resources/index.d.ts +11 -0
  22. package/dist/resources/index.d.ts.map +1 -0
  23. package/dist/resources/mcp-tool.d.ts +28 -0
  24. package/dist/resources/mcp-tool.d.ts.map +1 -0
  25. package/dist/resources/memory-thread.d.ts +61 -0
  26. package/dist/resources/memory-thread.d.ts.map +1 -0
  27. package/dist/resources/network-memory-thread.d.ts +47 -0
  28. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  29. package/dist/resources/observability.d.ts +35 -0
  30. package/dist/resources/observability.d.ts.map +1 -0
  31. package/dist/resources/tool.d.ts +24 -0
  32. package/dist/resources/tool.d.ts.map +1 -0
  33. package/dist/resources/vector.d.ts +51 -0
  34. package/dist/resources/vector.d.ts.map +1 -0
  35. package/dist/resources/workflow.d.ts +269 -0
  36. package/dist/resources/workflow.d.ts.map +1 -0
  37. package/dist/tools.d.ts +22 -0
  38. package/dist/tools.d.ts.map +1 -0
  39. package/dist/types.d.ts +475 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/utils/index.d.ts +11 -0
  42. package/dist/utils/index.d.ts.map +1 -0
  43. package/dist/utils/process-client-tools.d.ts +3 -0
  44. package/dist/utils/process-client-tools.d.ts.map +1 -0
  45. package/dist/utils/process-mastra-stream.d.ts +11 -0
  46. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  47. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  48. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  49. package/package.json +26 -14
  50. package/.turbo/turbo-build.log +0 -19
  51. package/dist/index.d.cts +0 -1194
  52. package/eslint.config.js +0 -6
  53. package/src/adapters/agui.test.ts +0 -180
  54. package/src/adapters/agui.ts +0 -239
  55. package/src/client.ts +0 -526
  56. package/src/example.ts +0 -95
  57. package/src/index.test.ts +0 -836
  58. package/src/index.ts +0 -2
  59. package/src/resources/a2a.ts +0 -88
  60. package/src/resources/agent.ts +0 -800
  61. package/src/resources/base.ts +0 -72
  62. package/src/resources/index.ts +0 -10
  63. package/src/resources/legacy-workflow.ts +0 -242
  64. package/src/resources/mcp-tool.ts +0 -48
  65. package/src/resources/memory-thread.ts +0 -63
  66. package/src/resources/network-memory-thread.ts +0 -63
  67. package/src/resources/network.ts +0 -85
  68. package/src/resources/tool.ts +0 -45
  69. package/src/resources/vNextNetwork.ts +0 -194
  70. package/src/resources/vector.ts +0 -83
  71. package/src/resources/workflow.ts +0 -401
  72. package/src/types.ts +0 -428
  73. package/src/utils/index.ts +0 -11
  74. package/src/utils/process-client-tools.ts +0 -32
  75. package/src/utils/zod-to-json-schema.ts +0 -10
  76. package/tsconfig.json +0 -5
  77. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,216 +1,63 @@
1
1
  'use strict';
2
2
 
3
- var client = require('@ag-ui/client');
4
- var rxjs = require('rxjs');
5
3
  var uiUtils = require('@ai-sdk/ui-utils');
6
- var zod = require('zod');
7
- var originalZodToJsonSchema = require('zod-to-json-schema');
8
- var tools = require('@mastra/core/tools');
9
4
  var uuid = require('@lukeed/uuid');
5
+ var error = require('@mastra/core/error');
10
6
  var runtimeContext = require('@mastra/core/runtime-context');
7
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
8
+ var zod = require('zod');
9
+ var originalZodToJsonSchema = require('zod-to-json-schema');
11
10
 
12
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
12
 
14
13
  var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
15
14
 
16
- // src/adapters/agui.ts
17
- var AGUIAdapter = class extends client.AbstractAgent {
18
- agent;
19
- resourceId;
20
- constructor({ agent, agentId, resourceId, ...rest }) {
21
- super({
22
- agentId,
23
- ...rest
24
- });
25
- this.agent = agent;
26
- this.resourceId = resourceId;
27
- }
28
- run(input) {
29
- return new rxjs.Observable((subscriber) => {
30
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
31
- subscriber.next({
32
- type: client.EventType.RUN_STARTED,
33
- threadId: input.threadId,
34
- runId: input.runId
35
- });
36
- this.agent.stream({
37
- threadId: input.threadId,
38
- resourceId: this.resourceId ?? "",
39
- runId: input.runId,
40
- messages: convertedMessages,
41
- clientTools: input.tools.reduce(
42
- (acc, tool) => {
43
- acc[tool.name] = {
44
- id: tool.name,
45
- description: tool.description,
46
- inputSchema: tool.parameters
47
- };
48
- return acc;
49
- },
50
- {}
51
- )
52
- }).then((response) => {
53
- let currentMessageId = void 0;
54
- let isInTextMessage = false;
55
- return response.processDataStream({
56
- onTextPart: (text) => {
57
- if (currentMessageId === void 0) {
58
- currentMessageId = generateUUID();
59
- const message2 = {
60
- type: client.EventType.TEXT_MESSAGE_START,
61
- messageId: currentMessageId,
62
- role: "assistant"
63
- };
64
- subscriber.next(message2);
65
- isInTextMessage = true;
66
- }
67
- const message = {
68
- type: client.EventType.TEXT_MESSAGE_CONTENT,
69
- messageId: currentMessageId,
70
- delta: text
71
- };
72
- subscriber.next(message);
73
- },
74
- onFinishMessagePart: () => {
75
- if (currentMessageId !== void 0) {
76
- const message = {
77
- type: client.EventType.TEXT_MESSAGE_END,
78
- messageId: currentMessageId
79
- };
80
- subscriber.next(message);
81
- isInTextMessage = false;
82
- }
83
- subscriber.next({
84
- type: client.EventType.RUN_FINISHED,
85
- threadId: input.threadId,
86
- runId: input.runId
87
- });
88
- subscriber.complete();
89
- },
90
- onToolCallPart(streamPart) {
91
- const parentMessageId = currentMessageId || generateUUID();
92
- if (isInTextMessage) {
93
- const message = {
94
- type: client.EventType.TEXT_MESSAGE_END,
95
- messageId: parentMessageId
96
- };
97
- subscriber.next(message);
98
- isInTextMessage = false;
99
- }
100
- subscriber.next({
101
- type: client.EventType.TOOL_CALL_START,
102
- toolCallId: streamPart.toolCallId,
103
- toolCallName: streamPart.toolName,
104
- parentMessageId
105
- });
106
- subscriber.next({
107
- type: client.EventType.TOOL_CALL_ARGS,
108
- toolCallId: streamPart.toolCallId,
109
- delta: JSON.stringify(streamPart.args),
110
- parentMessageId
111
- });
112
- subscriber.next({
113
- type: client.EventType.TOOL_CALL_END,
114
- toolCallId: streamPart.toolCallId,
115
- parentMessageId
116
- });
117
- }
118
- });
119
- }).catch((error) => {
120
- console.error("error", error);
121
- subscriber.error(error);
122
- });
123
- return () => {
124
- };
125
- });
126
- }
127
- };
128
- function generateUUID() {
129
- if (typeof crypto !== "undefined") {
130
- if (typeof crypto.randomUUID === "function") {
131
- return crypto.randomUUID();
132
- }
133
- if (typeof crypto.getRandomValues === "function") {
134
- const buffer = new Uint8Array(16);
135
- crypto.getRandomValues(buffer);
136
- buffer[6] = buffer[6] & 15 | 64;
137
- buffer[8] = buffer[8] & 63 | 128;
138
- let hex = "";
139
- for (let i = 0; i < 16; i++) {
140
- hex += buffer[i].toString(16).padStart(2, "0");
141
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
142
- }
143
- return hex;
15
+ // src/resources/agent.ts
16
+ function parseClientRuntimeContext(runtimeContext$1) {
17
+ if (runtimeContext$1) {
18
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
19
+ return Object.fromEntries(runtimeContext$1.entries());
144
20
  }
21
+ return runtimeContext$1;
145
22
  }
146
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
147
- const r = Math.random() * 16 | 0;
148
- const v = c === "x" ? r : r & 3 | 8;
149
- return v.toString(16);
150
- });
23
+ return void 0;
151
24
  }
152
- function convertMessagesToMastraMessages(messages) {
153
- const result = [];
154
- for (const message of messages) {
155
- if (message.role === "assistant") {
156
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
157
- for (const toolCall of message.toolCalls ?? []) {
158
- parts.push({
159
- type: "tool-call",
160
- toolCallId: toolCall.id,
161
- toolName: toolCall.function.name,
162
- args: JSON.parse(toolCall.function.arguments)
163
- });
164
- }
165
- result.push({
166
- role: "assistant",
167
- content: parts
168
- });
169
- if (message.toolCalls?.length) {
170
- result.push({
171
- role: "tool",
172
- content: message.toolCalls.map((toolCall) => ({
173
- type: "tool-result",
174
- toolCallId: toolCall.id,
175
- toolName: toolCall.function.name,
176
- result: JSON.parse(toolCall.function.arguments)
177
- }))
178
- });
179
- }
180
- } else if (message.role === "user") {
181
- result.push({
182
- role: "user",
183
- content: message.content || ""
184
- });
185
- } else if (message.role === "tool") {
186
- result.push({
187
- role: "tool",
188
- content: [
189
- {
190
- type: "tool-result",
191
- toolCallId: message.toolCallId,
192
- toolName: "unknown",
193
- result: message.content
194
- }
195
- ]
196
- });
197
- }
25
+ function base64RuntimeContext(runtimeContext) {
26
+ if (runtimeContext) {
27
+ return btoa(JSON.stringify(runtimeContext));
198
28
  }
199
- return result;
29
+ return void 0;
30
+ }
31
+ function runtimeContextQueryString(runtimeContext, delimiter = "?") {
32
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
33
+ if (!runtimeContextParam) return "";
34
+ const searchParams = new URLSearchParams();
35
+ searchParams.set("runtimeContext", runtimeContextParam);
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";
200
41
  }
201
42
  function zodToJsonSchema(zodSchema) {
202
- if (!(zodSchema instanceof zod.ZodSchema)) {
43
+ if (!isZodType(zodSchema)) {
203
44
  return zodSchema;
204
45
  }
205
- return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
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" });
206
51
  }
52
+
53
+ // src/utils/process-client-tools.ts
207
54
  function processClientTools(clientTools) {
208
55
  if (!clientTools) {
209
56
  return void 0;
210
57
  }
211
58
  return Object.fromEntries(
212
59
  Object.entries(clientTools).map(([key, value]) => {
213
- if (tools.isVercelTool(value)) {
60
+ if (isVercelTool.isVercelTool(value)) {
214
61
  return [
215
62
  key,
216
63
  {
@@ -232,6 +79,64 @@ function processClientTools(clientTools) {
232
79
  );
233
80
  }
234
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
+ }
139
+
235
140
  // src/resources/base.ts
236
141
  var BaseResource = class {
237
142
  options;
@@ -246,20 +151,21 @@ var BaseResource = class {
246
151
  */
247
152
  async request(path, options = {}) {
248
153
  let lastError = null;
249
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
154
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
250
155
  let delay = backoffMs;
251
156
  for (let attempt = 0; attempt <= retries; attempt++) {
252
157
  try {
253
158
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
254
159
  ...options,
255
160
  headers: {
256
- ...options.method === "POST" || options.method === "PUT" ? { "content-type": "application/json" } : {},
161
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
257
162
  ...headers,
258
163
  ...options.headers
259
164
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
260
165
  // 'x-mastra-client-type': 'js',
261
166
  },
262
167
  signal: this.options.abortSignal,
168
+ credentials: options.credentials ?? credentials,
263
169
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
264
170
  });
265
171
  if (!response.ok) {
@@ -292,14 +198,62 @@ var BaseResource = class {
292
198
  throw lastError || new Error("Request failed");
293
199
  }
294
200
  };
295
- function parseClientRuntimeContext(runtimeContext$1) {
296
- if (runtimeContext$1) {
297
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
298
- return Object.fromEntries(runtimeContext$1.entries());
201
+
202
+ // src/resources/agent.ts
203
+ async function executeToolCallAndRespond({
204
+ response,
205
+ params,
206
+ runId,
207
+ resourceId,
208
+ threadId,
209
+ runtimeContext,
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
+ runtimeContext,
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
+ }
299
255
  }
300
- return runtimeContext$1;
301
256
  }
302
- return void 0;
303
257
  }
304
258
  var AgentVoice = class extends BaseResource {
305
259
  constructor(options, agentId) {
@@ -342,17 +296,21 @@ var AgentVoice = class extends BaseResource {
342
296
  }
343
297
  /**
344
298
  * Get available speakers for the agent's voice provider
299
+ * @param runtimeContext - Optional runtime context to pass as query parameter
300
+ * @param runtimeContext - Optional runtime context to pass as query parameter
345
301
  * @returns Promise containing list of available speakers
346
302
  */
347
- getSpeakers() {
348
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
303
+ getSpeakers(runtimeContext) {
304
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
349
305
  }
350
306
  /**
351
307
  * Get the listener configuration for the agent's voice provider
308
+ * @param runtimeContext - Optional runtime context to pass as query parameter
309
+ * @param runtimeContext - Optional runtime context to pass as query parameter
352
310
  * @returns Promise containing a check if the agent has listening capabilities
353
311
  */
354
- getListener() {
355
- return this.request(`/api/agents/${this.agentId}/voice/listener`);
312
+ getListener(runtimeContext) {
313
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
356
314
  }
357
315
  };
358
316
  var Agent = class extends BaseResource {
@@ -364,12 +322,19 @@ var Agent = class extends BaseResource {
364
322
  voice;
365
323
  /**
366
324
  * Retrieves details about the agent
325
+ * @param runtimeContext - Optional runtime context to pass as query parameter
367
326
  * @returns Promise containing agent details including model and instructions
368
327
  */
369
- details() {
370
- return this.request(`/api/agents/${this.agentId}`);
328
+ details(runtimeContext) {
329
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
330
+ }
331
+ enhanceInstructions(instructions, comment) {
332
+ return this.request(`/api/agents/${this.agentId}/instructions/enhance`, {
333
+ method: "POST",
334
+ body: { instructions, comment }
335
+ });
371
336
  }
372
- async generate(params) {
337
+ async generateLegacy(params) {
373
338
  const processedParams = {
374
339
  ...params,
375
340
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -378,10 +343,13 @@ var Agent = class extends BaseResource {
378
343
  clientTools: processClientTools(params.clientTools)
379
344
  };
380
345
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
381
- const response = await this.request(`/api/agents/${this.agentId}/generate`, {
382
- method: "POST",
383
- body: processedParams
384
- });
346
+ const response = await this.request(
347
+ `/api/agents/${this.agentId}/generate-legacy`,
348
+ {
349
+ method: "POST",
350
+ body: processedParams
351
+ }
352
+ );
385
353
  if (response.finishReason === "tool-calls") {
386
354
  const toolCalls = response.toolCalls;
387
355
  if (!toolCalls || !Array.isArray(toolCalls)) {
@@ -391,17 +359,22 @@ var Agent = class extends BaseResource {
391
359
  const clientTool = params.clientTools?.[toolCall.toolName];
392
360
  if (clientTool && clientTool.execute) {
393
361
  const result = await clientTool.execute(
394
- { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
362
+ {
363
+ context: toolCall?.args,
364
+ runId,
365
+ resourceId,
366
+ threadId,
367
+ runtimeContext,
368
+ tracingContext: { currentSpan: void 0 },
369
+ suspend: async () => {
370
+ }
371
+ },
395
372
  {
396
373
  messages: response.messages,
397
374
  toolCallId: toolCall?.toolCallId
398
375
  }
399
376
  );
400
377
  const updatedMessages = [
401
- {
402
- role: "user",
403
- content: params.messages
404
- },
405
378
  ...response.response.messages,
406
379
  {
407
380
  role: "tool",
@@ -424,14 +397,53 @@ var Agent = class extends BaseResource {
424
397
  }
425
398
  return response;
426
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
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
413
+ clientTools: processClientTools(params.clientTools),
414
+ structuredOutput: params.structuredOutput ? {
415
+ ...params.structuredOutput,
416
+ schema: zodToJsonSchema(params.structuredOutput.schema)
417
+ } : void 0
418
+ };
419
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
420
+ const response = await this.request(
421
+ `/api/agents/${this.agentId}/generate`,
422
+ {
423
+ method: "POST",
424
+ body: processedParams
425
+ }
426
+ );
427
+ if (response.finishReason === "tool-calls") {
428
+ return executeToolCallAndRespond({
429
+ response,
430
+ params,
431
+ runId,
432
+ resourceId,
433
+ threadId,
434
+ runtimeContext,
435
+ respondFn: this.generate.bind(this)
436
+ });
437
+ }
438
+ return response;
439
+ }
427
440
  async processChatResponse({
428
441
  stream,
429
442
  update,
430
443
  onToolCall,
431
444
  onFinish,
432
445
  getCurrentDate = () => /* @__PURE__ */ new Date(),
433
- lastMessage,
434
- streamProtocol
446
+ lastMessage
435
447
  }) {
436
448
  const replaceLastMessage = lastMessage?.role === "assistant";
437
449
  let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
@@ -492,264 +504,569 @@ var Agent = class extends BaseResource {
492
504
  replaceLastMessage
493
505
  });
494
506
  }
495
- if (streamProtocol === "text") {
496
- await uiUtils.processTextStream({
497
- stream,
498
- onTextPart(value) {
499
- message.content += value;
500
- execUpdate();
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;
501
518
  }
502
- });
503
- onFinish?.({ message, finishReason, usage });
504
- } else {
505
- await uiUtils.processDataStream({
506
- stream,
507
- onTextPart(value) {
508
- if (currentTextPart == null) {
509
- currentTextPart = {
510
- type: "text",
511
- text: value
512
- };
513
- message.parts.push(currentTextPart);
514
- } else {
515
- currentTextPart.text += value;
516
- }
517
- message.content += value;
518
- execUpdate();
519
- },
520
- onReasoningPart(value) {
521
- if (currentReasoningTextDetail == null) {
522
- currentReasoningTextDetail = { type: "text", text: value };
523
- if (currentReasoningPart != null) {
524
- currentReasoningPart.details.push(currentReasoningTextDetail);
525
- }
526
- } else {
527
- currentReasoningTextDetail.text += value;
528
- }
529
- if (currentReasoningPart == null) {
530
- currentReasoningPart = {
531
- type: "reasoning",
532
- reasoning: value,
533
- details: [currentReasoningTextDetail]
534
- };
535
- message.parts.push(currentReasoningPart);
536
- } else {
537
- currentReasoningPart.reasoning += value;
538
- }
539
- message.reasoning = (message.reasoning ?? "") + value;
540
- execUpdate();
541
- },
542
- onReasoningSignaturePart(value) {
543
- if (currentReasoningTextDetail != null) {
544
- currentReasoningTextDetail.signature = value.signature;
545
- }
546
- },
547
- onRedactedReasoningPart(value) {
548
- if (currentReasoningPart == null) {
549
- currentReasoningPart = {
550
- type: "reasoning",
551
- reasoning: "",
552
- details: []
553
- };
554
- message.parts.push(currentReasoningPart);
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);
555
527
  }
556
- currentReasoningPart.details.push({
557
- type: "redacted",
558
- data: value.data
559
- });
560
- currentReasoningTextDetail = void 0;
561
- execUpdate();
562
- },
563
- onFilePart(value) {
564
- message.parts.push({
565
- type: "file",
566
- mimeType: value.mimeType,
567
- data: value.data
568
- });
569
- execUpdate();
570
- },
571
- onSourcePart(value) {
572
- message.parts.push({
573
- type: "source",
574
- source: value
575
- });
576
- execUpdate();
577
- },
578
- onToolCallStreamingStartPart(value) {
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 {
579
625
  if (message.toolInvocations == null) {
580
626
  message.toolInvocations = [];
581
627
  }
582
- partialToolCalls[value.toolCallId] = {
583
- text: "",
584
- step,
585
- toolName: value.toolName,
586
- index: message.toolInvocations.length
587
- };
588
- const invocation = {
589
- state: "partial-call",
590
- step,
591
- toolCallId: value.toolCallId,
592
- toolName: value.toolName,
593
- args: void 0
594
- };
595
628
  message.toolInvocations.push(invocation);
596
- updateToolInvocationPart(value.toolCallId, invocation);
597
- execUpdate();
598
- },
599
- onToolCallDeltaPart(value) {
600
- const partialToolCall = partialToolCalls[value.toolCallId];
601
- partialToolCall.text += value.argsTextDelta;
602
- const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
603
- const invocation = {
604
- state: "partial-call",
605
- step: partialToolCall.step,
606
- toolCallId: value.toolCallId,
607
- toolName: partialToolCall.toolName,
608
- args: partialArgs
609
- };
610
- message.toolInvocations[partialToolCall.index] = invocation;
611
- updateToolInvocationPart(value.toolCallId, invocation);
612
- execUpdate();
613
- },
614
- async onToolCallPart(value) {
615
- const invocation = {
616
- state: "call",
617
- step,
618
- ...value
619
- };
620
- if (partialToolCalls[value.toolCallId] != null) {
621
- message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
622
- } else {
623
- if (message.toolInvocations == null) {
624
- message.toolInvocations = [];
625
- }
626
- message.toolInvocations.push(invocation);
627
- }
628
- updateToolInvocationPart(value.toolCallId, invocation);
629
- execUpdate();
630
- if (onToolCall) {
631
- const result = await onToolCall({ toolCall: value });
632
- if (result != null) {
633
- const invocation2 = {
634
- state: "result",
635
- step,
636
- ...value,
637
- result
638
- };
639
- message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
640
- updateToolInvocationPart(value.toolCallId, invocation2);
641
- execUpdate();
642
- }
643
- }
644
- },
645
- onToolResultPart(value) {
646
- const toolInvocations = message.toolInvocations;
647
- if (toolInvocations == null) {
648
- throw new Error("tool_result must be preceded by a tool_call");
649
- }
650
- const toolInvocationIndex = toolInvocations.findIndex(
651
- (invocation2) => invocation2.toolCallId === value.toolCallId
652
- );
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;
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();
694
644
  }
695
- },
696
- onErrorPart(error) {
697
- throw new Error(error);
698
645
  }
699
- });
700
- onFinish?.({ message, finishReason, usage });
701
- }
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
+ }
699
+ });
700
+ onFinish?.({ message, finishReason, usage });
702
701
  }
703
702
  /**
704
- * Processes the stream response and handles tool calls
703
+ * Streams a response from the agent
704
+ * @param params - Stream parameters including prompt
705
+ * @returns Promise containing the enhanced Response object with processDataStream method
705
706
  */
706
- async processStreamResponse(processedParams, writable) {
707
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
708
- method: "POST",
709
- body: processedParams,
710
- stream: true
707
+ async streamLegacy(params) {
708
+ const processedParams = {
709
+ ...params,
710
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
711
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
712
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
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
711
721
  });
712
- if (!response.body) {
713
- throw new Error("No response body");
714
- }
715
- try {
716
- const streamProtocol = processedParams.output ? "text" : "data";
717
- let toolCalls = [];
718
- let messages = [];
719
- const [streamForWritable, streamForProcessing] = response.body.tee();
720
- streamForWritable.pipeTo(writable, {
721
- preventClose: true
722
- }).catch((error) => {
723
- console.error("Error piping to writable stream:", error);
722
+ streamResponse.processDataStream = async (options = {}) => {
723
+ await uiUtils.processDataStream({
724
+ stream: streamResponse.body,
725
+ ...options
724
726
  });
725
- this.processChatResponse({
726
- stream: streamForProcessing,
727
- update: ({ message }) => {
728
- messages.push(message);
729
- },
730
- onFinish: async ({ finishReason, message }) => {
731
- if (finishReason === "tool-calls") {
732
- const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
733
- if (toolCall) {
734
- toolCalls.push(toolCall);
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: []
749
+ };
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}`, {
996
+ method: "POST",
997
+ body: processedParams,
998
+ stream: true
999
+ });
1000
+ if (!response.body) {
1001
+ throw new Error("No response body");
1002
+ }
1003
+ try {
1004
+ let toolCalls = [];
1005
+ let messages = [];
1006
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1007
+ streamForWritable.pipeTo(
1008
+ new WritableStream({
1009
+ async write(chunk) {
1010
+ 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);
735
1045
  }
1046
+ let shouldExecuteClientTool = false;
736
1047
  for (const toolCall2 of toolCalls) {
737
1048
  const clientTool = processedParams.clientTools?.[toolCall2.toolName];
738
1049
  if (clientTool && clientTool.execute) {
1050
+ shouldExecuteClientTool = true;
739
1051
  const result = await clientTool.execute(
740
1052
  {
741
1053
  context: toolCall2?.args,
742
1054
  runId: processedParams.runId,
743
1055
  resourceId: processedParams.resourceId,
744
1056
  threadId: processedParams.threadId,
745
- runtimeContext: processedParams.runtimeContext
1057
+ runtimeContext: processedParams.runtimeContext,
1058
+ // TODO: Pass proper tracing context when client-js supports tracing
1059
+ tracingContext: { currentSpan: void 0 },
1060
+ suspend: async () => {
1061
+ }
746
1062
  },
747
1063
  {
748
1064
  messages: response.messages,
749
1065
  toolCallId: toolCall2?.toolCallId
750
1066
  }
751
1067
  );
752
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1068
+ const lastMessageRaw = messages[messages.length - 1];
1069
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
753
1070
  const toolInvocationPart = lastMessage?.parts?.find(
754
1071
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
755
1072
  );
@@ -767,58 +1084,80 @@ var Agent = class extends BaseResource {
767
1084
  toolInvocation.state = "result";
768
1085
  toolInvocation.result = result;
769
1086
  }
770
- const writer = writable.getWriter();
771
- try {
772
- await writer.write(
773
- new TextEncoder().encode(
774
- "a:" + JSON.stringify({
775
- toolCallId: toolCall2.toolCallId,
776
- result
777
- }) + "\n"
778
- )
779
- );
780
- } finally {
781
- writer.releaseLock();
782
- }
783
- const originalMessages = processedParams.messages;
784
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1087
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
785
1088
  this.processStreamResponse(
786
1089
  {
787
1090
  ...processedParams,
788
- messages: [...messageArray, ...messages, lastMessage]
1091
+ messages: updatedMessages
789
1092
  },
790
1093
  writable
791
- );
1094
+ ).catch((error) => {
1095
+ console.error("Error processing stream response:", error);
1096
+ });
792
1097
  }
793
1098
  }
1099
+ if (!shouldExecuteClientTool) {
1100
+ setTimeout(() => {
1101
+ writable.close();
1102
+ }, 0);
1103
+ }
794
1104
  } else {
795
1105
  setTimeout(() => {
796
- if (!writable.locked) {
797
- writable.close();
798
- }
1106
+ writable.close();
799
1107
  }, 0);
800
1108
  }
801
1109
  },
802
- lastMessage: void 0,
803
- streamProtocol
1110
+ lastMessage: void 0
1111
+ }).catch((error) => {
1112
+ console.error("Error processing stream response:", error);
804
1113
  });
805
1114
  } catch (error) {
806
1115
  console.error("Error processing stream response:", error);
807
1116
  }
808
1117
  return response;
809
1118
  }
810
- /**
811
- * Streams a response from the agent
812
- * @param params - Stream parameters including prompt
813
- * @returns Promise containing the enhanced Response object with processDataStream and processTextStream methods
814
- */
815
- async stream(params) {
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,
1150
+ ...options
1151
+ };
1152
+ }
816
1153
  const processedParams = {
817
1154
  ...params,
818
- output: params.output ? zodToJsonSchema(params.output) : void 0,
819
- experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
820
1155
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
821
- clientTools: processClientTools(params.clientTools)
1156
+ clientTools: processClientTools(params.clientTools),
1157
+ structuredOutput: params.structuredOutput ? {
1158
+ ...params.structuredOutput,
1159
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1160
+ } : void 0
822
1161
  };
823
1162
  const { readable, writable } = new TransformStream();
824
1163
  const response = await this.processStreamResponse(processedParams, writable);
@@ -827,115 +1166,246 @@ var Agent = class extends BaseResource {
827
1166
  statusText: response.statusText,
828
1167
  headers: response.headers
829
1168
  });
830
- streamResponse.processDataStream = async (options = {}) => {
831
- await uiUtils.processDataStream({
1169
+ streamResponse.processDataStream = async ({
1170
+ onChunk
1171
+ }) => {
1172
+ await processMastraStream({
832
1173
  stream: streamResponse.body,
833
- ...options
1174
+ onChunk
834
1175
  });
835
1176
  };
836
- streamResponse.processTextStream = async (options) => {
837
- await uiUtils.processTextStream({
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({
838
1191
  stream: streamResponse.body,
839
- onTextPart: options?.onTextPart ?? (() => {
840
- })
1192
+ onChunk
841
1193
  });
842
1194
  };
843
1195
  return streamResponse;
844
1196
  }
845
- /**
846
- * Gets details about a specific tool available to the agent
847
- * @param toolId - ID of the tool to retrieve
848
- * @returns Promise containing tool details
849
- */
850
- getTool(toolId) {
851
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
852
- }
853
- /**
854
- * Executes a tool for the agent
855
- * @param toolId - ID of the tool to execute
856
- * @param params - Parameters required for tool execution
857
- * @returns Promise containing the tool execution results
858
- */
859
- executeTool(toolId, params) {
860
- const body = {
861
- data: params.data,
862
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
863
- };
864
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
865
- method: "POST",
866
- body
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
867
1204
  });
1205
+ streamResponse.processDataStream = async ({
1206
+ onChunk
1207
+ }) => {
1208
+ await processMastraStream({
1209
+ stream: streamResponse.body,
1210
+ onChunk
1211
+ });
1212
+ };
1213
+ return streamResponse;
868
1214
  }
869
1215
  /**
870
- * Retrieves evaluation results for the agent
871
- * @returns Promise containing agent evaluations
872
- */
873
- evals() {
874
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
875
- }
876
- /**
877
- * Retrieves live evaluation results for the agent
878
- * @returns Promise containing live agent evaluations
879
- */
880
- liveEvals() {
881
- return this.request(`/api/agents/${this.agentId}/evals/live`);
882
- }
883
- };
884
- var Network = class extends BaseResource {
885
- constructor(options, networkId) {
886
- super(options);
887
- this.networkId = networkId;
888
- }
889
- /**
890
- * Retrieves details about the network
891
- * @returns Promise containing network details
892
- */
893
- details() {
894
- return this.request(`/api/networks/${this.networkId}`);
895
- }
896
- /**
897
- * Generates a response from the agent
898
- * @param params - Generation parameters including prompt
899
- * @returns Promise containing the generated response
1216
+ * Processes the stream response and handles tool calls
900
1217
  */
901
- generate(params) {
902
- const processedParams = {
903
- ...params,
904
- output: zodToJsonSchema(params.output),
905
- experimental_output: zodToJsonSchema(params.experimental_output)
906
- };
907
- return this.request(`/api/networks/${this.networkId}/generate`, {
1218
+ async processStreamResponseLegacy(processedParams, writable) {
1219
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
908
1220
  method: "POST",
909
- body: processedParams
910
- });
911
- }
912
- /**
913
- * Streams a response from the agent
914
- * @param params - Stream parameters including prompt
915
- * @returns Promise containing the enhanced Response object with processDataStream method
916
- */
917
- async stream(params) {
918
- const processedParams = {
919
- ...params,
920
- output: zodToJsonSchema(params.output),
921
- experimental_output: zodToJsonSchema(params.experimental_output)
922
- };
923
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
924
- method: "POST",
925
- body: processedParams,
926
- stream: true
1221
+ body: processedParams,
1222
+ stream: true
927
1223
  });
928
1224
  if (!response.body) {
929
1225
  throw new Error("No response body");
930
1226
  }
931
- response.processDataStream = async (options = {}) => {
932
- await uiUtils.processDataStream({
933
- stream: response.body,
934
- ...options
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);
935
1235
  });
936
- };
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
+ runtimeContext: processedParams.runtimeContext,
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
+ }
937
1327
  return response;
938
1328
  }
1329
+ /**
1330
+ * Gets details about a specific tool available to the agent
1331
+ * @param toolId - ID of the tool to retrieve
1332
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1333
+ * @returns Promise containing tool details
1334
+ */
1335
+ getTool(toolId, runtimeContext) {
1336
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
1337
+ }
1338
+ /**
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
1343
+ */
1344
+ executeTool(toolId, params) {
1345
+ const body = {
1346
+ data: params.data,
1347
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1348
+ };
1349
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1350
+ method: "POST",
1351
+ body
1352
+ });
1353
+ }
1354
+ /**
1355
+ * Retrieves evaluation results for the agent
1356
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1357
+ * @returns Promise containing agent evaluations
1358
+ */
1359
+ evals(runtimeContext) {
1360
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
1361
+ }
1362
+ /**
1363
+ * Retrieves live evaluation results for the agent
1364
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1365
+ * @returns Promise containing live agent evaluations
1366
+ */
1367
+ liveEvals(runtimeContext) {
1368
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
1369
+ }
1370
+ /**
1371
+ * Updates the model for the agent
1372
+ * @param params - Parameters for updating the model
1373
+ * @returns Promise containing the updated model
1374
+ */
1375
+ updateModel(params) {
1376
+ return this.request(`/api/agents/${this.agentId}/model`, {
1377
+ method: "POST",
1378
+ body: params
1379
+ });
1380
+ }
1381
+ /**
1382
+ * Updates the model for the agent in the model list
1383
+ * @param params - Parameters for updating the model
1384
+ * @returns Promise containing the updated model
1385
+ */
1386
+ updateModelInModelList({ modelConfigId, ...params }) {
1387
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
1388
+ method: "POST",
1389
+ body: params
1390
+ });
1391
+ }
1392
+ /**
1393
+ * Reorders the models for the agent
1394
+ * @param params - Parameters for reordering the model list
1395
+ * @returns Promise containing the updated model list
1396
+ */
1397
+ reorderModelList(params) {
1398
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
1399
+ method: "POST",
1400
+ body: params
1401
+ });
1402
+ }
1403
+ async generateVNext(_messagesOrParams, _options) {
1404
+ throw new Error("generateVNext has been renamed to generate. Please use generate instead.");
1405
+ }
1406
+ async streamVNext(_messagesOrParams, _options) {
1407
+ throw new Error("streamVNext has been renamed to stream. Please use stream instead.");
1408
+ }
939
1409
  };
940
1410
 
941
1411
  // src/resources/memory-thread.ts
@@ -947,34 +1417,44 @@ var MemoryThread = class extends BaseResource {
947
1417
  }
948
1418
  /**
949
1419
  * Retrieves the memory thread details
1420
+ * @param runtimeContext - Optional runtime context to pass as query parameter
950
1421
  * @returns Promise containing thread details including title and metadata
951
1422
  */
952
- get() {
953
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`);
1423
+ get(runtimeContext) {
1424
+ return this.request(
1425
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${runtimeContextQueryString(runtimeContext, "&")}`
1426
+ );
954
1427
  }
955
1428
  /**
956
1429
  * Updates the memory thread properties
957
- * @param params - Update parameters including title and metadata
1430
+ * @param params - Update parameters including title, metadata, and optional runtime context
958
1431
  * @returns Promise containing updated thread details
959
1432
  */
960
1433
  update(params) {
961
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
962
- method: "PATCH",
963
- body: params
964
- });
1434
+ return this.request(
1435
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`,
1436
+ {
1437
+ method: "PATCH",
1438
+ body: params
1439
+ }
1440
+ );
965
1441
  }
966
1442
  /**
967
1443
  * Deletes the memory thread
1444
+ * @param runtimeContext - Optional runtime context to pass as query parameter
968
1445
  * @returns Promise containing deletion result
969
1446
  */
970
- delete() {
971
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
972
- method: "DELETE"
973
- });
1447
+ delete(runtimeContext) {
1448
+ return this.request(
1449
+ `/api/memory/threads/${this.threadId}?agentId=${this.agentId}${runtimeContextQueryString(runtimeContext, "&")}`,
1450
+ {
1451
+ method: "DELETE"
1452
+ }
1453
+ );
974
1454
  }
975
1455
  /**
976
1456
  * Retrieves messages associated with the thread
977
- * @param params - Optional parameters including limit for number of messages to retrieve
1457
+ * @param params - Optional parameters including limit for number of messages to retrieve and runtime context
978
1458
  * @returns Promise containing thread messages and UI messages
979
1459
  */
980
1460
  getMessages(params) {
@@ -982,7 +1462,46 @@ var MemoryThread = class extends BaseResource {
982
1462
  agentId: this.agentId,
983
1463
  ...params?.limit ? { limit: params.limit.toString() } : {}
984
1464
  });
985
- return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
1465
+ return this.request(
1466
+ `/api/memory/threads/${this.threadId}/messages?${query.toString()}${runtimeContextQueryString(params?.runtimeContext, "&")}`
1467
+ );
1468
+ }
1469
+ /**
1470
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1471
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, message inclusion options, and runtime context
1472
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1473
+ */
1474
+ getMessagesPaginated({
1475
+ selectBy,
1476
+ runtimeContext,
1477
+ ...rest
1478
+ }) {
1479
+ const query = new URLSearchParams({
1480
+ ...rest,
1481
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1482
+ });
1483
+ return this.request(
1484
+ `/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}${runtimeContextQueryString(runtimeContext, "&")}`
1485
+ );
1486
+ }
1487
+ /**
1488
+ * Deletes one or more messages from the thread
1489
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1490
+ * message object with id property, or array of message objects
1491
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1492
+ * @returns Promise containing deletion result
1493
+ */
1494
+ deleteMessages(messageIds, runtimeContext) {
1495
+ const query = new URLSearchParams({
1496
+ agentId: this.agentId
1497
+ });
1498
+ return this.request(
1499
+ `/api/memory/messages/delete?${query.toString()}${runtimeContextQueryString(runtimeContext, "&")}`,
1500
+ {
1501
+ method: "POST",
1502
+ body: { messageIds }
1503
+ }
1504
+ );
986
1505
  }
987
1506
  };
988
1507
 
@@ -995,10 +1514,13 @@ var Vector = class extends BaseResource {
995
1514
  /**
996
1515
  * Retrieves details about a specific vector index
997
1516
  * @param indexName - Name of the index to get details for
1517
+ * @param runtimeContext - Optional runtime context to pass as query parameter
998
1518
  * @returns Promise containing vector index details
999
1519
  */
1000
- details(indexName) {
1001
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1520
+ details(indexName, runtimeContext) {
1521
+ return this.request(
1522
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1523
+ );
1002
1524
  }
1003
1525
  /**
1004
1526
  * Deletes a vector index
@@ -1012,10 +1534,11 @@ var Vector = class extends BaseResource {
1012
1534
  }
1013
1535
  /**
1014
1536
  * Retrieves a list of all available indexes
1537
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1015
1538
  * @returns Promise containing array of index names
1016
1539
  */
1017
- getIndexes() {
1018
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1540
+ getIndexes(runtimeContext) {
1541
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
1019
1542
  }
1020
1543
  /**
1021
1544
  * Creates a new vector index
@@ -1052,227 +1575,47 @@ var Vector = class extends BaseResource {
1052
1575
  }
1053
1576
  };
1054
1577
 
1055
- // src/resources/legacy-workflow.ts
1056
- var RECORD_SEPARATOR = "";
1057
- var LegacyWorkflow = class extends BaseResource {
1058
- constructor(options, workflowId) {
1578
+ // src/resources/tool.ts
1579
+ var Tool = class extends BaseResource {
1580
+ constructor(options, toolId) {
1059
1581
  super(options);
1060
- this.workflowId = workflowId;
1061
- }
1062
- /**
1063
- * Retrieves details about the legacy workflow
1064
- * @returns Promise containing legacy workflow details including steps and graphs
1065
- */
1066
- details() {
1067
- return this.request(`/api/workflows/legacy/${this.workflowId}`);
1582
+ this.toolId = toolId;
1068
1583
  }
1069
1584
  /**
1070
- * Retrieves all runs for a legacy workflow
1071
- * @param params - Parameters for filtering runs
1072
- * @returns Promise containing legacy workflow runs array
1585
+ * Retrieves details about the tool
1586
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1587
+ * @returns Promise containing tool details including description and schemas
1073
1588
  */
1074
- runs(params) {
1075
- const searchParams = new URLSearchParams();
1076
- if (params?.fromDate) {
1077
- searchParams.set("fromDate", params.fromDate.toISOString());
1078
- }
1079
- if (params?.toDate) {
1080
- searchParams.set("toDate", params.toDate.toISOString());
1081
- }
1082
- if (params?.limit) {
1083
- searchParams.set("limit", String(params.limit));
1084
- }
1085
- if (params?.offset) {
1086
- searchParams.set("offset", String(params.offset));
1087
- }
1088
- if (params?.resourceId) {
1089
- searchParams.set("resourceId", params.resourceId);
1090
- }
1091
- if (searchParams.size) {
1092
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1093
- } else {
1094
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1095
- }
1589
+ details(runtimeContext) {
1590
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1096
1591
  }
1097
1592
  /**
1098
- * Creates a new legacy workflow run
1099
- * @returns Promise containing the generated run ID
1593
+ * Executes the tool with the provided parameters
1594
+ * @param params - Parameters required for tool execution
1595
+ * @returns Promise containing the tool execution results
1100
1596
  */
1101
- createRun(params) {
1102
- const searchParams = new URLSearchParams();
1103
- if (!!params?.runId) {
1104
- searchParams.set("runId", params.runId);
1597
+ execute(params) {
1598
+ const url = new URLSearchParams();
1599
+ if (params.runId) {
1600
+ url.set("runId", params.runId);
1105
1601
  }
1106
- return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1107
- method: "POST"
1108
- });
1109
- }
1110
- /**
1111
- * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1112
- * @param params - Object containing the runId and triggerData
1113
- * @returns Promise containing success message
1114
- */
1115
- start(params) {
1116
- return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1602
+ const body = {
1603
+ data: params.data,
1604
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1605
+ };
1606
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1117
1607
  method: "POST",
1118
- body: params?.triggerData
1608
+ body
1119
1609
  });
1120
1610
  }
1121
- /**
1122
- * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
1123
- * @param stepId - ID of the step to resume
1124
- * @param runId - ID of the legacy workflow run
1125
- * @param context - Context to resume the legacy workflow with
1126
- * @returns Promise containing the legacy workflow resume results
1127
- */
1128
- resume({
1129
- stepId,
1130
- runId,
1131
- context
1132
- }) {
1133
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
1134
- method: "POST",
1135
- body: {
1136
- stepId,
1137
- context
1138
- }
1139
- });
1140
- }
1141
- /**
1142
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1143
- * @param params - Object containing the optional runId and triggerData
1144
- * @returns Promise containing the workflow execution results
1145
- */
1146
- startAsync(params) {
1147
- const searchParams = new URLSearchParams();
1148
- if (!!params?.runId) {
1149
- searchParams.set("runId", params.runId);
1150
- }
1151
- return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1152
- method: "POST",
1153
- body: params?.triggerData
1154
- });
1155
- }
1156
- /**
1157
- * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1158
- * @param params - Object containing the runId, stepId, and context
1159
- * @returns Promise containing the workflow resume results
1160
- */
1161
- resumeAsync(params) {
1162
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1163
- method: "POST",
1164
- body: {
1165
- stepId: params.stepId,
1166
- context: params.context
1167
- }
1168
- });
1169
- }
1170
- /**
1171
- * Creates an async generator that processes a readable stream and yields records
1172
- * separated by the Record Separator character (\x1E)
1173
- *
1174
- * @param stream - The readable stream to process
1175
- * @returns An async generator that yields parsed records
1176
- */
1177
- async *streamProcessor(stream) {
1178
- const reader = stream.getReader();
1179
- let doneReading = false;
1180
- let buffer = "";
1181
- try {
1182
- while (!doneReading) {
1183
- const { done, value } = await reader.read();
1184
- doneReading = done;
1185
- if (done && !value) continue;
1186
- try {
1187
- const decoded = value ? new TextDecoder().decode(value) : "";
1188
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1189
- buffer = chunks.pop() || "";
1190
- for (const chunk of chunks) {
1191
- if (chunk) {
1192
- if (typeof chunk === "string") {
1193
- try {
1194
- const parsedChunk = JSON.parse(chunk);
1195
- yield parsedChunk;
1196
- } catch {
1197
- }
1198
- }
1199
- }
1200
- }
1201
- } catch {
1202
- }
1203
- }
1204
- if (buffer) {
1205
- try {
1206
- yield JSON.parse(buffer);
1207
- } catch {
1208
- }
1209
- }
1210
- } finally {
1211
- reader.cancel().catch(() => {
1212
- });
1213
- }
1214
- }
1215
- /**
1216
- * Watches legacy workflow transitions in real-time
1217
- * @param runId - Optional run ID to filter the watch stream
1218
- * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1219
- */
1220
- async watch({ runId }, onRecord) {
1221
- const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1222
- stream: true
1223
- });
1224
- if (!response.ok) {
1225
- throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1226
- }
1227
- if (!response.body) {
1228
- throw new Error("Response body is null");
1229
- }
1230
- for await (const record of this.streamProcessor(response.body)) {
1231
- onRecord(record);
1232
- }
1233
- }
1234
- };
1235
-
1236
- // src/resources/tool.ts
1237
- var Tool2 = class extends BaseResource {
1238
- constructor(options, toolId) {
1239
- super(options);
1240
- this.toolId = toolId;
1241
- }
1242
- /**
1243
- * Retrieves details about the tool
1244
- * @returns Promise containing tool details including description and schemas
1245
- */
1246
- details() {
1247
- return this.request(`/api/tools/${this.toolId}`);
1248
- }
1249
- /**
1250
- * Executes the tool with the provided parameters
1251
- * @param params - Parameters required for tool execution
1252
- * @returns Promise containing the tool execution results
1253
- */
1254
- execute(params) {
1255
- const url = new URLSearchParams();
1256
- if (params.runId) {
1257
- url.set("runId", params.runId);
1258
- }
1259
- const body = {
1260
- data: params.data,
1261
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1262
- };
1263
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1264
- method: "POST",
1265
- body
1266
- });
1267
- }
1268
- };
1269
-
1270
- // src/resources/workflow.ts
1271
- var RECORD_SEPARATOR2 = "";
1272
- var Workflow = class extends BaseResource {
1273
- constructor(options, workflowId) {
1274
- super(options);
1275
- this.workflowId = workflowId;
1611
+ };
1612
+
1613
+ // src/resources/workflow.ts
1614
+ var RECORD_SEPARATOR = "";
1615
+ var Workflow = class extends BaseResource {
1616
+ constructor(options, workflowId) {
1617
+ super(options);
1618
+ this.workflowId = workflowId;
1276
1619
  }
1277
1620
  /**
1278
1621
  * Creates an async generator that processes a readable stream and yields workflow records
@@ -1292,7 +1635,7 @@ var Workflow = class extends BaseResource {
1292
1635
  if (done && !value) continue;
1293
1636
  try {
1294
1637
  const decoded = value ? new TextDecoder().decode(value) : "";
1295
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1638
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1296
1639
  buffer = chunks.pop() || "";
1297
1640
  for (const chunk of chunks) {
1298
1641
  if (chunk) {
@@ -1321,17 +1664,20 @@ var Workflow = class extends BaseResource {
1321
1664
  }
1322
1665
  /**
1323
1666
  * Retrieves details about the workflow
1667
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1324
1668
  * @returns Promise containing workflow details including steps and graphs
1325
1669
  */
1326
- details() {
1327
- return this.request(`/api/workflows/${this.workflowId}`);
1670
+ details(runtimeContext) {
1671
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1328
1672
  }
1329
1673
  /**
1330
1674
  * Retrieves all runs for a workflow
1331
1675
  * @param params - Parameters for filtering runs
1676
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1332
1677
  * @returns Promise containing workflow runs array
1333
1678
  */
1334
- runs(params) {
1679
+ runs(params, runtimeContext) {
1680
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1335
1681
  const searchParams = new URLSearchParams();
1336
1682
  if (params?.fromDate) {
1337
1683
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1348,6 +1694,9 @@ var Workflow = class extends BaseResource {
1348
1694
  if (params?.resourceId) {
1349
1695
  searchParams.set("resourceId", params.resourceId);
1350
1696
  }
1697
+ if (runtimeContextParam) {
1698
+ searchParams.set("runtimeContext", runtimeContextParam);
1699
+ }
1351
1700
  if (searchParams.size) {
1352
1701
  return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1353
1702
  } else {
@@ -1357,18 +1706,22 @@ var Workflow = class extends BaseResource {
1357
1706
  /**
1358
1707
  * Retrieves a specific workflow run by its ID
1359
1708
  * @param runId - The ID of the workflow run to retrieve
1709
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1360
1710
  * @returns Promise containing the workflow run details
1361
1711
  */
1362
- runById(runId) {
1363
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1712
+ runById(runId, runtimeContext) {
1713
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1364
1714
  }
1365
1715
  /**
1366
1716
  * Retrieves the execution result for a specific workflow run by its ID
1367
1717
  * @param runId - The ID of the workflow run to retrieve the execution result for
1718
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1368
1719
  * @returns Promise containing the workflow run execution result
1369
1720
  */
1370
- runExecutionResult(runId) {
1371
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1721
+ runExecutionResult(runId, runtimeContext) {
1722
+ return this.request(
1723
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1724
+ );
1372
1725
  }
1373
1726
  /**
1374
1727
  * Cancels a specific workflow run by its ID
@@ -1391,91 +1744,752 @@ var Workflow = class extends BaseResource {
1391
1744
  body: { event: params.event, data: params.data }
1392
1745
  });
1393
1746
  }
1747
+ /**
1748
+ * @deprecated Use createRunAsync() instead.
1749
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1750
+ */
1751
+ async createRun(_params) {
1752
+ throw new Error(
1753
+ "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."
1754
+ );
1755
+ }
1394
1756
  /**
1395
1757
  * Creates a new workflow run
1396
1758
  * @param params - Optional object containing the optional runId
1397
- * @returns Promise containing the runId of the created run
1759
+ * @returns Promise containing the runId of the created run with methods to control execution
1398
1760
  */
1399
- createRun(params) {
1761
+ async createRunAsync(params) {
1400
1762
  const searchParams = new URLSearchParams();
1401
1763
  if (!!params?.runId) {
1402
1764
  searchParams.set("runId", params.runId);
1403
1765
  }
1404
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1405
- method: "POST"
1766
+ const res = await this.request(
1767
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1768
+ {
1769
+ method: "POST"
1770
+ }
1771
+ );
1772
+ const runId = res.runId;
1773
+ return {
1774
+ runId,
1775
+ start: async (p) => {
1776
+ return this.start({
1777
+ runId,
1778
+ inputData: p.inputData,
1779
+ runtimeContext: p.runtimeContext,
1780
+ tracingOptions: p.tracingOptions
1781
+ });
1782
+ },
1783
+ startAsync: async (p) => {
1784
+ return this.startAsync({
1785
+ runId,
1786
+ inputData: p.inputData,
1787
+ runtimeContext: p.runtimeContext,
1788
+ tracingOptions: p.tracingOptions
1789
+ });
1790
+ },
1791
+ watch: async (onRecord) => {
1792
+ return this.watch({ runId }, onRecord);
1793
+ },
1794
+ stream: async (p) => {
1795
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1796
+ },
1797
+ resume: async (p) => {
1798
+ return this.resume({
1799
+ runId,
1800
+ step: p.step,
1801
+ resumeData: p.resumeData,
1802
+ runtimeContext: p.runtimeContext,
1803
+ tracingOptions: p.tracingOptions
1804
+ });
1805
+ },
1806
+ resumeAsync: async (p) => {
1807
+ return this.resumeAsync({
1808
+ runId,
1809
+ step: p.step,
1810
+ resumeData: p.resumeData,
1811
+ runtimeContext: p.runtimeContext,
1812
+ tracingOptions: p.tracingOptions
1813
+ });
1814
+ },
1815
+ resumeStreamVNext: async (p) => {
1816
+ return this.resumeStreamVNext({
1817
+ runId,
1818
+ step: p.step,
1819
+ resumeData: p.resumeData,
1820
+ runtimeContext: p.runtimeContext
1821
+ });
1822
+ }
1823
+ };
1824
+ }
1825
+ /**
1826
+ * Starts a workflow run synchronously without waiting for the workflow to complete
1827
+ * @param params - Object containing the runId, inputData and runtimeContext
1828
+ * @returns Promise containing success message
1829
+ */
1830
+ start(params) {
1831
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1832
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1833
+ method: "POST",
1834
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1835
+ });
1836
+ }
1837
+ /**
1838
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1839
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1840
+ * @returns Promise containing success message
1841
+ */
1842
+ resume({
1843
+ step,
1844
+ runId,
1845
+ resumeData,
1846
+ tracingOptions,
1847
+ ...rest
1848
+ }) {
1849
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1850
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1851
+ method: "POST",
1852
+ body: {
1853
+ step,
1854
+ resumeData,
1855
+ runtimeContext,
1856
+ tracingOptions
1857
+ }
1858
+ });
1859
+ }
1860
+ /**
1861
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1862
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1863
+ * @returns Promise containing the workflow execution results
1864
+ */
1865
+ startAsync(params) {
1866
+ const searchParams = new URLSearchParams();
1867
+ if (!!params?.runId) {
1868
+ searchParams.set("runId", params.runId);
1869
+ }
1870
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1871
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1872
+ method: "POST",
1873
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1874
+ });
1875
+ }
1876
+ /**
1877
+ * Starts a workflow run and returns a stream
1878
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1879
+ * @returns Promise containing the workflow execution results
1880
+ */
1881
+ async stream(params) {
1882
+ const searchParams = new URLSearchParams();
1883
+ if (!!params?.runId) {
1884
+ searchParams.set("runId", params.runId);
1885
+ }
1886
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1887
+ const response = await this.request(
1888
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1889
+ {
1890
+ method: "POST",
1891
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions },
1892
+ stream: true
1893
+ }
1894
+ );
1895
+ if (!response.ok) {
1896
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1897
+ }
1898
+ if (!response.body) {
1899
+ throw new Error("Response body is null");
1900
+ }
1901
+ let failedChunk = void 0;
1902
+ const transformStream = new TransformStream({
1903
+ start() {
1904
+ },
1905
+ async transform(chunk, controller) {
1906
+ try {
1907
+ const decoded = new TextDecoder().decode(chunk);
1908
+ const chunks = decoded.split(RECORD_SEPARATOR);
1909
+ for (const chunk2 of chunks) {
1910
+ if (chunk2) {
1911
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1912
+ try {
1913
+ const parsedChunk = JSON.parse(newChunk);
1914
+ controller.enqueue(parsedChunk);
1915
+ failedChunk = void 0;
1916
+ } catch {
1917
+ failedChunk = newChunk;
1918
+ }
1919
+ }
1920
+ }
1921
+ } catch {
1922
+ }
1923
+ }
1924
+ });
1925
+ return response.body.pipeThrough(transformStream);
1926
+ }
1927
+ /**
1928
+ * Observes workflow stream for a workflow run
1929
+ * @param params - Object containing the runId
1930
+ * @returns Promise containing the workflow execution results
1931
+ */
1932
+ async observeStream(params) {
1933
+ const searchParams = new URLSearchParams();
1934
+ searchParams.set("runId", params.runId);
1935
+ const response = await this.request(
1936
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1937
+ {
1938
+ method: "POST",
1939
+ stream: true
1940
+ }
1941
+ );
1942
+ if (!response.ok) {
1943
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1944
+ }
1945
+ if (!response.body) {
1946
+ throw new Error("Response body is null");
1947
+ }
1948
+ let failedChunk = void 0;
1949
+ const transformStream = new TransformStream({
1950
+ start() {
1951
+ },
1952
+ async transform(chunk, controller) {
1953
+ try {
1954
+ const decoded = new TextDecoder().decode(chunk);
1955
+ const chunks = decoded.split(RECORD_SEPARATOR);
1956
+ for (const chunk2 of chunks) {
1957
+ if (chunk2) {
1958
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1959
+ try {
1960
+ const parsedChunk = JSON.parse(newChunk);
1961
+ controller.enqueue(parsedChunk);
1962
+ failedChunk = void 0;
1963
+ } catch {
1964
+ failedChunk = newChunk;
1965
+ }
1966
+ }
1967
+ }
1968
+ } catch {
1969
+ }
1970
+ }
1971
+ });
1972
+ return response.body.pipeThrough(transformStream);
1973
+ }
1974
+ /**
1975
+ * Starts a workflow run and returns a stream
1976
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1977
+ * @returns Promise containing the workflow execution results
1978
+ */
1979
+ async streamVNext(params) {
1980
+ const searchParams = new URLSearchParams();
1981
+ if (!!params?.runId) {
1982
+ searchParams.set("runId", params.runId);
1983
+ }
1984
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1985
+ const response = await this.request(
1986
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1987
+ {
1988
+ method: "POST",
1989
+ body: {
1990
+ inputData: params.inputData,
1991
+ runtimeContext,
1992
+ closeOnSuspend: params.closeOnSuspend,
1993
+ tracingOptions: params.tracingOptions
1994
+ },
1995
+ stream: true
1996
+ }
1997
+ );
1998
+ if (!response.ok) {
1999
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2000
+ }
2001
+ if (!response.body) {
2002
+ throw new Error("Response body is null");
2003
+ }
2004
+ let failedChunk = void 0;
2005
+ const transformStream = new TransformStream({
2006
+ start() {
2007
+ },
2008
+ async transform(chunk, controller) {
2009
+ try {
2010
+ const decoded = new TextDecoder().decode(chunk);
2011
+ const chunks = decoded.split(RECORD_SEPARATOR);
2012
+ for (const chunk2 of chunks) {
2013
+ if (chunk2) {
2014
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2015
+ try {
2016
+ const parsedChunk = JSON.parse(newChunk);
2017
+ controller.enqueue(parsedChunk);
2018
+ failedChunk = void 0;
2019
+ } catch {
2020
+ failedChunk = newChunk;
2021
+ }
2022
+ }
2023
+ }
2024
+ } catch {
2025
+ }
2026
+ }
2027
+ });
2028
+ return response.body.pipeThrough(transformStream);
2029
+ }
2030
+ /**
2031
+ * Observes workflow vNext stream for a workflow run
2032
+ * @param params - Object containing the runId
2033
+ * @returns Promise containing the workflow execution results
2034
+ */
2035
+ async observeStreamVNext(params) {
2036
+ const searchParams = new URLSearchParams();
2037
+ searchParams.set("runId", params.runId);
2038
+ const response = await this.request(
2039
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
2040
+ {
2041
+ method: "POST",
2042
+ stream: true
2043
+ }
2044
+ );
2045
+ if (!response.ok) {
2046
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
2047
+ }
2048
+ if (!response.body) {
2049
+ throw new Error("Response body is null");
2050
+ }
2051
+ let failedChunk = void 0;
2052
+ const transformStream = new TransformStream({
2053
+ start() {
2054
+ },
2055
+ async transform(chunk, controller) {
2056
+ try {
2057
+ const decoded = new TextDecoder().decode(chunk);
2058
+ const chunks = decoded.split(RECORD_SEPARATOR);
2059
+ for (const chunk2 of chunks) {
2060
+ if (chunk2) {
2061
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2062
+ try {
2063
+ const parsedChunk = JSON.parse(newChunk);
2064
+ controller.enqueue(parsedChunk);
2065
+ failedChunk = void 0;
2066
+ } catch {
2067
+ failedChunk = newChunk;
2068
+ }
2069
+ }
2070
+ }
2071
+ } catch {
2072
+ }
2073
+ }
2074
+ });
2075
+ return response.body.pipeThrough(transformStream);
2076
+ }
2077
+ /**
2078
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2079
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2080
+ * @returns Promise containing the workflow resume results
2081
+ */
2082
+ resumeAsync(params) {
2083
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2084
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2085
+ method: "POST",
2086
+ body: {
2087
+ step: params.step,
2088
+ resumeData: params.resumeData,
2089
+ runtimeContext,
2090
+ tracingOptions: params.tracingOptions
2091
+ }
2092
+ });
2093
+ }
2094
+ /**
2095
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2096
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2097
+ * @returns Promise containing the workflow resume results
2098
+ */
2099
+ async resumeStreamVNext(params) {
2100
+ const searchParams = new URLSearchParams();
2101
+ searchParams.set("runId", params.runId);
2102
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2103
+ const response = await this.request(
2104
+ `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
2105
+ {
2106
+ method: "POST",
2107
+ body: {
2108
+ step: params.step,
2109
+ resumeData: params.resumeData,
2110
+ runtimeContext,
2111
+ tracingOptions: params.tracingOptions
2112
+ },
2113
+ stream: true
2114
+ }
2115
+ );
2116
+ if (!response.ok) {
2117
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2118
+ }
2119
+ if (!response.body) {
2120
+ throw new Error("Response body is null");
2121
+ }
2122
+ let failedChunk = void 0;
2123
+ const transformStream = new TransformStream({
2124
+ start() {
2125
+ },
2126
+ async transform(chunk, controller) {
2127
+ try {
2128
+ const decoded = new TextDecoder().decode(chunk);
2129
+ const chunks = decoded.split(RECORD_SEPARATOR);
2130
+ for (const chunk2 of chunks) {
2131
+ if (chunk2) {
2132
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2133
+ try {
2134
+ const parsedChunk = JSON.parse(newChunk);
2135
+ controller.enqueue(parsedChunk);
2136
+ failedChunk = void 0;
2137
+ } catch {
2138
+ failedChunk = newChunk;
2139
+ }
2140
+ }
2141
+ }
2142
+ } catch {
2143
+ }
2144
+ }
2145
+ });
2146
+ return response.body.pipeThrough(transformStream);
2147
+ }
2148
+ /**
2149
+ * Watches workflow transitions in real-time
2150
+ * @param runId - Optional run ID to filter the watch stream
2151
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2152
+ */
2153
+ async watch({ runId }, onRecord) {
2154
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2155
+ stream: true
2156
+ });
2157
+ if (!response.ok) {
2158
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
2159
+ }
2160
+ if (!response.body) {
2161
+ throw new Error("Response body is null");
2162
+ }
2163
+ for await (const record of this.streamProcessor(response.body)) {
2164
+ if (typeof record === "string") {
2165
+ onRecord(JSON.parse(record));
2166
+ } else {
2167
+ onRecord(record);
2168
+ }
2169
+ }
2170
+ }
2171
+ /**
2172
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2173
+ * serializing each as JSON and separating them with the record separator (\x1E).
2174
+ *
2175
+ * @param records - An iterable or async iterable of objects to stream
2176
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2177
+ */
2178
+ static createRecordStream(records) {
2179
+ const encoder = new TextEncoder();
2180
+ return new ReadableStream({
2181
+ async start(controller) {
2182
+ try {
2183
+ for await (const record of records) {
2184
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
2185
+ controller.enqueue(encoder.encode(json));
2186
+ }
2187
+ controller.close();
2188
+ } catch (err) {
2189
+ controller.error(err);
2190
+ }
2191
+ }
2192
+ });
2193
+ }
2194
+ };
2195
+
2196
+ // src/resources/a2a.ts
2197
+ var A2A = class extends BaseResource {
2198
+ constructor(options, agentId) {
2199
+ super(options);
2200
+ this.agentId = agentId;
2201
+ }
2202
+ /**
2203
+ * Get the agent card with metadata about the agent
2204
+ * @returns Promise containing the agent card information
2205
+ */
2206
+ async getCard() {
2207
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2208
+ }
2209
+ /**
2210
+ * Send a message to the agent and gets a message or task response
2211
+ * @param params - Parameters for the task
2212
+ * @returns Promise containing the response
2213
+ */
2214
+ async sendMessage(params) {
2215
+ const response = await this.request(`/a2a/${this.agentId}`, {
2216
+ method: "POST",
2217
+ body: {
2218
+ method: "message/send",
2219
+ params
2220
+ }
2221
+ });
2222
+ return response;
2223
+ }
2224
+ /**
2225
+ * Sends a message to an agent to initiate/continue a task and subscribes
2226
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2227
+ * @param params - Parameters for the task
2228
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2229
+ */
2230
+ async sendStreamingMessage(params) {
2231
+ const response = await this.request(`/a2a/${this.agentId}`, {
2232
+ method: "POST",
2233
+ body: {
2234
+ method: "message/stream",
2235
+ params
2236
+ }
2237
+ });
2238
+ return response;
2239
+ }
2240
+ /**
2241
+ * Get the status and result of a task
2242
+ * @param params - Parameters for querying the task
2243
+ * @returns Promise containing the task response
2244
+ */
2245
+ async getTask(params) {
2246
+ const response = await this.request(`/a2a/${this.agentId}`, {
2247
+ method: "POST",
2248
+ body: {
2249
+ method: "tasks/get",
2250
+ params
2251
+ }
2252
+ });
2253
+ return response;
2254
+ }
2255
+ /**
2256
+ * Cancel a running task
2257
+ * @param params - Parameters identifying the task to cancel
2258
+ * @returns Promise containing the task response
2259
+ */
2260
+ async cancelTask(params) {
2261
+ return this.request(`/a2a/${this.agentId}`, {
2262
+ method: "POST",
2263
+ body: {
2264
+ method: "tasks/cancel",
2265
+ params
2266
+ }
2267
+ });
2268
+ }
2269
+ };
2270
+
2271
+ // src/resources/mcp-tool.ts
2272
+ var MCPTool = class extends BaseResource {
2273
+ serverId;
2274
+ toolId;
2275
+ constructor(options, serverId, toolId) {
2276
+ super(options);
2277
+ this.serverId = serverId;
2278
+ this.toolId = toolId;
2279
+ }
2280
+ /**
2281
+ * Retrieves details about this specific tool from the MCP server.
2282
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2283
+ * @returns Promise containing the tool's information (name, description, schema).
2284
+ */
2285
+ details(runtimeContext) {
2286
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2287
+ }
2288
+ /**
2289
+ * Executes this specific tool on the MCP server.
2290
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2291
+ * @returns Promise containing the result of the tool execution.
2292
+ */
2293
+ execute(params) {
2294
+ const body = {};
2295
+ if (params.data !== void 0) body.data = params.data;
2296
+ if (params.runtimeContext !== void 0) {
2297
+ body.runtimeContext = params.runtimeContext;
2298
+ }
2299
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2300
+ method: "POST",
2301
+ body: Object.keys(body).length > 0 ? body : void 0
2302
+ });
2303
+ }
2304
+ };
2305
+
2306
+ // src/resources/agent-builder.ts
2307
+ var RECORD_SEPARATOR2 = "";
2308
+ var AgentBuilder = class extends BaseResource {
2309
+ constructor(options, actionId) {
2310
+ super(options);
2311
+ this.actionId = actionId;
2312
+ }
2313
+ // Helper function to transform workflow result to action result
2314
+ transformWorkflowResult(result) {
2315
+ if (result.status === "success") {
2316
+ return {
2317
+ success: result.result.success || false,
2318
+ applied: result.result.applied || false,
2319
+ branchName: result.result.branchName,
2320
+ message: result.result.message || "Agent builder action completed",
2321
+ validationResults: result.result.validationResults,
2322
+ error: result.result.error,
2323
+ errors: result.result.errors,
2324
+ stepResults: result.result.stepResults
2325
+ };
2326
+ } else if (result.status === "failed") {
2327
+ return {
2328
+ success: false,
2329
+ applied: false,
2330
+ message: `Agent builder action failed: ${result.error.message}`,
2331
+ error: result.error.message
2332
+ };
2333
+ } else {
2334
+ return {
2335
+ success: false,
2336
+ applied: false,
2337
+ message: "Agent builder action was suspended",
2338
+ error: "Workflow suspended - manual intervention required"
2339
+ };
2340
+ }
2341
+ }
2342
+ /**
2343
+ * @deprecated Use createRunAsync() instead.
2344
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2345
+ */
2346
+ async createRun(_params) {
2347
+ throw new Error(
2348
+ "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."
2349
+ );
2350
+ }
2351
+ /**
2352
+ * Creates a new agent builder action run and returns the runId.
2353
+ * This calls `/api/agent-builder/:actionId/create-run`.
2354
+ */
2355
+ async createRunAsync(params) {
2356
+ const searchParams = new URLSearchParams();
2357
+ if (!!params?.runId) {
2358
+ searchParams.set("runId", params.runId);
2359
+ }
2360
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2361
+ return this.request(url, {
2362
+ method: "POST"
2363
+ });
2364
+ }
2365
+ /**
2366
+ * Starts agent builder action asynchronously and waits for completion.
2367
+ * This calls `/api/agent-builder/:actionId/start-async`.
2368
+ */
2369
+ async startAsync(params, runId) {
2370
+ const searchParams = new URLSearchParams();
2371
+ if (runId) {
2372
+ searchParams.set("runId", runId);
2373
+ }
2374
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2375
+ const { runtimeContext: _, ...actionParams } = params;
2376
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2377
+ const result = await this.request(url, {
2378
+ method: "POST",
2379
+ body: { ...actionParams, runtimeContext }
1406
2380
  });
2381
+ return this.transformWorkflowResult(result);
1407
2382
  }
1408
2383
  /**
1409
- * Starts a workflow run synchronously without waiting for the workflow to complete
1410
- * @param params - Object containing the runId, inputData and runtimeContext
1411
- * @returns Promise containing success message
2384
+ * Starts an existing agent builder action run.
2385
+ * This calls `/api/agent-builder/:actionId/start`.
1412
2386
  */
1413
- start(params) {
2387
+ async startActionRun(params, runId) {
2388
+ const searchParams = new URLSearchParams();
2389
+ searchParams.set("runId", runId);
1414
2390
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1415
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
2391
+ const { runtimeContext: _, ...actionParams } = params;
2392
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2393
+ return this.request(url, {
1416
2394
  method: "POST",
1417
- body: { inputData: params?.inputData, runtimeContext }
2395
+ body: { ...actionParams, runtimeContext }
1418
2396
  });
1419
2397
  }
1420
2398
  /**
1421
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1422
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1423
- * @returns Promise containing success message
2399
+ * Resumes a suspended agent builder action step.
2400
+ * This calls `/api/agent-builder/:actionId/resume`.
1424
2401
  */
1425
- resume({
1426
- step,
1427
- runId,
1428
- resumeData,
1429
- ...rest
1430
- }) {
1431
- const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1432
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
2402
+ async resume(params, runId) {
2403
+ const searchParams = new URLSearchParams();
2404
+ searchParams.set("runId", runId);
2405
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2406
+ const { runtimeContext: _, ...resumeParams } = params;
2407
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2408
+ return this.request(url, {
1433
2409
  method: "POST",
1434
- stream: true,
1435
- body: {
1436
- step,
1437
- resumeData,
1438
- runtimeContext
1439
- }
2410
+ body: { ...resumeParams, runtimeContext }
1440
2411
  });
1441
2412
  }
1442
2413
  /**
1443
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1444
- * @param params - Object containing the optional runId, inputData and runtimeContext
1445
- * @returns Promise containing the workflow execution results
2414
+ * Resumes a suspended agent builder action step asynchronously.
2415
+ * This calls `/api/agent-builder/:actionId/resume-async`.
1446
2416
  */
1447
- startAsync(params) {
2417
+ async resumeAsync(params, runId) {
1448
2418
  const searchParams = new URLSearchParams();
1449
- if (!!params?.runId) {
1450
- searchParams.set("runId", params.runId);
1451
- }
2419
+ searchParams.set("runId", runId);
1452
2420
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1453
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
2421
+ const { runtimeContext: _, ...resumeParams } = params;
2422
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2423
+ const result = await this.request(url, {
1454
2424
  method: "POST",
1455
- body: { inputData: params.inputData, runtimeContext }
2425
+ body: { ...resumeParams, runtimeContext }
1456
2426
  });
2427
+ return this.transformWorkflowResult(result);
1457
2428
  }
1458
2429
  /**
1459
- * Starts a workflow run and returns a stream
1460
- * @param params - Object containing the optional runId, inputData and runtimeContext
1461
- * @returns Promise containing the workflow execution results
2430
+ * Creates an async generator that processes a readable stream and yields action records
2431
+ * separated by the Record Separator character (\x1E)
2432
+ *
2433
+ * @param stream - The readable stream to process
2434
+ * @returns An async generator that yields parsed records
1462
2435
  */
1463
- async stream(params) {
2436
+ async *streamProcessor(stream) {
2437
+ const reader = stream.getReader();
2438
+ let doneReading = false;
2439
+ let buffer = "";
2440
+ try {
2441
+ while (!doneReading) {
2442
+ const { done, value } = await reader.read();
2443
+ doneReading = done;
2444
+ if (done && !value) continue;
2445
+ try {
2446
+ const decoded = value ? new TextDecoder().decode(value) : "";
2447
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2448
+ buffer = chunks.pop() || "";
2449
+ for (const chunk of chunks) {
2450
+ if (chunk) {
2451
+ if (typeof chunk === "string") {
2452
+ try {
2453
+ const parsedChunk = JSON.parse(chunk);
2454
+ yield parsedChunk;
2455
+ } catch {
2456
+ }
2457
+ }
2458
+ }
2459
+ }
2460
+ } catch {
2461
+ }
2462
+ }
2463
+ if (buffer) {
2464
+ try {
2465
+ yield JSON.parse(buffer);
2466
+ } catch {
2467
+ }
2468
+ }
2469
+ } finally {
2470
+ reader.cancel().catch(() => {
2471
+ });
2472
+ }
2473
+ }
2474
+ /**
2475
+ * Streams agent builder action progress in real-time.
2476
+ * This calls `/api/agent-builder/:actionId/stream`.
2477
+ */
2478
+ async stream(params, runId) {
1464
2479
  const searchParams = new URLSearchParams();
1465
- if (!!params?.runId) {
1466
- searchParams.set("runId", params.runId);
2480
+ if (runId) {
2481
+ searchParams.set("runId", runId);
1467
2482
  }
1468
2483
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1469
- const response = await this.request(
1470
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1471
- {
1472
- method: "POST",
1473
- body: { inputData: params.inputData, runtimeContext },
1474
- stream: true
1475
- }
1476
- );
2484
+ const { runtimeContext: _, ...actionParams } = params;
2485
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2486
+ const response = await this.request(url, {
2487
+ method: "POST",
2488
+ body: { ...actionParams, runtimeContext },
2489
+ stream: true
2490
+ });
1477
2491
  if (!response.ok) {
1478
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2492
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
1479
2493
  }
1480
2494
  if (!response.body) {
1481
2495
  throw new Error("Response body is null");
@@ -1495,7 +2509,7 @@ var Workflow = class extends BaseResource {
1495
2509
  const parsedChunk = JSON.parse(newChunk);
1496
2510
  controller.enqueue(parsedChunk);
1497
2511
  failedChunk = void 0;
1498
- } catch (error) {
2512
+ } catch {
1499
2513
  failedChunk = newChunk;
1500
2514
  }
1501
2515
  }
@@ -1507,32 +2521,68 @@ var Workflow = class extends BaseResource {
1507
2521
  return response.body.pipeThrough(transformStream);
1508
2522
  }
1509
2523
  /**
1510
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1511
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1512
- * @returns Promise containing the workflow resume results
2524
+ * Streams agent builder action progress in real-time using VNext streaming.
2525
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
1513
2526
  */
1514
- resumeAsync(params) {
2527
+ async streamVNext(params, runId) {
2528
+ const searchParams = new URLSearchParams();
2529
+ if (runId) {
2530
+ searchParams.set("runId", runId);
2531
+ }
1515
2532
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1516
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2533
+ const { runtimeContext: _, ...actionParams } = params;
2534
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2535
+ const response = await this.request(url, {
1517
2536
  method: "POST",
1518
- body: {
1519
- step: params.step,
1520
- resumeData: params.resumeData,
1521
- runtimeContext
2537
+ body: { ...actionParams, runtimeContext },
2538
+ stream: true
2539
+ });
2540
+ if (!response.ok) {
2541
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2542
+ }
2543
+ if (!response.body) {
2544
+ throw new Error("Response body is null");
2545
+ }
2546
+ let failedChunk = void 0;
2547
+ const transformStream = new TransformStream({
2548
+ start() {
2549
+ },
2550
+ async transform(chunk, controller) {
2551
+ try {
2552
+ const decoded = new TextDecoder().decode(chunk);
2553
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2554
+ for (const chunk2 of chunks) {
2555
+ if (chunk2) {
2556
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2557
+ try {
2558
+ const parsedChunk = JSON.parse(newChunk);
2559
+ controller.enqueue(parsedChunk);
2560
+ failedChunk = void 0;
2561
+ } catch {
2562
+ failedChunk = newChunk;
2563
+ }
2564
+ }
2565
+ }
2566
+ } catch {
2567
+ }
1522
2568
  }
1523
2569
  });
2570
+ return response.body.pipeThrough(transformStream);
1524
2571
  }
1525
2572
  /**
1526
- * Watches workflow transitions in real-time
1527
- * @param runId - Optional run ID to filter the watch stream
1528
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2573
+ * Watches an existing agent builder action run by runId.
2574
+ * This is used for hot reload recovery - it loads the existing run state
2575
+ * and streams any remaining progress.
2576
+ * This calls `/api/agent-builder/:actionId/watch`.
1529
2577
  */
1530
- async watch({ runId }, onRecord) {
1531
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2578
+ async watch({ runId, eventType }, onRecord) {
2579
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2580
+ const response = await this.request(url, {
2581
+ method: "GET",
1532
2582
  stream: true
1533
2583
  });
1534
2584
  if (!response.ok) {
1535
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
2585
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
1536
2586
  }
1537
2587
  if (!response.body) {
1538
2588
  throw new Error("Response body is null");
@@ -1546,134 +2596,154 @@ var Workflow = class extends BaseResource {
1546
2596
  }
1547
2597
  }
1548
2598
  /**
1549
- * Creates a new ReadableStream from an iterable or async iterable of objects,
1550
- * serializing each as JSON and separating them with the record separator (\x1E).
1551
- *
1552
- * @param records - An iterable or async iterable of objects to stream
1553
- * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2599
+ * Gets a specific action run by its ID.
2600
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
1554
2601
  */
1555
- static createRecordStream(records) {
1556
- const encoder = new TextEncoder();
1557
- return new ReadableStream({
1558
- async start(controller) {
1559
- try {
1560
- for await (const record of records) {
1561
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1562
- controller.enqueue(encoder.encode(json));
1563
- }
1564
- controller.close();
1565
- } catch (err) {
1566
- controller.error(err);
1567
- }
1568
- }
2602
+ async runById(runId) {
2603
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2604
+ return this.request(url, {
2605
+ method: "GET"
1569
2606
  });
1570
2607
  }
1571
- };
1572
-
1573
- // src/resources/a2a.ts
1574
- var A2A = class extends BaseResource {
1575
- constructor(options, agentId) {
1576
- super(options);
1577
- this.agentId = agentId;
1578
- }
1579
2608
  /**
1580
- * Get the agent card with metadata about the agent
1581
- * @returns Promise containing the agent card information
2609
+ * Gets details about this agent builder action.
2610
+ * This calls `/api/agent-builder/:actionId`.
1582
2611
  */
1583
- async getCard() {
1584
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2612
+ async details() {
2613
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2614
+ return result;
1585
2615
  }
1586
2616
  /**
1587
- * Send a message to the agent and get a response
1588
- * @param params - Parameters for the task
1589
- * @returns Promise containing the task response
2617
+ * Gets all runs for this agent builder action.
2618
+ * This calls `/api/agent-builder/:actionId/runs`.
1590
2619
  */
1591
- async sendMessage(params) {
1592
- const response = await this.request(`/a2a/${this.agentId}`, {
1593
- method: "POST",
1594
- body: {
1595
- method: "tasks/send",
1596
- params
1597
- }
2620
+ async runs(params) {
2621
+ const searchParams = new URLSearchParams();
2622
+ if (params?.fromDate) {
2623
+ searchParams.set("fromDate", params.fromDate.toISOString());
2624
+ }
2625
+ if (params?.toDate) {
2626
+ searchParams.set("toDate", params.toDate.toISOString());
2627
+ }
2628
+ if (params?.limit !== void 0) {
2629
+ searchParams.set("limit", String(params.limit));
2630
+ }
2631
+ if (params?.offset !== void 0) {
2632
+ searchParams.set("offset", String(params.offset));
2633
+ }
2634
+ if (params?.resourceId) {
2635
+ searchParams.set("resourceId", params.resourceId);
2636
+ }
2637
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2638
+ return this.request(url, {
2639
+ method: "GET"
1598
2640
  });
1599
- return { task: response.result };
1600
2641
  }
1601
2642
  /**
1602
- * Get the status and result of a task
1603
- * @param params - Parameters for querying the task
1604
- * @returns Promise containing the task response
2643
+ * Gets the execution result of an agent builder action run.
2644
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
1605
2645
  */
1606
- async getTask(params) {
1607
- const response = await this.request(`/a2a/${this.agentId}`, {
1608
- method: "POST",
1609
- body: {
1610
- method: "tasks/get",
1611
- params
1612
- }
2646
+ async runExecutionResult(runId) {
2647
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2648
+ return this.request(url, {
2649
+ method: "GET"
1613
2650
  });
1614
- return response.result;
1615
2651
  }
1616
2652
  /**
1617
- * Cancel a running task
1618
- * @param params - Parameters identifying the task to cancel
1619
- * @returns Promise containing the task response
2653
+ * Cancels an agent builder action run.
2654
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
1620
2655
  */
1621
- async cancelTask(params) {
1622
- return this.request(`/a2a/${this.agentId}`, {
1623
- method: "POST",
1624
- body: {
1625
- method: "tasks/cancel",
1626
- params
1627
- }
2656
+ async cancelRun(runId) {
2657
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2658
+ return this.request(url, {
2659
+ method: "POST"
1628
2660
  });
1629
2661
  }
1630
2662
  /**
1631
- * Send a message and subscribe to streaming updates (not fully implemented)
1632
- * @param params - Parameters for the task
1633
- * @returns Promise containing the task response
2663
+ * Sends an event to an agent builder action run.
2664
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
1634
2665
  */
1635
- async sendAndSubscribe(params) {
1636
- return this.request(`/a2a/${this.agentId}`, {
2666
+ async sendRunEvent(params) {
2667
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2668
+ return this.request(url, {
1637
2669
  method: "POST",
1638
- body: {
1639
- method: "tasks/sendSubscribe",
1640
- params
1641
- },
1642
- stream: true
2670
+ body: { event: params.event, data: params.data }
1643
2671
  });
1644
2672
  }
1645
2673
  };
1646
2674
 
1647
- // src/resources/mcp-tool.ts
1648
- var MCPTool = class extends BaseResource {
1649
- serverId;
1650
- toolId;
1651
- constructor(options, serverId, toolId) {
2675
+ // src/resources/observability.ts
2676
+ var Observability = class extends BaseResource {
2677
+ constructor(options) {
1652
2678
  super(options);
1653
- this.serverId = serverId;
1654
- this.toolId = toolId;
1655
2679
  }
1656
2680
  /**
1657
- * Retrieves details about this specific tool from the MCP server.
1658
- * @returns Promise containing the tool's information (name, description, schema).
2681
+ * Retrieves a specific AI trace by ID
2682
+ * @param traceId - ID of the trace to retrieve
2683
+ * @returns Promise containing the AI trace with all its spans
1659
2684
  */
1660
- details() {
1661
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2685
+ getTrace(traceId) {
2686
+ return this.request(`/api/observability/traces/${traceId}`);
1662
2687
  }
1663
2688
  /**
1664
- * Executes this specific tool on the MCP server.
1665
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1666
- * @returns Promise containing the result of the tool execution.
2689
+ * Retrieves paginated list of AI traces with optional filtering
2690
+ * @param params - Parameters for pagination and filtering
2691
+ * @returns Promise containing paginated traces and pagination info
1667
2692
  */
1668
- execute(params) {
1669
- const body = {};
1670
- if (params.data !== void 0) body.data = params.data;
1671
- if (params.runtimeContext !== void 0) {
1672
- body.runtimeContext = params.runtimeContext;
2693
+ getTraces(params) {
2694
+ const { pagination, filters } = params;
2695
+ const { page, perPage, dateRange } = pagination || {};
2696
+ const { name, spanType, entityId, entityType } = filters || {};
2697
+ const searchParams = new URLSearchParams();
2698
+ if (page !== void 0) {
2699
+ searchParams.set("page", String(page));
2700
+ }
2701
+ if (perPage !== void 0) {
2702
+ searchParams.set("perPage", String(perPage));
2703
+ }
2704
+ if (name) {
2705
+ searchParams.set("name", name);
2706
+ }
2707
+ if (spanType !== void 0) {
2708
+ searchParams.set("spanType", String(spanType));
2709
+ }
2710
+ if (entityId && entityType) {
2711
+ searchParams.set("entityId", entityId);
2712
+ searchParams.set("entityType", entityType);
2713
+ }
2714
+ if (dateRange) {
2715
+ const dateRangeStr = JSON.stringify({
2716
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2717
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2718
+ });
2719
+ searchParams.set("dateRange", dateRangeStr);
2720
+ }
2721
+ const queryString = searchParams.toString();
2722
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2723
+ }
2724
+ /**
2725
+ * Retrieves scores by trace ID and span ID
2726
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2727
+ * @returns Promise containing scores and pagination info
2728
+ */
2729
+ getScoresBySpan(params) {
2730
+ const { traceId, spanId, page, perPage } = params;
2731
+ const searchParams = new URLSearchParams();
2732
+ if (page !== void 0) {
2733
+ searchParams.set("page", String(page));
1673
2734
  }
1674
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2735
+ if (perPage !== void 0) {
2736
+ searchParams.set("perPage", String(perPage));
2737
+ }
2738
+ const queryString = searchParams.toString();
2739
+ return this.request(
2740
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2741
+ );
2742
+ }
2743
+ score(params) {
2744
+ return this.request(`/api/observability/traces/score`, {
1675
2745
  method: "POST",
1676
- body: Object.keys(body).length > 0 ? body : void 0
2746
+ body: { ...params }
1677
2747
  });
1678
2748
  }
1679
2749
  };
@@ -1724,172 +2794,46 @@ var NetworkMemoryThread = class extends BaseResource {
1724
2794
  });
1725
2795
  return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1726
2796
  }
1727
- };
1728
-
1729
- // src/resources/vNextNetwork.ts
1730
- var RECORD_SEPARATOR3 = "";
1731
- var VNextNetwork = class extends BaseResource {
1732
- constructor(options, networkId) {
1733
- super(options);
1734
- this.networkId = networkId;
1735
- }
1736
- /**
1737
- * Retrieves details about the network
1738
- * @returns Promise containing vNext network details
1739
- */
1740
- details() {
1741
- return this.request(`/api/networks/v-next/${this.networkId}`);
1742
- }
1743
- /**
1744
- * Generates a response from the v-next network
1745
- * @param params - Generation parameters including message
1746
- * @returns Promise containing the generated response
1747
- */
1748
- generate(params) {
1749
- return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1750
- method: "POST",
1751
- body: {
1752
- ...params,
1753
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1754
- }
1755
- });
1756
- }
1757
- /**
1758
- * Generates a response from the v-next network using multiple primitives
1759
- * @param params - Generation parameters including message
1760
- * @returns Promise containing the generated response
1761
- */
1762
- loop(params) {
1763
- return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1764
- method: "POST",
1765
- body: {
1766
- ...params,
1767
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1768
- }
1769
- });
1770
- }
1771
- async *streamProcessor(stream) {
1772
- const reader = stream.getReader();
1773
- let doneReading = false;
1774
- let buffer = "";
1775
- try {
1776
- while (!doneReading) {
1777
- const { done, value } = await reader.read();
1778
- doneReading = done;
1779
- if (done && !value) continue;
1780
- try {
1781
- const decoded = value ? new TextDecoder().decode(value) : "";
1782
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1783
- buffer = chunks.pop() || "";
1784
- for (const chunk of chunks) {
1785
- if (chunk) {
1786
- if (typeof chunk === "string") {
1787
- try {
1788
- const parsedChunk = JSON.parse(chunk);
1789
- yield parsedChunk;
1790
- } catch {
1791
- }
1792
- }
1793
- }
1794
- }
1795
- } catch {
1796
- }
1797
- }
1798
- if (buffer) {
1799
- try {
1800
- yield JSON.parse(buffer);
1801
- } catch {
1802
- }
1803
- }
1804
- } finally {
1805
- reader.cancel().catch(() => {
1806
- });
1807
- }
1808
- }
1809
2797
  /**
1810
- * Streams a response from the v-next network
1811
- * @param params - Stream parameters including message
1812
- * @returns Promise containing the results
2798
+ * Deletes one or more messages from the thread
2799
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2800
+ * message object with id property, or array of message objects
2801
+ * @returns Promise containing deletion result
1813
2802
  */
1814
- async stream(params, onRecord) {
1815
- const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1816
- method: "POST",
1817
- body: {
1818
- ...params,
1819
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1820
- },
1821
- stream: true
2803
+ deleteMessages(messageIds) {
2804
+ const query = new URLSearchParams({
2805
+ networkId: this.networkId
1822
2806
  });
1823
- if (!response.ok) {
1824
- throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1825
- }
1826
- if (!response.body) {
1827
- throw new Error("Response body is null");
1828
- }
1829
- for await (const record of this.streamProcessor(response.body)) {
1830
- if (typeof record === "string") {
1831
- onRecord(JSON.parse(record));
1832
- } else {
1833
- onRecord(record);
1834
- }
1835
- }
1836
- }
1837
- /**
1838
- * Streams a response from the v-next network loop
1839
- * @param params - Stream parameters including message
1840
- * @returns Promise containing the results
1841
- */
1842
- async loopStream(params, onRecord) {
1843
- const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
2807
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
1844
2808
  method: "POST",
1845
- body: {
1846
- ...params,
1847
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1848
- },
1849
- stream: true
2809
+ body: { messageIds }
1850
2810
  });
1851
- if (!response.ok) {
1852
- throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1853
- }
1854
- if (!response.body) {
1855
- throw new Error("Response body is null");
1856
- }
1857
- for await (const record of this.streamProcessor(response.body)) {
1858
- if (typeof record === "string") {
1859
- onRecord(JSON.parse(record));
1860
- } else {
1861
- onRecord(record);
1862
- }
1863
- }
1864
2811
  }
1865
2812
  };
1866
2813
 
1867
2814
  // src/client.ts
1868
2815
  var MastraClient = class extends BaseResource {
2816
+ observability;
1869
2817
  constructor(options) {
1870
2818
  super(options);
2819
+ this.observability = new Observability(options);
1871
2820
  }
1872
2821
  /**
1873
2822
  * Retrieves all available agents
2823
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1874
2824
  * @returns Promise containing map of agent IDs to agent details
1875
2825
  */
1876
- getAgents() {
1877
- return this.request("/api/agents");
1878
- }
1879
- async getAGUI({ resourceId }) {
1880
- const agents = await this.getAgents();
1881
- return Object.entries(agents).reduce(
1882
- (acc, [agentId]) => {
1883
- const agent = this.getAgent(agentId);
1884
- acc[agentId] = new AGUIAdapter({
1885
- agentId,
1886
- agent,
1887
- resourceId
1888
- });
1889
- return acc;
1890
- },
1891
- {}
1892
- );
2826
+ getAgents(runtimeContext) {
2827
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2828
+ const searchParams = new URLSearchParams();
2829
+ if (runtimeContextParam) {
2830
+ searchParams.set("runtimeContext", runtimeContextParam);
2831
+ }
2832
+ const queryString = searchParams.toString();
2833
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
2834
+ }
2835
+ getAgentsModelProviders() {
2836
+ return this.request(`/api/agents/providers`);
1893
2837
  }
1894
2838
  /**
1895
2839
  * Gets an agent instance by ID
@@ -1901,19 +2845,34 @@ var MastraClient = class extends BaseResource {
1901
2845
  }
1902
2846
  /**
1903
2847
  * Retrieves memory threads for a resource
1904
- * @param params - Parameters containing the resource ID
2848
+ * @param params - Parameters containing the resource ID and optional runtime context
1905
2849
  * @returns Promise containing array of memory threads
1906
2850
  */
1907
2851
  getMemoryThreads(params) {
1908
- return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
2852
+ return this.request(
2853
+ `/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`
2854
+ );
2855
+ }
2856
+ /**
2857
+ * Retrieves memory config for a resource
2858
+ * @param params - Parameters containing the resource ID and optional runtime context
2859
+ * @returns Promise containing memory configuration
2860
+ */
2861
+ getMemoryConfig(params) {
2862
+ return this.request(
2863
+ `/api/memory/config?agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`
2864
+ );
1909
2865
  }
1910
2866
  /**
1911
2867
  * Creates a new memory thread
1912
- * @param params - Parameters for creating the memory thread
2868
+ * @param params - Parameters for creating the memory thread including optional runtime context
1913
2869
  * @returns Promise containing the created memory thread
1914
2870
  */
1915
2871
  createMemoryThread(params) {
1916
- return this.request(`/api/memory/threads?agentId=${params.agentId}`, { method: "POST", body: params });
2872
+ return this.request(
2873
+ `/api/memory/threads?agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`,
2874
+ { method: "POST", body: params }
2875
+ );
1917
2876
  }
1918
2877
  /**
1919
2878
  * Gets a memory thread instance by ID
@@ -1923,23 +2882,46 @@ var MastraClient = class extends BaseResource {
1923
2882
  getMemoryThread(threadId, agentId) {
1924
2883
  return new MemoryThread(this.options, threadId, agentId);
1925
2884
  }
2885
+ getThreadMessages(threadId, opts = {}) {
2886
+ let url = "";
2887
+ if (opts.agentId) {
2888
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2889
+ } else if (opts.networkId) {
2890
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2891
+ }
2892
+ return this.request(url);
2893
+ }
2894
+ deleteThread(threadId, opts = {}) {
2895
+ let url = "";
2896
+ if (opts.agentId) {
2897
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2898
+ } else if (opts.networkId) {
2899
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}${runtimeContextQueryString(opts.runtimeContext, "&")}`;
2900
+ }
2901
+ return this.request(url, { method: "DELETE" });
2902
+ }
1926
2903
  /**
1927
2904
  * Saves messages to memory
1928
- * @param params - Parameters containing messages to save
2905
+ * @param params - Parameters containing messages to save and optional runtime context
1929
2906
  * @returns Promise containing the saved messages
1930
2907
  */
1931
2908
  saveMessageToMemory(params) {
1932
- return this.request(`/api/memory/save-messages?agentId=${params.agentId}`, {
1933
- method: "POST",
1934
- body: params
1935
- });
2909
+ return this.request(
2910
+ `/api/memory/save-messages?agentId=${params.agentId}${runtimeContextQueryString(params.runtimeContext, "&")}`,
2911
+ {
2912
+ method: "POST",
2913
+ body: params
2914
+ }
2915
+ );
1936
2916
  }
1937
2917
  /**
1938
2918
  * Gets the status of the memory system
2919
+ * @param agentId - The agent ID
2920
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1939
2921
  * @returns Promise containing memory system status
1940
2922
  */
1941
- getMemoryStatus(agentId) {
1942
- return this.request(`/api/memory/status?agentId=${agentId}`);
2923
+ getMemoryStatus(agentId, runtimeContext) {
2924
+ return this.request(`/api/memory/status?agentId=${agentId}${runtimeContextQueryString(runtimeContext, "&")}`);
1943
2925
  }
1944
2926
  /**
1945
2927
  * Retrieves memory threads for a resource
@@ -1985,10 +2967,17 @@ var MastraClient = class extends BaseResource {
1985
2967
  }
1986
2968
  /**
1987
2969
  * Retrieves all available tools
2970
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1988
2971
  * @returns Promise containing map of tool IDs to tool details
1989
2972
  */
1990
- getTools() {
1991
- return this.request("/api/tools");
2973
+ getTools(runtimeContext) {
2974
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2975
+ const searchParams = new URLSearchParams();
2976
+ if (runtimeContextParam) {
2977
+ searchParams.set("runtimeContext", runtimeContextParam);
2978
+ }
2979
+ const queryString = searchParams.toString();
2980
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
1992
2981
  }
1993
2982
  /**
1994
2983
  * Gets a tool instance by ID
@@ -1996,29 +2985,21 @@ var MastraClient = class extends BaseResource {
1996
2985
  * @returns Tool instance
1997
2986
  */
1998
2987
  getTool(toolId) {
1999
- return new Tool2(this.options, toolId);
2000
- }
2001
- /**
2002
- * Retrieves all available legacy workflows
2003
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2004
- */
2005
- getLegacyWorkflows() {
2006
- return this.request("/api/workflows/legacy");
2007
- }
2008
- /**
2009
- * Gets a legacy workflow instance by ID
2010
- * @param workflowId - ID of the legacy workflow to retrieve
2011
- * @returns Legacy Workflow instance
2012
- */
2013
- getLegacyWorkflow(workflowId) {
2014
- return new LegacyWorkflow(this.options, workflowId);
2988
+ return new Tool(this.options, toolId);
2015
2989
  }
2016
2990
  /**
2017
2991
  * Retrieves all available workflows
2992
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2018
2993
  * @returns Promise containing map of workflow IDs to workflow details
2019
2994
  */
2020
- getWorkflows() {
2021
- return this.request("/api/workflows");
2995
+ getWorkflows(runtimeContext) {
2996
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2997
+ const searchParams = new URLSearchParams();
2998
+ if (runtimeContextParam) {
2999
+ searchParams.set("runtimeContext", runtimeContextParam);
3000
+ }
3001
+ const queryString = searchParams.toString();
3002
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
2022
3003
  }
2023
3004
  /**
2024
3005
  * Gets a workflow instance by ID
@@ -2028,6 +3009,20 @@ var MastraClient = class extends BaseResource {
2028
3009
  getWorkflow(workflowId) {
2029
3010
  return new Workflow(this.options, workflowId);
2030
3011
  }
3012
+ /**
3013
+ * Gets all available agent builder actions
3014
+ * @returns Promise containing map of action IDs to action details
3015
+ */
3016
+ getAgentBuilderActions() {
3017
+ return this.request("/api/agent-builder/");
3018
+ }
3019
+ /**
3020
+ * Gets an agent builder instance for executing agent-builder workflows
3021
+ * @returns AgentBuilder instance
3022
+ */
3023
+ getAgentBuilderAction(actionId) {
3024
+ return new AgentBuilder(this.options, actionId);
3025
+ }
2031
3026
  /**
2032
3027
  * Gets a vector instance by name
2033
3028
  * @param vectorName - Name of the vector to retrieve
@@ -2130,78 +3125,6 @@ var MastraClient = class extends BaseResource {
2130
3125
  getLogTransports() {
2131
3126
  return this.request("/api/logs/transports");
2132
3127
  }
2133
- /**
2134
- * List of all traces (paged)
2135
- * @param params - Parameters for filtering traces
2136
- * @returns Promise containing telemetry data
2137
- */
2138
- getTelemetry(params) {
2139
- const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
2140
- const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
2141
- const searchParams = new URLSearchParams();
2142
- if (name) {
2143
- searchParams.set("name", name);
2144
- }
2145
- if (scope) {
2146
- searchParams.set("scope", scope);
2147
- }
2148
- if (page) {
2149
- searchParams.set("page", String(page));
2150
- }
2151
- if (perPage) {
2152
- searchParams.set("perPage", String(perPage));
2153
- }
2154
- if (_attribute) {
2155
- if (Array.isArray(_attribute)) {
2156
- for (const attr of _attribute) {
2157
- searchParams.append("attribute", attr);
2158
- }
2159
- } else {
2160
- searchParams.set("attribute", _attribute);
2161
- }
2162
- }
2163
- if (fromDate) {
2164
- searchParams.set("fromDate", fromDate.toISOString());
2165
- }
2166
- if (toDate) {
2167
- searchParams.set("toDate", toDate.toISOString());
2168
- }
2169
- if (searchParams.size) {
2170
- return this.request(`/api/telemetry?${searchParams}`);
2171
- } else {
2172
- return this.request(`/api/telemetry`);
2173
- }
2174
- }
2175
- /**
2176
- * Retrieves all available networks
2177
- * @returns Promise containing map of network IDs to network details
2178
- */
2179
- getNetworks() {
2180
- return this.request("/api/networks");
2181
- }
2182
- /**
2183
- * Retrieves all available vNext networks
2184
- * @returns Promise containing map of vNext network IDs to vNext network details
2185
- */
2186
- getVNextNetworks() {
2187
- return this.request("/api/networks/v-next");
2188
- }
2189
- /**
2190
- * Gets a network instance by ID
2191
- * @param networkId - ID of the network to retrieve
2192
- * @returns Network instance
2193
- */
2194
- getNetwork(networkId) {
2195
- return new Network(this.options, networkId);
2196
- }
2197
- /**
2198
- * Gets a vNext network instance by ID
2199
- * @param networkId - ID of the vNext network to retrieve
2200
- * @returns vNext Network instance
2201
- */
2202
- getVNextNetwork(networkId) {
2203
- return new VNextNetwork(this.options, networkId);
2204
- }
2205
3128
  /**
2206
3129
  * Retrieves a list of available MCP servers.
2207
3130
  * @param params - Optional parameters for pagination (limit, offset).
@@ -2268,9 +3191,33 @@ var MastraClient = class extends BaseResource {
2268
3191
  getWorkingMemory({
2269
3192
  agentId,
2270
3193
  threadId,
2271
- resourceId
3194
+ resourceId,
3195
+ runtimeContext
3196
+ }) {
3197
+ return this.request(
3198
+ `/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}${runtimeContextQueryString(runtimeContext, "&")}`
3199
+ );
3200
+ }
3201
+ searchMemory({
3202
+ agentId,
3203
+ resourceId,
3204
+ threadId,
3205
+ searchQuery,
3206
+ memoryConfig,
3207
+ runtimeContext
2272
3208
  }) {
2273
- return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3209
+ const params = new URLSearchParams({
3210
+ searchQuery,
3211
+ resourceId,
3212
+ agentId
3213
+ });
3214
+ if (threadId) {
3215
+ params.append("threadId", threadId);
3216
+ }
3217
+ if (memoryConfig) {
3218
+ params.append("memoryConfig", JSON.stringify(memoryConfig));
3219
+ }
3220
+ return this.request(`/api/memory/search?${params}${runtimeContextQueryString(runtimeContext, "&")}`);
2274
3221
  }
2275
3222
  /**
2276
3223
  * Updates the working memory for a specific thread (optionally resource-scoped).
@@ -2283,16 +3230,142 @@ var MastraClient = class extends BaseResource {
2283
3230
  agentId,
2284
3231
  threadId,
2285
3232
  workingMemory,
2286
- resourceId
3233
+ resourceId,
3234
+ runtimeContext
2287
3235
  }) {
2288
- return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2289
- method: "POST",
2290
- body: {
2291
- workingMemory,
2292
- resourceId
3236
+ return this.request(
3237
+ `/api/memory/threads/${threadId}/working-memory?agentId=${agentId}${runtimeContextQueryString(runtimeContext, "&")}`,
3238
+ {
3239
+ method: "POST",
3240
+ body: {
3241
+ workingMemory,
3242
+ resourceId
3243
+ }
2293
3244
  }
3245
+ );
3246
+ }
3247
+ /**
3248
+ * Retrieves all available scorers
3249
+ * @returns Promise containing list of available scorers
3250
+ */
3251
+ getScorers() {
3252
+ return this.request("/api/scores/scorers");
3253
+ }
3254
+ /**
3255
+ * Retrieves a scorer by ID
3256
+ * @param scorerId - ID of the scorer to retrieve
3257
+ * @returns Promise containing the scorer
3258
+ */
3259
+ getScorer(scorerId) {
3260
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3261
+ }
3262
+ getScoresByScorerId(params) {
3263
+ const { page, perPage, scorerId, entityId, entityType } = params;
3264
+ const searchParams = new URLSearchParams();
3265
+ if (entityId) {
3266
+ searchParams.set("entityId", entityId);
3267
+ }
3268
+ if (entityType) {
3269
+ searchParams.set("entityType", entityType);
3270
+ }
3271
+ if (page !== void 0) {
3272
+ searchParams.set("page", String(page));
3273
+ }
3274
+ if (perPage !== void 0) {
3275
+ searchParams.set("perPage", String(perPage));
3276
+ }
3277
+ const queryString = searchParams.toString();
3278
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3279
+ }
3280
+ /**
3281
+ * Retrieves scores by run ID
3282
+ * @param params - Parameters containing run ID and pagination options
3283
+ * @returns Promise containing scores and pagination info
3284
+ */
3285
+ getScoresByRunId(params) {
3286
+ const { runId, page, perPage } = params;
3287
+ const searchParams = new URLSearchParams();
3288
+ if (page !== void 0) {
3289
+ searchParams.set("page", String(page));
3290
+ }
3291
+ if (perPage !== void 0) {
3292
+ searchParams.set("perPage", String(perPage));
3293
+ }
3294
+ const queryString = searchParams.toString();
3295
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
3296
+ }
3297
+ /**
3298
+ * Retrieves scores by entity ID and type
3299
+ * @param params - Parameters containing entity ID, type, and pagination options
3300
+ * @returns Promise containing scores and pagination info
3301
+ */
3302
+ getScoresByEntityId(params) {
3303
+ const { entityId, entityType, page, perPage } = params;
3304
+ const searchParams = new URLSearchParams();
3305
+ if (page !== void 0) {
3306
+ searchParams.set("page", String(page));
3307
+ }
3308
+ if (perPage !== void 0) {
3309
+ searchParams.set("perPage", String(perPage));
3310
+ }
3311
+ const queryString = searchParams.toString();
3312
+ return this.request(
3313
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3314
+ );
3315
+ }
3316
+ /**
3317
+ * Saves a score
3318
+ * @param params - Parameters containing the score data to save
3319
+ * @returns Promise containing the saved score
3320
+ */
3321
+ saveScore(params) {
3322
+ return this.request("/api/scores", {
3323
+ method: "POST",
3324
+ body: params
2294
3325
  });
2295
3326
  }
3327
+ /**
3328
+ * Retrieves model providers with available keys
3329
+ * @returns Promise containing model providers with available keys
3330
+ */
3331
+ getModelProviders() {
3332
+ return this.request(`/api/model-providers`);
3333
+ }
3334
+ getAITrace(traceId) {
3335
+ return this.observability.getTrace(traceId);
3336
+ }
3337
+ getAITraces(params) {
3338
+ return this.observability.getTraces(params);
3339
+ }
3340
+ getScoresBySpan(params) {
3341
+ return this.observability.getScoresBySpan(params);
3342
+ }
3343
+ score(params) {
3344
+ return this.observability.score(params);
3345
+ }
2296
3346
  };
2297
3347
 
3348
+ // src/tools.ts
3349
+ var ClientTool = class {
3350
+ id;
3351
+ description;
3352
+ inputSchema;
3353
+ outputSchema;
3354
+ execute;
3355
+ constructor(opts) {
3356
+ this.id = opts.id;
3357
+ this.description = opts.description;
3358
+ this.inputSchema = opts.inputSchema;
3359
+ this.outputSchema = opts.outputSchema;
3360
+ this.execute = opts.execute;
3361
+ }
3362
+ };
3363
+ function createTool(opts) {
3364
+ return new ClientTool(opts);
3365
+ }
3366
+
3367
+ exports.ClientTool = ClientTool;
2298
3368
  exports.MastraClient = MastraClient;
3369
+ exports.createTool = createTool;
3370
+ //# sourceMappingURL=index.cjs.map
3371
+ //# sourceMappingURL=index.cjs.map