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