@mastra/client-js 0.0.0-pass-headers-for-create-mastra-client-20250530010057 → 0.0.0-pgvector-index-fix-20250905222058

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 (79) hide show
  1. package/CHANGELOG.md +1358 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +7 -4
  4. package/dist/client.d.ts +280 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/example.d.ts +2 -0
  7. package/dist/example.d.ts.map +1 -0
  8. package/dist/index.cjs +2062 -286
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +4 -900
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +2064 -288
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources/a2a.d.ts +41 -0
  15. package/dist/resources/a2a.d.ts.map +1 -0
  16. package/dist/resources/agent-builder.d.ts +161 -0
  17. package/dist/resources/agent-builder.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +155 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +13 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/legacy-workflow.d.ts +87 -0
  25. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  26. package/dist/resources/mcp-tool.d.ts +27 -0
  27. package/dist/resources/mcp-tool.d.ts.map +1 -0
  28. package/dist/resources/memory-thread.d.ts +53 -0
  29. package/dist/resources/memory-thread.d.ts.map +1 -0
  30. package/dist/resources/network-memory-thread.d.ts +47 -0
  31. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  32. package/dist/resources/network.d.ts +30 -0
  33. package/dist/resources/network.d.ts.map +1 -0
  34. package/dist/resources/observability.d.ts +19 -0
  35. package/dist/resources/observability.d.ts.map +1 -0
  36. package/dist/resources/tool.d.ts +23 -0
  37. package/dist/resources/tool.d.ts.map +1 -0
  38. package/dist/resources/vNextNetwork.d.ts +42 -0
  39. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  40. package/dist/resources/vector.d.ts +48 -0
  41. package/dist/resources/vector.d.ts.map +1 -0
  42. package/dist/resources/workflow.d.ts +154 -0
  43. package/dist/resources/workflow.d.ts.map +1 -0
  44. package/dist/types.d.ts +461 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/utils/index.d.ts +3 -0
  47. package/dist/utils/index.d.ts.map +1 -0
  48. package/dist/utils/process-client-tools.d.ts +3 -0
  49. package/dist/utils/process-client-tools.d.ts.map +1 -0
  50. package/dist/utils/process-mastra-stream.d.ts +7 -0
  51. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  52. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  53. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  54. package/package.json +38 -21
  55. package/.turbo/turbo-build.log +0 -19
  56. package/dist/index.d.cts +0 -900
  57. package/eslint.config.js +0 -6
  58. package/src/adapters/agui.test.ts +0 -180
  59. package/src/adapters/agui.ts +0 -239
  60. package/src/client.ts +0 -334
  61. package/src/example.ts +0 -64
  62. package/src/index.test.ts +0 -830
  63. package/src/index.ts +0 -2
  64. package/src/resources/a2a.ts +0 -88
  65. package/src/resources/agent.ts +0 -197
  66. package/src/resources/base.ts +0 -70
  67. package/src/resources/index.ts +0 -10
  68. package/src/resources/legacy-workflow.ts +0 -242
  69. package/src/resources/mcp-tool.ts +0 -48
  70. package/src/resources/memory-thread.ts +0 -63
  71. package/src/resources/network.ts +0 -86
  72. package/src/resources/tool.ts +0 -45
  73. package/src/resources/vector.ts +0 -83
  74. package/src/resources/workflow.ts +0 -353
  75. package/src/types.ts +0 -314
  76. package/src/utils/index.ts +0 -11
  77. package/src/utils/zod-to-json-schema.ts +0 -10
  78. package/tsconfig.json +0 -5
  79. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,208 +1,105 @@
1
1
  'use strict';
2
2
 
3
- var client = require('@ag-ui/client');
4
- var rxjs = require('rxjs');
5
3
  var uiUtils = require('@ai-sdk/ui-utils');
4
+ var uuid = require('@lukeed/uuid');
5
+ var runtimeContext = require('@mastra/core/runtime-context');
6
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
6
7
  var zod = require('zod');
7
8
  var originalZodToJsonSchema = require('zod-to-json-schema');
8
- var runtimeContext = require('@mastra/core/runtime-context');
9
9
 
10
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
11
 
12
12
  var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
13
13
 
14
- // src/adapters/agui.ts
15
- var AGUIAdapter = class extends client.AbstractAgent {
16
- agent;
17
- resourceId;
18
- constructor({ agent, agentId, resourceId, ...rest }) {
19
- super({
20
- agentId,
21
- ...rest
22
- });
23
- this.agent = agent;
24
- this.resourceId = resourceId;
25
- }
26
- run(input) {
27
- return new rxjs.Observable((subscriber) => {
28
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
29
- subscriber.next({
30
- type: client.EventType.RUN_STARTED,
31
- threadId: input.threadId,
32
- runId: input.runId
33
- });
34
- this.agent.stream({
35
- threadId: input.threadId,
36
- resourceId: this.resourceId ?? "",
37
- runId: input.runId,
38
- messages: convertedMessages,
39
- clientTools: input.tools.reduce(
40
- (acc, tool) => {
41
- acc[tool.name] = {
42
- id: tool.name,
43
- description: tool.description,
44
- inputSchema: tool.parameters
45
- };
46
- return acc;
47
- },
48
- {}
49
- )
50
- }).then((response) => {
51
- let currentMessageId = void 0;
52
- let isInTextMessage = false;
53
- return response.processDataStream({
54
- onTextPart: (text) => {
55
- if (currentMessageId === void 0) {
56
- currentMessageId = generateUUID();
57
- const message2 = {
58
- type: client.EventType.TEXT_MESSAGE_START,
59
- messageId: currentMessageId,
60
- role: "assistant"
61
- };
62
- subscriber.next(message2);
63
- isInTextMessage = true;
64
- }
65
- const message = {
66
- type: client.EventType.TEXT_MESSAGE_CONTENT,
67
- messageId: currentMessageId,
68
- delta: text
69
- };
70
- subscriber.next(message);
71
- },
72
- onFinishMessagePart: () => {
73
- if (currentMessageId !== void 0) {
74
- const message = {
75
- type: client.EventType.TEXT_MESSAGE_END,
76
- messageId: currentMessageId
77
- };
78
- subscriber.next(message);
79
- isInTextMessage = false;
80
- }
81
- subscriber.next({
82
- type: client.EventType.RUN_FINISHED,
83
- threadId: input.threadId,
84
- runId: input.runId
85
- });
86
- subscriber.complete();
87
- },
88
- onToolCallPart(streamPart) {
89
- const parentMessageId = currentMessageId || generateUUID();
90
- if (isInTextMessage) {
91
- const message = {
92
- type: client.EventType.TEXT_MESSAGE_END,
93
- messageId: parentMessageId
94
- };
95
- subscriber.next(message);
96
- isInTextMessage = false;
97
- }
98
- subscriber.next({
99
- type: client.EventType.TOOL_CALL_START,
100
- toolCallId: streamPart.toolCallId,
101
- toolCallName: streamPart.toolName,
102
- parentMessageId
103
- });
104
- subscriber.next({
105
- type: client.EventType.TOOL_CALL_ARGS,
106
- toolCallId: streamPart.toolCallId,
107
- delta: JSON.stringify(streamPart.args),
108
- parentMessageId
109
- });
110
- subscriber.next({
111
- type: client.EventType.TOOL_CALL_END,
112
- toolCallId: streamPart.toolCallId,
113
- parentMessageId
114
- });
115
- }
116
- });
117
- }).catch((error) => {
118
- console.error("error", error);
119
- subscriber.error(error);
120
- });
121
- return () => {
122
- };
123
- });
124
- }
125
- };
126
- function generateUUID() {
127
- if (typeof crypto !== "undefined") {
128
- if (typeof crypto.randomUUID === "function") {
129
- return crypto.randomUUID();
130
- }
131
- if (typeof crypto.getRandomValues === "function") {
132
- const buffer = new Uint8Array(16);
133
- crypto.getRandomValues(buffer);
134
- buffer[6] = buffer[6] & 15 | 64;
135
- buffer[8] = buffer[8] & 63 | 128;
136
- let hex = "";
137
- for (let i = 0; i < 16; i++) {
138
- hex += buffer[i].toString(16).padStart(2, "0");
139
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
140
- }
141
- return hex;
14
+ // src/resources/agent.ts
15
+ function parseClientRuntimeContext(runtimeContext$1) {
16
+ if (runtimeContext$1) {
17
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
18
+ return Object.fromEntries(runtimeContext$1.entries());
142
19
  }
20
+ return runtimeContext$1;
143
21
  }
144
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
145
- const r = Math.random() * 16 | 0;
146
- const v = c === "x" ? r : r & 3 | 8;
147
- return v.toString(16);
148
- });
22
+ return void 0;
149
23
  }
150
- function convertMessagesToMastraMessages(messages) {
151
- const result = [];
152
- for (const message of messages) {
153
- if (message.role === "assistant") {
154
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
155
- for (const toolCall of message.toolCalls ?? []) {
156
- parts.push({
157
- type: "tool-call",
158
- toolCallId: toolCall.id,
159
- toolName: toolCall.function.name,
160
- args: JSON.parse(toolCall.function.arguments)
161
- });
162
- }
163
- result.push({
164
- role: "assistant",
165
- content: parts
166
- });
167
- if (message.toolCalls?.length) {
168
- result.push({
169
- role: "tool",
170
- content: message.toolCalls.map((toolCall) => ({
171
- type: "tool-result",
172
- toolCallId: toolCall.id,
173
- toolName: toolCall.function.name,
174
- result: JSON.parse(toolCall.function.arguments)
175
- }))
176
- });
177
- }
178
- } else if (message.role === "user") {
179
- result.push({
180
- role: "user",
181
- content: message.content || ""
182
- });
183
- } else if (message.role === "tool") {
184
- result.push({
185
- role: "tool",
186
- content: [
187
- {
188
- type: "tool-result",
189
- toolCallId: message.toolCallId,
190
- toolName: "unknown",
191
- result: message.content
192
- }
193
- ]
194
- });
195
- }
196
- }
197
- return result;
24
+ function isZodType(value) {
25
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
198
26
  }
199
27
  function zodToJsonSchema(zodSchema) {
200
- if (!(zodSchema instanceof zod.ZodSchema)) {
28
+ if (!isZodType(zodSchema)) {
201
29
  return zodSchema;
202
30
  }
31
+ if ("toJSONSchema" in zod.z) {
32
+ const fn = "toJSONSchema";
33
+ return zod.z[fn].call(zod.z, zodSchema);
34
+ }
203
35
  return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
204
36
  }
205
37
 
38
+ // src/utils/process-client-tools.ts
39
+ function processClientTools(clientTools) {
40
+ if (!clientTools) {
41
+ return void 0;
42
+ }
43
+ return Object.fromEntries(
44
+ Object.entries(clientTools).map(([key, value]) => {
45
+ if (isVercelTool.isVercelTool(value)) {
46
+ return [
47
+ key,
48
+ {
49
+ ...value,
50
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
51
+ }
52
+ ];
53
+ } else {
54
+ return [
55
+ key,
56
+ {
57
+ ...value,
58
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
59
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
60
+ }
61
+ ];
62
+ }
63
+ })
64
+ );
65
+ }
66
+
67
+ // src/utils/process-mastra-stream.ts
68
+ async function processMastraStream({
69
+ stream,
70
+ onChunk
71
+ }) {
72
+ const reader = stream.getReader();
73
+ const decoder = new TextDecoder();
74
+ let buffer = "";
75
+ try {
76
+ while (true) {
77
+ const { done, value } = await reader.read();
78
+ if (done) break;
79
+ buffer += decoder.decode(value, { stream: true });
80
+ const lines = buffer.split("\n\n");
81
+ buffer = lines.pop() || "";
82
+ for (const line of lines) {
83
+ if (line.startsWith("data: ")) {
84
+ const data = line.slice(6);
85
+ if (data === "[DONE]") {
86
+ console.log("\u{1F3C1} Stream finished");
87
+ return;
88
+ }
89
+ try {
90
+ const json = JSON.parse(data);
91
+ await onChunk(json);
92
+ } catch (error) {
93
+ console.error("\u274C JSON parse error:", error, "Data:", data);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ } finally {
99
+ reader.releaseLock();
100
+ }
101
+ }
102
+
206
103
  // src/resources/base.ts
207
104
  var BaseResource = class {
208
105
  options;
@@ -217,18 +114,21 @@ var BaseResource = class {
217
114
  */
218
115
  async request(path, options = {}) {
219
116
  let lastError = null;
220
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
117
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
221
118
  let delay = backoffMs;
222
119
  for (let attempt = 0; attempt <= retries; attempt++) {
223
120
  try {
224
121
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
225
122
  ...options,
226
123
  headers: {
124
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
227
125
  ...headers,
228
126
  ...options.headers
229
127
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
230
128
  // 'x-mastra-client-type': 'js',
231
129
  },
130
+ signal: this.options.abortSignal,
131
+ credentials: options.credentials ?? credentials,
232
132
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
233
133
  });
234
134
  if (!response.ok) {
@@ -261,17 +161,65 @@ var BaseResource = class {
261
161
  throw lastError || new Error("Request failed");
262
162
  }
263
163
  };
264
- function parseClientRuntimeContext(runtimeContext$1) {
265
- if (runtimeContext$1) {
266
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
267
- return Object.fromEntries(runtimeContext$1.entries());
164
+
165
+ // src/resources/agent.ts
166
+ async function executeToolCallAndRespond({
167
+ response,
168
+ params,
169
+ runId,
170
+ resourceId,
171
+ threadId,
172
+ runtimeContext,
173
+ respondFn
174
+ }) {
175
+ if (response.finishReason === "tool-calls") {
176
+ const toolCalls = response.toolCalls;
177
+ if (!toolCalls || !Array.isArray(toolCalls)) {
178
+ return response;
179
+ }
180
+ for (const toolCall of toolCalls) {
181
+ const clientTool = params.clientTools?.[toolCall.toolName];
182
+ if (clientTool && clientTool.execute) {
183
+ const result = await clientTool.execute(
184
+ {
185
+ context: toolCall?.args,
186
+ runId,
187
+ resourceId,
188
+ threadId,
189
+ runtimeContext,
190
+ tracingContext: { currentSpan: void 0 }
191
+ },
192
+ {
193
+ messages: response.messages,
194
+ toolCallId: toolCall?.toolCallId
195
+ }
196
+ );
197
+ const updatedMessages = [
198
+ {
199
+ role: "user",
200
+ content: params.messages
201
+ },
202
+ ...response.response.messages,
203
+ {
204
+ role: "tool",
205
+ content: [
206
+ {
207
+ type: "tool-result",
208
+ toolCallId: toolCall.toolCallId,
209
+ toolName: toolCall.toolName,
210
+ result
211
+ }
212
+ ]
213
+ }
214
+ ];
215
+ return respondFn({
216
+ ...params,
217
+ messages: updatedMessages
218
+ });
219
+ }
268
220
  }
269
- return runtimeContext$1;
270
221
  }
271
- return void 0;
272
222
  }
273
-
274
- // src/resources/agent.ts
275
223
  var AgentVoice = class extends BaseResource {
276
224
  constructor(options, agentId) {
277
225
  super(options);
@@ -318,6 +266,13 @@ var AgentVoice = class extends BaseResource {
318
266
  getSpeakers() {
319
267
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
320
268
  }
269
+ /**
270
+ * Get the listener configuration for the agent's voice provider
271
+ * @returns Promise containing a check if the agent has listening capabilities
272
+ */
273
+ getListener() {
274
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
275
+ }
321
276
  };
322
277
  var Agent = class extends BaseResource {
323
278
  constructor(options, agentId) {
@@ -333,22 +288,366 @@ var Agent = class extends BaseResource {
333
288
  details() {
334
289
  return this.request(`/api/agents/${this.agentId}`);
335
290
  }
336
- /**
337
- * Generates a response from the agent
338
- * @param params - Generation parameters including prompt
339
- * @returns Promise containing the generated response
340
- */
341
- generate(params) {
291
+ async generate(params) {
292
+ console.warn(
293
+ "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th. Please use generateLegacy if you don't want to upgrade just yet."
294
+ );
295
+ return this.generateLegacy(params);
296
+ }
297
+ async generateLegacy(params) {
342
298
  const processedParams = {
343
299
  ...params,
344
300
  output: params.output ? zodToJsonSchema(params.output) : void 0,
345
301
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
346
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
302
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
303
+ clientTools: processClientTools(params.clientTools)
347
304
  };
348
- return this.request(`/api/agents/${this.agentId}/generate`, {
349
- method: "POST",
350
- body: processedParams
305
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
306
+ const response = await this.request(
307
+ `/api/agents/${this.agentId}/generate-legacy`,
308
+ {
309
+ method: "POST",
310
+ body: processedParams
311
+ }
312
+ );
313
+ if (response.finishReason === "tool-calls") {
314
+ const toolCalls = response.toolCalls;
315
+ if (!toolCalls || !Array.isArray(toolCalls)) {
316
+ return response;
317
+ }
318
+ for (const toolCall of toolCalls) {
319
+ const clientTool = params.clientTools?.[toolCall.toolName];
320
+ if (clientTool && clientTool.execute) {
321
+ const result = await clientTool.execute(
322
+ {
323
+ context: toolCall?.args,
324
+ runId,
325
+ resourceId,
326
+ threadId,
327
+ runtimeContext,
328
+ tracingContext: { currentSpan: void 0 }
329
+ },
330
+ {
331
+ messages: response.messages,
332
+ toolCallId: toolCall?.toolCallId
333
+ }
334
+ );
335
+ const updatedMessages = [
336
+ {
337
+ role: "user",
338
+ content: params.messages
339
+ },
340
+ ...response.response.messages,
341
+ {
342
+ role: "tool",
343
+ content: [
344
+ {
345
+ type: "tool-result",
346
+ toolCallId: toolCall.toolCallId,
347
+ toolName: toolCall.toolName,
348
+ result
349
+ }
350
+ ]
351
+ }
352
+ ];
353
+ return this.generate({
354
+ ...params,
355
+ messages: updatedMessages
356
+ });
357
+ }
358
+ }
359
+ }
360
+ return response;
361
+ }
362
+ async generateVNext(params) {
363
+ const processedParams = {
364
+ ...params,
365
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
366
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
367
+ clientTools: processClientTools(params.clientTools)
368
+ };
369
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
370
+ const response = await this.request(
371
+ `/api/agents/${this.agentId}/generate/vnext`,
372
+ {
373
+ method: "POST",
374
+ body: processedParams
375
+ }
376
+ );
377
+ if (response.finishReason === "tool-calls") {
378
+ return executeToolCallAndRespond({
379
+ response,
380
+ params,
381
+ runId,
382
+ resourceId,
383
+ threadId,
384
+ runtimeContext,
385
+ respondFn: this.generateVNext.bind(this)
386
+ });
387
+ }
388
+ return response;
389
+ }
390
+ async processChatResponse({
391
+ stream,
392
+ update,
393
+ onToolCall,
394
+ onFinish,
395
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
396
+ lastMessage
397
+ }) {
398
+ const replaceLastMessage = lastMessage?.role === "assistant";
399
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
400
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
401
+ return Math.max(max, toolInvocation.step ?? 0);
402
+ }, 0) ?? 0) : 0;
403
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
404
+ id: uuid.v4(),
405
+ createdAt: getCurrentDate(),
406
+ role: "assistant",
407
+ content: "",
408
+ parts: []
409
+ };
410
+ let currentTextPart = void 0;
411
+ let currentReasoningPart = void 0;
412
+ let currentReasoningTextDetail = void 0;
413
+ function updateToolInvocationPart(toolCallId, invocation) {
414
+ const part = message.parts.find(
415
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
416
+ );
417
+ if (part != null) {
418
+ part.toolInvocation = invocation;
419
+ } else {
420
+ message.parts.push({
421
+ type: "tool-invocation",
422
+ toolInvocation: invocation
423
+ });
424
+ }
425
+ }
426
+ const data = [];
427
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
428
+ const partialToolCalls = {};
429
+ let usage = {
430
+ completionTokens: NaN,
431
+ promptTokens: NaN,
432
+ totalTokens: NaN
433
+ };
434
+ let finishReason = "unknown";
435
+ function execUpdate() {
436
+ const copiedData = [...data];
437
+ if (messageAnnotations?.length) {
438
+ message.annotations = messageAnnotations;
439
+ }
440
+ const copiedMessage = {
441
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
442
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
443
+ ...structuredClone(message),
444
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
445
+ // hashing approach by default to detect changes, but it only works for shallow
446
+ // changes. This is why we need to add a revision id to ensure that the message
447
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
448
+ // forwarded to rendering):
449
+ revisionId: uuid.v4()
450
+ };
451
+ update({
452
+ message: copiedMessage,
453
+ data: copiedData,
454
+ replaceLastMessage
455
+ });
456
+ }
457
+ await uiUtils.processDataStream({
458
+ stream,
459
+ onTextPart(value) {
460
+ if (currentTextPart == null) {
461
+ currentTextPart = {
462
+ type: "text",
463
+ text: value
464
+ };
465
+ message.parts.push(currentTextPart);
466
+ } else {
467
+ currentTextPart.text += value;
468
+ }
469
+ message.content += value;
470
+ execUpdate();
471
+ },
472
+ onReasoningPart(value) {
473
+ if (currentReasoningTextDetail == null) {
474
+ currentReasoningTextDetail = { type: "text", text: value };
475
+ if (currentReasoningPart != null) {
476
+ currentReasoningPart.details.push(currentReasoningTextDetail);
477
+ }
478
+ } else {
479
+ currentReasoningTextDetail.text += value;
480
+ }
481
+ if (currentReasoningPart == null) {
482
+ currentReasoningPart = {
483
+ type: "reasoning",
484
+ reasoning: value,
485
+ details: [currentReasoningTextDetail]
486
+ };
487
+ message.parts.push(currentReasoningPart);
488
+ } else {
489
+ currentReasoningPart.reasoning += value;
490
+ }
491
+ message.reasoning = (message.reasoning ?? "") + value;
492
+ execUpdate();
493
+ },
494
+ onReasoningSignaturePart(value) {
495
+ if (currentReasoningTextDetail != null) {
496
+ currentReasoningTextDetail.signature = value.signature;
497
+ }
498
+ },
499
+ onRedactedReasoningPart(value) {
500
+ if (currentReasoningPart == null) {
501
+ currentReasoningPart = {
502
+ type: "reasoning",
503
+ reasoning: "",
504
+ details: []
505
+ };
506
+ message.parts.push(currentReasoningPart);
507
+ }
508
+ currentReasoningPart.details.push({
509
+ type: "redacted",
510
+ data: value.data
511
+ });
512
+ currentReasoningTextDetail = void 0;
513
+ execUpdate();
514
+ },
515
+ onFilePart(value) {
516
+ message.parts.push({
517
+ type: "file",
518
+ mimeType: value.mimeType,
519
+ data: value.data
520
+ });
521
+ execUpdate();
522
+ },
523
+ onSourcePart(value) {
524
+ message.parts.push({
525
+ type: "source",
526
+ source: value
527
+ });
528
+ execUpdate();
529
+ },
530
+ onToolCallStreamingStartPart(value) {
531
+ if (message.toolInvocations == null) {
532
+ message.toolInvocations = [];
533
+ }
534
+ partialToolCalls[value.toolCallId] = {
535
+ text: "",
536
+ step,
537
+ toolName: value.toolName,
538
+ index: message.toolInvocations.length
539
+ };
540
+ const invocation = {
541
+ state: "partial-call",
542
+ step,
543
+ toolCallId: value.toolCallId,
544
+ toolName: value.toolName,
545
+ args: void 0
546
+ };
547
+ message.toolInvocations.push(invocation);
548
+ updateToolInvocationPart(value.toolCallId, invocation);
549
+ execUpdate();
550
+ },
551
+ onToolCallDeltaPart(value) {
552
+ const partialToolCall = partialToolCalls[value.toolCallId];
553
+ partialToolCall.text += value.argsTextDelta;
554
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
555
+ const invocation = {
556
+ state: "partial-call",
557
+ step: partialToolCall.step,
558
+ toolCallId: value.toolCallId,
559
+ toolName: partialToolCall.toolName,
560
+ args: partialArgs
561
+ };
562
+ message.toolInvocations[partialToolCall.index] = invocation;
563
+ updateToolInvocationPart(value.toolCallId, invocation);
564
+ execUpdate();
565
+ },
566
+ async onToolCallPart(value) {
567
+ const invocation = {
568
+ state: "call",
569
+ step,
570
+ ...value
571
+ };
572
+ if (partialToolCalls[value.toolCallId] != null) {
573
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
574
+ } else {
575
+ if (message.toolInvocations == null) {
576
+ message.toolInvocations = [];
577
+ }
578
+ message.toolInvocations.push(invocation);
579
+ }
580
+ updateToolInvocationPart(value.toolCallId, invocation);
581
+ execUpdate();
582
+ if (onToolCall) {
583
+ const result = await onToolCall({ toolCall: value });
584
+ if (result != null) {
585
+ const invocation2 = {
586
+ state: "result",
587
+ step,
588
+ ...value,
589
+ result
590
+ };
591
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
592
+ updateToolInvocationPart(value.toolCallId, invocation2);
593
+ execUpdate();
594
+ }
595
+ }
596
+ },
597
+ onToolResultPart(value) {
598
+ const toolInvocations = message.toolInvocations;
599
+ if (toolInvocations == null) {
600
+ throw new Error("tool_result must be preceded by a tool_call");
601
+ }
602
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
603
+ if (toolInvocationIndex === -1) {
604
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
605
+ }
606
+ const invocation = {
607
+ ...toolInvocations[toolInvocationIndex],
608
+ state: "result",
609
+ ...value
610
+ };
611
+ toolInvocations[toolInvocationIndex] = invocation;
612
+ updateToolInvocationPart(value.toolCallId, invocation);
613
+ execUpdate();
614
+ },
615
+ onDataPart(value) {
616
+ data.push(...value);
617
+ execUpdate();
618
+ },
619
+ onMessageAnnotationsPart(value) {
620
+ if (messageAnnotations == null) {
621
+ messageAnnotations = [...value];
622
+ } else {
623
+ messageAnnotations.push(...value);
624
+ }
625
+ execUpdate();
626
+ },
627
+ onFinishStepPart(value) {
628
+ step += 1;
629
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
630
+ currentReasoningPart = void 0;
631
+ currentReasoningTextDetail = void 0;
632
+ },
633
+ onStartStepPart(value) {
634
+ if (!replaceLastMessage) {
635
+ message.id = value.messageId;
636
+ }
637
+ message.parts.push({ type: "step-start" });
638
+ execUpdate();
639
+ },
640
+ onFinishMessagePart(value) {
641
+ finishReason = value.finishReason;
642
+ if (value.usage != null) {
643
+ usage = value.usage;
644
+ }
645
+ },
646
+ onErrorPart(error) {
647
+ throw new Error(error);
648
+ }
351
649
  });
650
+ onFinish?.({ message, finishReason, usage });
352
651
  }
353
652
  /**
354
653
  * Streams a response from the agent
@@ -356,13 +655,294 @@ var Agent = class extends BaseResource {
356
655
  * @returns Promise containing the enhanced Response object with processDataStream method
357
656
  */
358
657
  async stream(params) {
658
+ console.warn(
659
+ "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th. Please use streamLegacy if you don't want to upgrade just yet."
660
+ );
661
+ return this.streamLegacy(params);
662
+ }
663
+ /**
664
+ * Streams a response from the agent
665
+ * @param params - Stream parameters including prompt
666
+ * @returns Promise containing the enhanced Response object with processDataStream method
667
+ */
668
+ async streamLegacy(params) {
359
669
  const processedParams = {
360
670
  ...params,
361
671
  output: params.output ? zodToJsonSchema(params.output) : void 0,
362
672
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
363
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
673
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
674
+ clientTools: processClientTools(params.clientTools)
675
+ };
676
+ const { readable, writable } = new TransformStream();
677
+ const response = await this.processStreamResponse(processedParams, writable);
678
+ const streamResponse = new Response(readable, {
679
+ status: response.status,
680
+ statusText: response.statusText,
681
+ headers: response.headers
682
+ });
683
+ streamResponse.processDataStream = async (options = {}) => {
684
+ await uiUtils.processDataStream({
685
+ stream: streamResponse.body,
686
+ ...options
687
+ });
688
+ };
689
+ return streamResponse;
690
+ }
691
+ async processChatResponse_vNext({
692
+ stream,
693
+ update,
694
+ onToolCall,
695
+ onFinish,
696
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
697
+ lastMessage
698
+ }) {
699
+ const replaceLastMessage = lastMessage?.role === "assistant";
700
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
701
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
702
+ return Math.max(max, toolInvocation.step ?? 0);
703
+ }, 0) ?? 0) : 0;
704
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
705
+ id: uuid.v4(),
706
+ createdAt: getCurrentDate(),
707
+ role: "assistant",
708
+ content: "",
709
+ parts: []
710
+ };
711
+ let currentTextPart = void 0;
712
+ let currentReasoningPart = void 0;
713
+ let currentReasoningTextDetail = void 0;
714
+ function updateToolInvocationPart(toolCallId, invocation) {
715
+ const part = message.parts.find(
716
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
717
+ );
718
+ if (part != null) {
719
+ part.toolInvocation = invocation;
720
+ } else {
721
+ message.parts.push({
722
+ type: "tool-invocation",
723
+ toolInvocation: invocation
724
+ });
725
+ }
726
+ }
727
+ const data = [];
728
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
729
+ const partialToolCalls = {};
730
+ let usage = {
731
+ completionTokens: NaN,
732
+ promptTokens: NaN,
733
+ totalTokens: NaN
364
734
  };
365
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
735
+ let finishReason = "unknown";
736
+ function execUpdate() {
737
+ const copiedData = [...data];
738
+ if (messageAnnotations?.length) {
739
+ message.annotations = messageAnnotations;
740
+ }
741
+ const copiedMessage = {
742
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
743
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
744
+ ...structuredClone(message),
745
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
746
+ // hashing approach by default to detect changes, but it only works for shallow
747
+ // changes. This is why we need to add a revision id to ensure that the message
748
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
749
+ // forwarded to rendering):
750
+ revisionId: uuid.v4()
751
+ };
752
+ update({
753
+ message: copiedMessage,
754
+ data: copiedData,
755
+ replaceLastMessage
756
+ });
757
+ }
758
+ await processMastraStream({
759
+ stream,
760
+ // TODO: casting as any here because the stream types were all typed as any before in core.
761
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
762
+ onChunk: async (chunk) => {
763
+ switch (chunk.type) {
764
+ case "step-start": {
765
+ if (!replaceLastMessage) {
766
+ message.id = chunk.payload.messageId;
767
+ }
768
+ message.parts.push({ type: "step-start" });
769
+ execUpdate();
770
+ break;
771
+ }
772
+ case "text-delta": {
773
+ if (currentTextPart == null) {
774
+ currentTextPart = {
775
+ type: "text",
776
+ text: chunk.payload.text
777
+ };
778
+ message.parts.push(currentTextPart);
779
+ } else {
780
+ currentTextPart.text += chunk.payload.text;
781
+ }
782
+ message.content += chunk.payload.text;
783
+ execUpdate();
784
+ break;
785
+ }
786
+ case "reasoning-delta": {
787
+ if (currentReasoningTextDetail == null) {
788
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
789
+ if (currentReasoningPart != null) {
790
+ currentReasoningPart.details.push(currentReasoningTextDetail);
791
+ }
792
+ } else {
793
+ currentReasoningTextDetail.text += chunk.payload.text;
794
+ }
795
+ if (currentReasoningPart == null) {
796
+ currentReasoningPart = {
797
+ type: "reasoning",
798
+ reasoning: chunk.payload.text,
799
+ details: [currentReasoningTextDetail]
800
+ };
801
+ message.parts.push(currentReasoningPart);
802
+ } else {
803
+ currentReasoningPart.reasoning += chunk.payload.text;
804
+ }
805
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
806
+ execUpdate();
807
+ break;
808
+ }
809
+ case "file": {
810
+ message.parts.push({
811
+ type: "file",
812
+ mimeType: chunk.payload.mimeType,
813
+ data: chunk.payload.data
814
+ });
815
+ execUpdate();
816
+ break;
817
+ }
818
+ case "source": {
819
+ message.parts.push({
820
+ type: "source",
821
+ source: chunk.payload.source
822
+ });
823
+ execUpdate();
824
+ break;
825
+ }
826
+ case "tool-call": {
827
+ const invocation = {
828
+ state: "call",
829
+ step,
830
+ ...chunk.payload
831
+ };
832
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
833
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
834
+ } else {
835
+ if (message.toolInvocations == null) {
836
+ message.toolInvocations = [];
837
+ }
838
+ message.toolInvocations.push(invocation);
839
+ }
840
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
841
+ execUpdate();
842
+ if (onToolCall) {
843
+ const result = await onToolCall({ toolCall: chunk.payload });
844
+ if (result != null) {
845
+ const invocation2 = {
846
+ state: "result",
847
+ step,
848
+ ...chunk.payload,
849
+ result
850
+ };
851
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
852
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
853
+ execUpdate();
854
+ }
855
+ }
856
+ }
857
+ case "tool-call-input-streaming-start": {
858
+ if (message.toolInvocations == null) {
859
+ message.toolInvocations = [];
860
+ }
861
+ partialToolCalls[chunk.payload.toolCallId] = {
862
+ text: "",
863
+ step,
864
+ toolName: chunk.payload.toolName,
865
+ index: message.toolInvocations.length
866
+ };
867
+ const invocation = {
868
+ state: "partial-call",
869
+ step,
870
+ toolCallId: chunk.payload.toolCallId,
871
+ toolName: chunk.payload.toolName,
872
+ args: void 0
873
+ };
874
+ message.toolInvocations.push(invocation);
875
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
876
+ execUpdate();
877
+ break;
878
+ }
879
+ case "tool-call-delta": {
880
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
881
+ partialToolCall.text += chunk.payload.argsTextDelta;
882
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
883
+ const invocation = {
884
+ state: "partial-call",
885
+ step: partialToolCall.step,
886
+ toolCallId: chunk.payload.toolCallId,
887
+ toolName: partialToolCall.toolName,
888
+ args: partialArgs
889
+ };
890
+ message.toolInvocations[partialToolCall.index] = invocation;
891
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
892
+ execUpdate();
893
+ break;
894
+ }
895
+ case "tool-result": {
896
+ const toolInvocations = message.toolInvocations;
897
+ if (toolInvocations == null) {
898
+ throw new Error("tool_result must be preceded by a tool_call");
899
+ }
900
+ const toolInvocationIndex = toolInvocations.findIndex(
901
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
902
+ );
903
+ if (toolInvocationIndex === -1) {
904
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
905
+ }
906
+ const invocation = {
907
+ ...toolInvocations[toolInvocationIndex],
908
+ state: "result",
909
+ ...chunk.payload
910
+ };
911
+ toolInvocations[toolInvocationIndex] = invocation;
912
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
913
+ execUpdate();
914
+ break;
915
+ }
916
+ case "error": {
917
+ throw new Error(chunk.payload.error);
918
+ }
919
+ case "data": {
920
+ data.push(...chunk.payload.data);
921
+ execUpdate();
922
+ break;
923
+ }
924
+ case "step-finish": {
925
+ step += 1;
926
+ currentTextPart = chunk.payload.isContinued ? currentTextPart : void 0;
927
+ currentReasoningPart = void 0;
928
+ currentReasoningTextDetail = void 0;
929
+ execUpdate();
930
+ break;
931
+ }
932
+ case "finish": {
933
+ finishReason = chunk.payload.finishReason;
934
+ if (chunk.payload.usage != null) {
935
+ usage = chunk.payload.usage;
936
+ }
937
+ break;
938
+ }
939
+ }
940
+ }
941
+ });
942
+ onFinish?.({ message, finishReason, usage });
943
+ }
944
+ async processStreamResponse_vNext(processedParams, writable) {
945
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
366
946
  method: "POST",
367
947
  body: processedParams,
368
948
  stream: true
@@ -370,15 +950,247 @@ var Agent = class extends BaseResource {
370
950
  if (!response.body) {
371
951
  throw new Error("No response body");
372
952
  }
373
- response.processDataStream = async (options = {}) => {
374
- await uiUtils.processDataStream({
375
- stream: response.body,
376
- ...options
953
+ try {
954
+ let toolCalls = [];
955
+ let messages = [];
956
+ const [streamForWritable, streamForProcessing] = response.body.tee();
957
+ streamForWritable.pipeTo(writable, {
958
+ preventClose: true
959
+ }).catch((error) => {
960
+ console.error("Error piping to writable stream:", error);
377
961
  });
378
- };
962
+ this.processChatResponse_vNext({
963
+ stream: streamForProcessing,
964
+ update: ({ message }) => {
965
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
966
+ if (existingIndex !== -1) {
967
+ messages[existingIndex] = message;
968
+ } else {
969
+ messages.push(message);
970
+ }
971
+ },
972
+ onFinish: async ({ finishReason, message }) => {
973
+ if (finishReason === "tool-calls") {
974
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
975
+ if (toolCall) {
976
+ toolCalls.push(toolCall);
977
+ }
978
+ for (const toolCall2 of toolCalls) {
979
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
980
+ if (clientTool && clientTool.execute) {
981
+ const result = await clientTool.execute(
982
+ {
983
+ context: toolCall2?.args,
984
+ runId: processedParams.runId,
985
+ resourceId: processedParams.resourceId,
986
+ threadId: processedParams.threadId,
987
+ runtimeContext: processedParams.runtimeContext,
988
+ // TODO: Pass proper tracing context when client-js supports tracing
989
+ tracingContext: { currentSpan: void 0 }
990
+ },
991
+ {
992
+ messages: response.messages,
993
+ toolCallId: toolCall2?.toolCallId
994
+ }
995
+ );
996
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
997
+ const toolInvocationPart = lastMessage?.parts?.find(
998
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
999
+ );
1000
+ if (toolInvocationPart) {
1001
+ toolInvocationPart.toolInvocation = {
1002
+ ...toolInvocationPart.toolInvocation,
1003
+ state: "result",
1004
+ result
1005
+ };
1006
+ }
1007
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1008
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1009
+ );
1010
+ if (toolInvocation) {
1011
+ toolInvocation.state = "result";
1012
+ toolInvocation.result = result;
1013
+ }
1014
+ const writer = writable.getWriter();
1015
+ try {
1016
+ await writer.write(
1017
+ new TextEncoder().encode(
1018
+ "a:" + JSON.stringify({
1019
+ toolCallId: toolCall2.toolCallId,
1020
+ result
1021
+ }) + "\n"
1022
+ )
1023
+ );
1024
+ } finally {
1025
+ writer.releaseLock();
1026
+ }
1027
+ const originalMessages = processedParams.messages;
1028
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1029
+ this.processStreamResponse_vNext(
1030
+ {
1031
+ ...processedParams,
1032
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1033
+ },
1034
+ writable
1035
+ ).catch((error) => {
1036
+ console.error("Error processing stream response:", error);
1037
+ });
1038
+ }
1039
+ }
1040
+ } else {
1041
+ setTimeout(() => {
1042
+ writable.close();
1043
+ }, 0);
1044
+ }
1045
+ },
1046
+ lastMessage: void 0
1047
+ }).catch((error) => {
1048
+ console.error("Error processing stream response:", error);
1049
+ });
1050
+ } catch (error) {
1051
+ console.error("Error processing stream response:", error);
1052
+ }
379
1053
  return response;
380
1054
  }
381
- /**
1055
+ async streamVNext(params) {
1056
+ const processedParams = {
1057
+ ...params,
1058
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1059
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1060
+ clientTools: processClientTools(params.clientTools)
1061
+ };
1062
+ const { readable, writable } = new TransformStream();
1063
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1064
+ const streamResponse = new Response(readable, {
1065
+ status: response.status,
1066
+ statusText: response.statusText,
1067
+ headers: response.headers
1068
+ });
1069
+ streamResponse.processDataStream = async ({
1070
+ onChunk
1071
+ }) => {
1072
+ await processMastraStream({
1073
+ stream: streamResponse.body,
1074
+ onChunk
1075
+ });
1076
+ };
1077
+ return streamResponse;
1078
+ }
1079
+ /**
1080
+ * Processes the stream response and handles tool calls
1081
+ */
1082
+ async processStreamResponse(processedParams, writable) {
1083
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1084
+ method: "POST",
1085
+ body: processedParams,
1086
+ stream: true
1087
+ });
1088
+ if (!response.body) {
1089
+ throw new Error("No response body");
1090
+ }
1091
+ try {
1092
+ let toolCalls = [];
1093
+ let messages = [];
1094
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1095
+ streamForWritable.pipeTo(writable, {
1096
+ preventClose: true
1097
+ }).catch((error) => {
1098
+ console.error("Error piping to writable stream:", error);
1099
+ });
1100
+ this.processChatResponse({
1101
+ stream: streamForProcessing,
1102
+ update: ({ message }) => {
1103
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1104
+ if (existingIndex !== -1) {
1105
+ messages[existingIndex] = message;
1106
+ } else {
1107
+ messages.push(message);
1108
+ }
1109
+ },
1110
+ onFinish: async ({ finishReason, message }) => {
1111
+ if (finishReason === "tool-calls") {
1112
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1113
+ if (toolCall) {
1114
+ toolCalls.push(toolCall);
1115
+ }
1116
+ for (const toolCall2 of toolCalls) {
1117
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1118
+ if (clientTool && clientTool.execute) {
1119
+ const result = await clientTool.execute(
1120
+ {
1121
+ context: toolCall2?.args,
1122
+ runId: processedParams.runId,
1123
+ resourceId: processedParams.resourceId,
1124
+ threadId: processedParams.threadId,
1125
+ runtimeContext: processedParams.runtimeContext,
1126
+ // TODO: Pass proper tracing context when client-js supports tracing
1127
+ tracingContext: { currentSpan: void 0 }
1128
+ },
1129
+ {
1130
+ messages: response.messages,
1131
+ toolCallId: toolCall2?.toolCallId
1132
+ }
1133
+ );
1134
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1135
+ const toolInvocationPart = lastMessage?.parts?.find(
1136
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1137
+ );
1138
+ if (toolInvocationPart) {
1139
+ toolInvocationPart.toolInvocation = {
1140
+ ...toolInvocationPart.toolInvocation,
1141
+ state: "result",
1142
+ result
1143
+ };
1144
+ }
1145
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1146
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1147
+ );
1148
+ if (toolInvocation) {
1149
+ toolInvocation.state = "result";
1150
+ toolInvocation.result = result;
1151
+ }
1152
+ const writer = writable.getWriter();
1153
+ try {
1154
+ await writer.write(
1155
+ new TextEncoder().encode(
1156
+ "a:" + JSON.stringify({
1157
+ toolCallId: toolCall2.toolCallId,
1158
+ result
1159
+ }) + "\n"
1160
+ )
1161
+ );
1162
+ } finally {
1163
+ writer.releaseLock();
1164
+ }
1165
+ const originalMessages = processedParams.messages;
1166
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1167
+ this.processStreamResponse(
1168
+ {
1169
+ ...processedParams,
1170
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1171
+ },
1172
+ writable
1173
+ ).catch((error) => {
1174
+ console.error("Error processing stream response:", error);
1175
+ });
1176
+ }
1177
+ }
1178
+ } else {
1179
+ setTimeout(() => {
1180
+ writable.close();
1181
+ }, 0);
1182
+ }
1183
+ },
1184
+ lastMessage: void 0
1185
+ }).catch((error) => {
1186
+ console.error("Error processing stream response:", error);
1187
+ });
1188
+ } catch (error) {
1189
+ console.error("Error processing stream response:", error);
1190
+ }
1191
+ return response;
1192
+ }
1193
+ /**
382
1194
  * Gets details about a specific tool available to the agent
383
1195
  * @param toolId - ID of the tool to retrieve
384
1196
  * @returns Promise containing tool details
@@ -416,6 +1228,17 @@ var Agent = class extends BaseResource {
416
1228
  liveEvals() {
417
1229
  return this.request(`/api/agents/${this.agentId}/evals/live`);
418
1230
  }
1231
+ /**
1232
+ * Updates the model for the agent
1233
+ * @param params - Parameters for updating the model
1234
+ * @returns Promise containing the updated model
1235
+ */
1236
+ updateModel(params) {
1237
+ return this.request(`/api/agents/${this.agentId}/model`, {
1238
+ method: "POST",
1239
+ body: params
1240
+ });
1241
+ }
419
1242
  };
420
1243
  var Network = class extends BaseResource {
421
1244
  constructor(options, networkId) {
@@ -520,6 +1343,36 @@ var MemoryThread = class extends BaseResource {
520
1343
  });
521
1344
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
522
1345
  }
1346
+ /**
1347
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1348
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1349
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1350
+ */
1351
+ getMessagesPaginated({
1352
+ selectBy,
1353
+ ...rest
1354
+ }) {
1355
+ const query = new URLSearchParams({
1356
+ ...rest,
1357
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1358
+ });
1359
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1360
+ }
1361
+ /**
1362
+ * Deletes one or more messages from the thread
1363
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1364
+ * message object with id property, or array of message objects
1365
+ * @returns Promise containing deletion result
1366
+ */
1367
+ deleteMessages(messageIds) {
1368
+ const query = new URLSearchParams({
1369
+ agentId: this.agentId
1370
+ });
1371
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1372
+ method: "POST",
1373
+ body: { messageIds }
1374
+ });
1375
+ }
523
1376
  };
524
1377
 
525
1378
  // src/resources/vector.ts
@@ -875,10 +1728,10 @@ var Workflow = class extends BaseResource {
875
1728
  if (params?.toDate) {
876
1729
  searchParams.set("toDate", params.toDate.toISOString());
877
1730
  }
878
- if (params?.limit) {
1731
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
879
1732
  searchParams.set("limit", String(params.limit));
880
1733
  }
881
- if (params?.offset) {
1734
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
882
1735
  searchParams.set("offset", String(params.offset));
883
1736
  }
884
1737
  if (params?.resourceId) {
@@ -890,6 +1743,43 @@ var Workflow = class extends BaseResource {
890
1743
  return this.request(`/api/workflows/${this.workflowId}/runs`);
891
1744
  }
892
1745
  }
1746
+ /**
1747
+ * Retrieves a specific workflow run by its ID
1748
+ * @param runId - The ID of the workflow run to retrieve
1749
+ * @returns Promise containing the workflow run details
1750
+ */
1751
+ runById(runId) {
1752
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1753
+ }
1754
+ /**
1755
+ * Retrieves the execution result for a specific workflow run by its ID
1756
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1757
+ * @returns Promise containing the workflow run execution result
1758
+ */
1759
+ runExecutionResult(runId) {
1760
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1761
+ }
1762
+ /**
1763
+ * Cancels a specific workflow run by its ID
1764
+ * @param runId - The ID of the workflow run to cancel
1765
+ * @returns Promise containing a success message
1766
+ */
1767
+ cancelRun(runId) {
1768
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1769
+ method: "POST"
1770
+ });
1771
+ }
1772
+ /**
1773
+ * Sends an event to a specific workflow run by its ID
1774
+ * @param params - Object containing the runId, event and data
1775
+ * @returns Promise containing a success message
1776
+ */
1777
+ sendRunEvent(params) {
1778
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1779
+ method: "POST",
1780
+ body: { event: params.event, data: params.data }
1781
+ });
1782
+ }
893
1783
  /**
894
1784
  * Creates a new workflow run
895
1785
  * @param params - Optional object containing the optional runId
@@ -904,6 +1794,14 @@ var Workflow = class extends BaseResource {
904
1794
  method: "POST"
905
1795
  });
906
1796
  }
1797
+ /**
1798
+ * Creates a new workflow run (alias for createRun)
1799
+ * @param params - Optional object containing the optional runId
1800
+ * @returns Promise containing the runId of the created run
1801
+ */
1802
+ createRunAsync(params) {
1803
+ return this.createRun(params);
1804
+ }
907
1805
  /**
908
1806
  * Starts a workflow run synchronously without waiting for the workflow to complete
909
1807
  * @param params - Object containing the runId, inputData and runtimeContext
@@ -955,16 +1853,16 @@ var Workflow = class extends BaseResource {
955
1853
  });
956
1854
  }
957
1855
  /**
958
- * Starts a vNext workflow run and returns a stream
1856
+ * Starts a workflow run and returns a stream
959
1857
  * @param params - Object containing the optional runId, inputData and runtimeContext
960
- * @returns Promise containing the vNext workflow execution results
1858
+ * @returns Promise containing the workflow execution results
961
1859
  */
962
1860
  async stream(params) {
963
1861
  const searchParams = new URLSearchParams();
964
1862
  if (!!params?.runId) {
965
1863
  searchParams.set("runId", params.runId);
966
1864
  }
967
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
1865
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
968
1866
  const response = await this.request(
969
1867
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
970
1868
  {
@@ -979,6 +1877,7 @@ var Workflow = class extends BaseResource {
979
1877
  if (!response.body) {
980
1878
  throw new Error("Response body is null");
981
1879
  }
1880
+ let failedChunk = void 0;
982
1881
  const transformStream = new TransformStream({
983
1882
  start() {
984
1883
  },
@@ -988,10 +1887,13 @@ var Workflow = class extends BaseResource {
988
1887
  const chunks = decoded.split(RECORD_SEPARATOR2);
989
1888
  for (const chunk2 of chunks) {
990
1889
  if (chunk2) {
1890
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
991
1891
  try {
992
- const parsedChunk = JSON.parse(chunk2);
1892
+ const parsedChunk = JSON.parse(newChunk);
993
1893
  controller.enqueue(parsedChunk);
1894
+ failedChunk = void 0;
994
1895
  } catch {
1896
+ failedChunk = newChunk;
995
1897
  }
996
1898
  }
997
1899
  }
@@ -1076,22 +1978,38 @@ var A2A = class extends BaseResource {
1076
1978
  * @returns Promise containing the agent card information
1077
1979
  */
1078
1980
  async getCard() {
1079
- return this.request(`/.well-known/${this.agentId}/agent.json`);
1981
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1080
1982
  }
1081
1983
  /**
1082
- * Send a message to the agent and get a response
1984
+ * Send a message to the agent and gets a message or task response
1083
1985
  * @param params - Parameters for the task
1084
- * @returns Promise containing the task response
1986
+ * @returns Promise containing the response
1085
1987
  */
1086
1988
  async sendMessage(params) {
1087
1989
  const response = await this.request(`/a2a/${this.agentId}`, {
1088
1990
  method: "POST",
1089
1991
  body: {
1090
- method: "tasks/send",
1992
+ method: "message/send",
1091
1993
  params
1092
1994
  }
1093
1995
  });
1094
- return { task: response.result };
1996
+ return response;
1997
+ }
1998
+ /**
1999
+ * Sends a message to an agent to initiate/continue a task and subscribes
2000
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2001
+ * @param params - Parameters for the task
2002
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2003
+ */
2004
+ async sendStreamingMessage(params) {
2005
+ const response = await this.request(`/a2a/${this.agentId}`, {
2006
+ method: "POST",
2007
+ body: {
2008
+ method: "message/stream",
2009
+ params
2010
+ }
2011
+ });
2012
+ return response;
1095
2013
  }
1096
2014
  /**
1097
2015
  * Get the status and result of a task
@@ -1102,81 +2020,684 @@ var A2A = class extends BaseResource {
1102
2020
  const response = await this.request(`/a2a/${this.agentId}`, {
1103
2021
  method: "POST",
1104
2022
  body: {
1105
- method: "tasks/get",
1106
- params
2023
+ method: "tasks/get",
2024
+ params
2025
+ }
2026
+ });
2027
+ return response;
2028
+ }
2029
+ /**
2030
+ * Cancel a running task
2031
+ * @param params - Parameters identifying the task to cancel
2032
+ * @returns Promise containing the task response
2033
+ */
2034
+ async cancelTask(params) {
2035
+ return this.request(`/a2a/${this.agentId}`, {
2036
+ method: "POST",
2037
+ body: {
2038
+ method: "tasks/cancel",
2039
+ params
2040
+ }
2041
+ });
2042
+ }
2043
+ };
2044
+
2045
+ // src/resources/mcp-tool.ts
2046
+ var MCPTool = class extends BaseResource {
2047
+ serverId;
2048
+ toolId;
2049
+ constructor(options, serverId, toolId) {
2050
+ super(options);
2051
+ this.serverId = serverId;
2052
+ this.toolId = toolId;
2053
+ }
2054
+ /**
2055
+ * Retrieves details about this specific tool from the MCP server.
2056
+ * @returns Promise containing the tool's information (name, description, schema).
2057
+ */
2058
+ details() {
2059
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2060
+ }
2061
+ /**
2062
+ * Executes this specific tool on the MCP server.
2063
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2064
+ * @returns Promise containing the result of the tool execution.
2065
+ */
2066
+ execute(params) {
2067
+ const body = {};
2068
+ if (params.data !== void 0) body.data = params.data;
2069
+ if (params.runtimeContext !== void 0) {
2070
+ body.runtimeContext = params.runtimeContext;
2071
+ }
2072
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2073
+ method: "POST",
2074
+ body: Object.keys(body).length > 0 ? body : void 0
2075
+ });
2076
+ }
2077
+ };
2078
+
2079
+ // src/resources/agent-builder.ts
2080
+ var RECORD_SEPARATOR3 = "";
2081
+ var AgentBuilder = class extends BaseResource {
2082
+ constructor(options, actionId) {
2083
+ super(options);
2084
+ this.actionId = actionId;
2085
+ }
2086
+ // Helper function to transform workflow result to action result
2087
+ transformWorkflowResult(result) {
2088
+ if (result.status === "success") {
2089
+ return {
2090
+ success: result.result.success || false,
2091
+ applied: result.result.applied || false,
2092
+ branchName: result.result.branchName,
2093
+ message: result.result.message || "Agent builder action completed",
2094
+ validationResults: result.result.validationResults,
2095
+ error: result.result.error,
2096
+ errors: result.result.errors,
2097
+ stepResults: result.result.stepResults
2098
+ };
2099
+ } else if (result.status === "failed") {
2100
+ return {
2101
+ success: false,
2102
+ applied: false,
2103
+ message: `Agent builder action failed: ${result.error.message}`,
2104
+ error: result.error.message
2105
+ };
2106
+ } else {
2107
+ return {
2108
+ success: false,
2109
+ applied: false,
2110
+ message: "Agent builder action was suspended",
2111
+ error: "Workflow suspended - manual intervention required"
2112
+ };
2113
+ }
2114
+ }
2115
+ /**
2116
+ * Creates a new agent builder action run and returns the runId.
2117
+ * This calls `/api/agent-builder/:actionId/create-run`.
2118
+ */
2119
+ async createRun(params) {
2120
+ const searchParams = new URLSearchParams();
2121
+ if (!!params?.runId) {
2122
+ searchParams.set("runId", params.runId);
2123
+ }
2124
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2125
+ return this.request(url, {
2126
+ method: "POST"
2127
+ });
2128
+ }
2129
+ /**
2130
+ * Creates a new workflow run (alias for createRun)
2131
+ * @param params - Optional object containing the optional runId
2132
+ * @returns Promise containing the runId of the created run
2133
+ */
2134
+ createRunAsync(params) {
2135
+ return this.createRun(params);
2136
+ }
2137
+ /**
2138
+ * Starts agent builder action asynchronously and waits for completion.
2139
+ * This calls `/api/agent-builder/:actionId/start-async`.
2140
+ */
2141
+ async startAsync(params, runId) {
2142
+ const searchParams = new URLSearchParams();
2143
+ if (runId) {
2144
+ searchParams.set("runId", runId);
2145
+ }
2146
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2147
+ const { runtimeContext: _, ...actionParams } = params;
2148
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2149
+ const result = await this.request(url, {
2150
+ method: "POST",
2151
+ body: { ...actionParams, runtimeContext }
2152
+ });
2153
+ return this.transformWorkflowResult(result);
2154
+ }
2155
+ /**
2156
+ * Starts an existing agent builder action run.
2157
+ * This calls `/api/agent-builder/:actionId/start`.
2158
+ */
2159
+ async startActionRun(params, runId) {
2160
+ const searchParams = new URLSearchParams();
2161
+ searchParams.set("runId", runId);
2162
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2163
+ const { runtimeContext: _, ...actionParams } = params;
2164
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2165
+ return this.request(url, {
2166
+ method: "POST",
2167
+ body: { ...actionParams, runtimeContext }
2168
+ });
2169
+ }
2170
+ /**
2171
+ * Resumes a suspended agent builder action step.
2172
+ * This calls `/api/agent-builder/:actionId/resume`.
2173
+ */
2174
+ async resume(params, runId) {
2175
+ const searchParams = new URLSearchParams();
2176
+ searchParams.set("runId", runId);
2177
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2178
+ const { runtimeContext: _, ...resumeParams } = params;
2179
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2180
+ return this.request(url, {
2181
+ method: "POST",
2182
+ body: { ...resumeParams, runtimeContext }
2183
+ });
2184
+ }
2185
+ /**
2186
+ * Resumes a suspended agent builder action step asynchronously.
2187
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2188
+ */
2189
+ async resumeAsync(params, runId) {
2190
+ const searchParams = new URLSearchParams();
2191
+ searchParams.set("runId", runId);
2192
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2193
+ const { runtimeContext: _, ...resumeParams } = params;
2194
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2195
+ const result = await this.request(url, {
2196
+ method: "POST",
2197
+ body: { ...resumeParams, runtimeContext }
2198
+ });
2199
+ return this.transformWorkflowResult(result);
2200
+ }
2201
+ /**
2202
+ * Creates an async generator that processes a readable stream and yields action records
2203
+ * separated by the Record Separator character (\x1E)
2204
+ *
2205
+ * @param stream - The readable stream to process
2206
+ * @returns An async generator that yields parsed records
2207
+ */
2208
+ async *streamProcessor(stream) {
2209
+ const reader = stream.getReader();
2210
+ let doneReading = false;
2211
+ let buffer = "";
2212
+ try {
2213
+ while (!doneReading) {
2214
+ const { done, value } = await reader.read();
2215
+ doneReading = done;
2216
+ if (done && !value) continue;
2217
+ try {
2218
+ const decoded = value ? new TextDecoder().decode(value) : "";
2219
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2220
+ buffer = chunks.pop() || "";
2221
+ for (const chunk of chunks) {
2222
+ if (chunk) {
2223
+ if (typeof chunk === "string") {
2224
+ try {
2225
+ const parsedChunk = JSON.parse(chunk);
2226
+ yield parsedChunk;
2227
+ } catch {
2228
+ }
2229
+ }
2230
+ }
2231
+ }
2232
+ } catch {
2233
+ }
2234
+ }
2235
+ if (buffer) {
2236
+ try {
2237
+ yield JSON.parse(buffer);
2238
+ } catch {
2239
+ }
2240
+ }
2241
+ } finally {
2242
+ reader.cancel().catch(() => {
2243
+ });
2244
+ }
2245
+ }
2246
+ /**
2247
+ * Streams agent builder action progress in real-time.
2248
+ * This calls `/api/agent-builder/:actionId/stream`.
2249
+ */
2250
+ async stream(params, runId) {
2251
+ const searchParams = new URLSearchParams();
2252
+ if (runId) {
2253
+ searchParams.set("runId", runId);
2254
+ }
2255
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2256
+ const { runtimeContext: _, ...actionParams } = params;
2257
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2258
+ const response = await this.request(url, {
2259
+ method: "POST",
2260
+ body: { ...actionParams, runtimeContext },
2261
+ stream: true
2262
+ });
2263
+ if (!response.ok) {
2264
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2265
+ }
2266
+ if (!response.body) {
2267
+ throw new Error("Response body is null");
2268
+ }
2269
+ let failedChunk = void 0;
2270
+ const transformStream = new TransformStream({
2271
+ start() {
2272
+ },
2273
+ async transform(chunk, controller) {
2274
+ try {
2275
+ const decoded = new TextDecoder().decode(chunk);
2276
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2277
+ for (const chunk2 of chunks) {
2278
+ if (chunk2) {
2279
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2280
+ try {
2281
+ const parsedChunk = JSON.parse(newChunk);
2282
+ controller.enqueue(parsedChunk);
2283
+ failedChunk = void 0;
2284
+ } catch {
2285
+ failedChunk = newChunk;
2286
+ }
2287
+ }
2288
+ }
2289
+ } catch {
2290
+ }
2291
+ }
2292
+ });
2293
+ return response.body.pipeThrough(transformStream);
2294
+ }
2295
+ /**
2296
+ * Streams agent builder action progress in real-time using VNext streaming.
2297
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2298
+ */
2299
+ async streamVNext(params, runId) {
2300
+ const searchParams = new URLSearchParams();
2301
+ if (runId) {
2302
+ searchParams.set("runId", runId);
2303
+ }
2304
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2305
+ const { runtimeContext: _, ...actionParams } = params;
2306
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2307
+ const response = await this.request(url, {
2308
+ method: "POST",
2309
+ body: { ...actionParams, runtimeContext },
2310
+ stream: true
2311
+ });
2312
+ if (!response.ok) {
2313
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2314
+ }
2315
+ if (!response.body) {
2316
+ throw new Error("Response body is null");
2317
+ }
2318
+ let failedChunk = void 0;
2319
+ const transformStream = new TransformStream({
2320
+ start() {
2321
+ },
2322
+ async transform(chunk, controller) {
2323
+ try {
2324
+ const decoded = new TextDecoder().decode(chunk);
2325
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2326
+ for (const chunk2 of chunks) {
2327
+ if (chunk2) {
2328
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2329
+ try {
2330
+ const parsedChunk = JSON.parse(newChunk);
2331
+ controller.enqueue(parsedChunk);
2332
+ failedChunk = void 0;
2333
+ } catch {
2334
+ failedChunk = newChunk;
2335
+ }
2336
+ }
2337
+ }
2338
+ } catch {
2339
+ }
2340
+ }
2341
+ });
2342
+ return response.body.pipeThrough(transformStream);
2343
+ }
2344
+ /**
2345
+ * Watches an existing agent builder action run by runId.
2346
+ * This is used for hot reload recovery - it loads the existing run state
2347
+ * and streams any remaining progress.
2348
+ * This calls `/api/agent-builder/:actionId/watch`.
2349
+ */
2350
+ async watch({ runId, eventType }, onRecord) {
2351
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2352
+ const response = await this.request(url, {
2353
+ method: "GET",
2354
+ stream: true
2355
+ });
2356
+ if (!response.ok) {
2357
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2358
+ }
2359
+ if (!response.body) {
2360
+ throw new Error("Response body is null");
2361
+ }
2362
+ for await (const record of this.streamProcessor(response.body)) {
2363
+ if (typeof record === "string") {
2364
+ onRecord(JSON.parse(record));
2365
+ } else {
2366
+ onRecord(record);
2367
+ }
2368
+ }
2369
+ }
2370
+ /**
2371
+ * Gets a specific action run by its ID.
2372
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2373
+ */
2374
+ async runById(runId) {
2375
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2376
+ return this.request(url, {
2377
+ method: "GET"
2378
+ });
2379
+ }
2380
+ /**
2381
+ * Gets details about this agent builder action.
2382
+ * This calls `/api/agent-builder/:actionId`.
2383
+ */
2384
+ async details() {
2385
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2386
+ return result;
2387
+ }
2388
+ /**
2389
+ * Gets all runs for this agent builder action.
2390
+ * This calls `/api/agent-builder/:actionId/runs`.
2391
+ */
2392
+ async runs(params) {
2393
+ const searchParams = new URLSearchParams();
2394
+ if (params?.fromDate) {
2395
+ searchParams.set("fromDate", params.fromDate.toISOString());
2396
+ }
2397
+ if (params?.toDate) {
2398
+ searchParams.set("toDate", params.toDate.toISOString());
2399
+ }
2400
+ if (params?.limit !== void 0) {
2401
+ searchParams.set("limit", String(params.limit));
2402
+ }
2403
+ if (params?.offset !== void 0) {
2404
+ searchParams.set("offset", String(params.offset));
2405
+ }
2406
+ if (params?.resourceId) {
2407
+ searchParams.set("resourceId", params.resourceId);
2408
+ }
2409
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2410
+ return this.request(url, {
2411
+ method: "GET"
2412
+ });
2413
+ }
2414
+ /**
2415
+ * Gets the execution result of an agent builder action run.
2416
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2417
+ */
2418
+ async runExecutionResult(runId) {
2419
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2420
+ return this.request(url, {
2421
+ method: "GET"
2422
+ });
2423
+ }
2424
+ /**
2425
+ * Cancels an agent builder action run.
2426
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2427
+ */
2428
+ async cancelRun(runId) {
2429
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2430
+ return this.request(url, {
2431
+ method: "POST"
2432
+ });
2433
+ }
2434
+ /**
2435
+ * Sends an event to an agent builder action run.
2436
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2437
+ */
2438
+ async sendRunEvent(params) {
2439
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2440
+ return this.request(url, {
2441
+ method: "POST",
2442
+ body: { event: params.event, data: params.data }
2443
+ });
2444
+ }
2445
+ };
2446
+
2447
+ // src/resources/observability.ts
2448
+ var Observability = class extends BaseResource {
2449
+ constructor(options) {
2450
+ super(options);
2451
+ }
2452
+ /**
2453
+ * Retrieves a specific AI trace by ID
2454
+ * @param traceId - ID of the trace to retrieve
2455
+ * @returns Promise containing the AI trace with all its spans
2456
+ */
2457
+ getTrace(traceId) {
2458
+ return this.request(`/api/observability/traces/${traceId}`);
2459
+ }
2460
+ /**
2461
+ * Retrieves paginated list of AI traces with optional filtering
2462
+ * @param params - Parameters for pagination and filtering
2463
+ * @returns Promise containing paginated traces and pagination info
2464
+ */
2465
+ getTraces(params) {
2466
+ const { pagination, filters } = params;
2467
+ const { page, perPage, dateRange } = pagination || {};
2468
+ const { name, spanType } = filters || {};
2469
+ const searchParams = new URLSearchParams();
2470
+ if (page !== void 0) {
2471
+ searchParams.set("page", String(page));
2472
+ }
2473
+ if (perPage !== void 0) {
2474
+ searchParams.set("perPage", String(perPage));
2475
+ }
2476
+ if (name) {
2477
+ searchParams.set("name", name);
2478
+ }
2479
+ if (spanType !== void 0) {
2480
+ searchParams.set("spanType", String(spanType));
2481
+ }
2482
+ if (dateRange) {
2483
+ const dateRangeStr = JSON.stringify({
2484
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2485
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2486
+ });
2487
+ searchParams.set("dateRange", dateRangeStr);
2488
+ }
2489
+ const queryString = searchParams.toString();
2490
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2491
+ }
2492
+ };
2493
+
2494
+ // src/resources/network-memory-thread.ts
2495
+ var NetworkMemoryThread = class extends BaseResource {
2496
+ constructor(options, threadId, networkId) {
2497
+ super(options);
2498
+ this.threadId = threadId;
2499
+ this.networkId = networkId;
2500
+ }
2501
+ /**
2502
+ * Retrieves the memory thread details
2503
+ * @returns Promise containing thread details including title and metadata
2504
+ */
2505
+ get() {
2506
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
2507
+ }
2508
+ /**
2509
+ * Updates the memory thread properties
2510
+ * @param params - Update parameters including title and metadata
2511
+ * @returns Promise containing updated thread details
2512
+ */
2513
+ update(params) {
2514
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2515
+ method: "PATCH",
2516
+ body: params
2517
+ });
2518
+ }
2519
+ /**
2520
+ * Deletes the memory thread
2521
+ * @returns Promise containing deletion result
2522
+ */
2523
+ delete() {
2524
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2525
+ method: "DELETE"
2526
+ });
2527
+ }
2528
+ /**
2529
+ * Retrieves messages associated with the thread
2530
+ * @param params - Optional parameters including limit for number of messages to retrieve
2531
+ * @returns Promise containing thread messages and UI messages
2532
+ */
2533
+ getMessages(params) {
2534
+ const query = new URLSearchParams({
2535
+ networkId: this.networkId,
2536
+ ...params?.limit ? { limit: params.limit.toString() } : {}
2537
+ });
2538
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
2539
+ }
2540
+ /**
2541
+ * Deletes one or more messages from the thread
2542
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2543
+ * message object with id property, or array of message objects
2544
+ * @returns Promise containing deletion result
2545
+ */
2546
+ deleteMessages(messageIds) {
2547
+ const query = new URLSearchParams({
2548
+ networkId: this.networkId
2549
+ });
2550
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
2551
+ method: "POST",
2552
+ body: { messageIds }
2553
+ });
2554
+ }
2555
+ };
2556
+
2557
+ // src/resources/vNextNetwork.ts
2558
+ var RECORD_SEPARATOR4 = "";
2559
+ var VNextNetwork = class extends BaseResource {
2560
+ constructor(options, networkId) {
2561
+ super(options);
2562
+ this.networkId = networkId;
2563
+ }
2564
+ /**
2565
+ * Retrieves details about the network
2566
+ * @returns Promise containing vNext network details
2567
+ */
2568
+ details() {
2569
+ return this.request(`/api/networks/v-next/${this.networkId}`);
2570
+ }
2571
+ /**
2572
+ * Generates a response from the v-next network
2573
+ * @param params - Generation parameters including message
2574
+ * @returns Promise containing the generated response
2575
+ */
2576
+ generate(params) {
2577
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
2578
+ method: "POST",
2579
+ body: {
2580
+ ...params,
2581
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1107
2582
  }
1108
2583
  });
1109
- return response.result;
1110
2584
  }
1111
2585
  /**
1112
- * Cancel a running task
1113
- * @param params - Parameters identifying the task to cancel
1114
- * @returns Promise containing the task response
2586
+ * Generates a response from the v-next network using multiple primitives
2587
+ * @param params - Generation parameters including message
2588
+ * @returns Promise containing the generated response
1115
2589
  */
1116
- async cancelTask(params) {
1117
- return this.request(`/a2a/${this.agentId}`, {
2590
+ loop(params) {
2591
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1118
2592
  method: "POST",
1119
2593
  body: {
1120
- method: "tasks/cancel",
1121
- params
2594
+ ...params,
2595
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1122
2596
  }
1123
2597
  });
1124
2598
  }
2599
+ async *streamProcessor(stream) {
2600
+ const reader = stream.getReader();
2601
+ let doneReading = false;
2602
+ let buffer = "";
2603
+ try {
2604
+ while (!doneReading) {
2605
+ const { done, value } = await reader.read();
2606
+ doneReading = done;
2607
+ if (done && !value) continue;
2608
+ try {
2609
+ const decoded = value ? new TextDecoder().decode(value) : "";
2610
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
2611
+ buffer = chunks.pop() || "";
2612
+ for (const chunk of chunks) {
2613
+ if (chunk) {
2614
+ if (typeof chunk === "string") {
2615
+ try {
2616
+ const parsedChunk = JSON.parse(chunk);
2617
+ yield parsedChunk;
2618
+ } catch {
2619
+ }
2620
+ }
2621
+ }
2622
+ }
2623
+ } catch {
2624
+ }
2625
+ }
2626
+ if (buffer) {
2627
+ try {
2628
+ yield JSON.parse(buffer);
2629
+ } catch {
2630
+ }
2631
+ }
2632
+ } finally {
2633
+ reader.cancel().catch(() => {
2634
+ });
2635
+ }
2636
+ }
1125
2637
  /**
1126
- * Send a message and subscribe to streaming updates (not fully implemented)
1127
- * @param params - Parameters for the task
1128
- * @returns Promise containing the task response
2638
+ * Streams a response from the v-next network
2639
+ * @param params - Stream parameters including message
2640
+ * @returns Promise containing the results
1129
2641
  */
1130
- async sendAndSubscribe(params) {
1131
- return this.request(`/a2a/${this.agentId}`, {
2642
+ async stream(params, onRecord) {
2643
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1132
2644
  method: "POST",
1133
2645
  body: {
1134
- method: "tasks/sendSubscribe",
1135
- params
2646
+ ...params,
2647
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1136
2648
  },
1137
2649
  stream: true
1138
2650
  });
1139
- }
1140
- };
1141
-
1142
- // src/resources/mcp-tool.ts
1143
- var MCPTool = class extends BaseResource {
1144
- serverId;
1145
- toolId;
1146
- constructor(options, serverId, toolId) {
1147
- super(options);
1148
- this.serverId = serverId;
1149
- this.toolId = toolId;
1150
- }
1151
- /**
1152
- * Retrieves details about this specific tool from the MCP server.
1153
- * @returns Promise containing the tool's information (name, description, schema).
1154
- */
1155
- details() {
1156
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2651
+ if (!response.ok) {
2652
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2653
+ }
2654
+ if (!response.body) {
2655
+ throw new Error("Response body is null");
2656
+ }
2657
+ for await (const record of this.streamProcessor(response.body)) {
2658
+ if (typeof record === "string") {
2659
+ onRecord(JSON.parse(record));
2660
+ } else {
2661
+ onRecord(record);
2662
+ }
2663
+ }
1157
2664
  }
1158
2665
  /**
1159
- * Executes this specific tool on the MCP server.
1160
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1161
- * @returns Promise containing the result of the tool execution.
2666
+ * Streams a response from the v-next network loop
2667
+ * @param params - Stream parameters including message
2668
+ * @returns Promise containing the results
1162
2669
  */
1163
- execute(params) {
1164
- const body = {};
1165
- if (params.data !== void 0) body.data = params.data;
1166
- if (params.runtimeContext !== void 0) {
1167
- body.runtimeContext = params.runtimeContext;
1168
- }
1169
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2670
+ async loopStream(params, onRecord) {
2671
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1170
2672
  method: "POST",
1171
- body: Object.keys(body).length > 0 ? body : void 0
2673
+ body: {
2674
+ ...params,
2675
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2676
+ },
2677
+ stream: true
1172
2678
  });
2679
+ if (!response.ok) {
2680
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2681
+ }
2682
+ if (!response.body) {
2683
+ throw new Error("Response body is null");
2684
+ }
2685
+ for await (const record of this.streamProcessor(response.body)) {
2686
+ if (typeof record === "string") {
2687
+ onRecord(JSON.parse(record));
2688
+ } else {
2689
+ onRecord(record);
2690
+ }
2691
+ }
1173
2692
  }
1174
2693
  };
1175
2694
 
1176
2695
  // src/client.ts
1177
2696
  var MastraClient = class extends BaseResource {
2697
+ observability;
1178
2698
  constructor(options) {
1179
2699
  super(options);
2700
+ this.observability = new Observability(options);
1180
2701
  }
1181
2702
  /**
1182
2703
  * Retrieves all available agents
@@ -1185,21 +2706,6 @@ var MastraClient = class extends BaseResource {
1185
2706
  getAgents() {
1186
2707
  return this.request("/api/agents");
1187
2708
  }
1188
- async getAGUI({ resourceId }) {
1189
- const agents = await this.getAgents();
1190
- return Object.entries(agents).reduce(
1191
- (acc, [agentId]) => {
1192
- const agent = this.getAgent(agentId);
1193
- acc[agentId] = new AGUIAdapter({
1194
- agentId,
1195
- agent,
1196
- resourceId
1197
- });
1198
- return acc;
1199
- },
1200
- {}
1201
- );
1202
- }
1203
2709
  /**
1204
2710
  * Gets an agent instance by ID
1205
2711
  * @param agentId - ID of the agent to retrieve
@@ -1250,6 +2756,48 @@ var MastraClient = class extends BaseResource {
1250
2756
  getMemoryStatus(agentId) {
1251
2757
  return this.request(`/api/memory/status?agentId=${agentId}`);
1252
2758
  }
2759
+ /**
2760
+ * Retrieves memory threads for a resource
2761
+ * @param params - Parameters containing the resource ID
2762
+ * @returns Promise containing array of memory threads
2763
+ */
2764
+ getNetworkMemoryThreads(params) {
2765
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
2766
+ }
2767
+ /**
2768
+ * Creates a new memory thread
2769
+ * @param params - Parameters for creating the memory thread
2770
+ * @returns Promise containing the created memory thread
2771
+ */
2772
+ createNetworkMemoryThread(params) {
2773
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
2774
+ }
2775
+ /**
2776
+ * Gets a memory thread instance by ID
2777
+ * @param threadId - ID of the memory thread to retrieve
2778
+ * @returns MemoryThread instance
2779
+ */
2780
+ getNetworkMemoryThread(threadId, networkId) {
2781
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2782
+ }
2783
+ /**
2784
+ * Saves messages to memory
2785
+ * @param params - Parameters containing messages to save
2786
+ * @returns Promise containing the saved messages
2787
+ */
2788
+ saveNetworkMessageToMemory(params) {
2789
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2790
+ method: "POST",
2791
+ body: params
2792
+ });
2793
+ }
2794
+ /**
2795
+ * Gets the status of the memory system
2796
+ * @returns Promise containing memory system status
2797
+ */
2798
+ getNetworkMemoryStatus(networkId) {
2799
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2800
+ }
1253
2801
  /**
1254
2802
  * Retrieves all available tools
1255
2803
  * @returns Promise containing map of tool IDs to tool details
@@ -1295,6 +2843,20 @@ var MastraClient = class extends BaseResource {
1295
2843
  getWorkflow(workflowId) {
1296
2844
  return new Workflow(this.options, workflowId);
1297
2845
  }
2846
+ /**
2847
+ * Gets all available agent builder actions
2848
+ * @returns Promise containing map of action IDs to action details
2849
+ */
2850
+ getAgentBuilderActions() {
2851
+ return this.request("/api/agent-builder/");
2852
+ }
2853
+ /**
2854
+ * Gets an agent builder instance for executing agent-builder workflows
2855
+ * @returns AgentBuilder instance
2856
+ */
2857
+ getAgentBuilderAction(actionId) {
2858
+ return new AgentBuilder(this.options, actionId);
2859
+ }
1298
2860
  /**
1299
2861
  * Gets a vector instance by name
1300
2862
  * @param vectorName - Name of the vector to retrieve
@@ -1309,7 +2871,41 @@ var MastraClient = class extends BaseResource {
1309
2871
  * @returns Promise containing array of log messages
1310
2872
  */
1311
2873
  getLogs(params) {
1312
- return this.request(`/api/logs?transportId=${params.transportId}`);
2874
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2875
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2876
+ const searchParams = new URLSearchParams();
2877
+ if (transportId) {
2878
+ searchParams.set("transportId", transportId);
2879
+ }
2880
+ if (fromDate) {
2881
+ searchParams.set("fromDate", fromDate.toISOString());
2882
+ }
2883
+ if (toDate) {
2884
+ searchParams.set("toDate", toDate.toISOString());
2885
+ }
2886
+ if (logLevel) {
2887
+ searchParams.set("logLevel", logLevel);
2888
+ }
2889
+ if (page) {
2890
+ searchParams.set("page", String(page));
2891
+ }
2892
+ if (perPage) {
2893
+ searchParams.set("perPage", String(perPage));
2894
+ }
2895
+ if (_filters) {
2896
+ if (Array.isArray(_filters)) {
2897
+ for (const filter of _filters) {
2898
+ searchParams.append("filters", filter);
2899
+ }
2900
+ } else {
2901
+ searchParams.set("filters", _filters);
2902
+ }
2903
+ }
2904
+ if (searchParams.size) {
2905
+ return this.request(`/api/logs?${searchParams}`);
2906
+ } else {
2907
+ return this.request(`/api/logs`);
2908
+ }
1313
2909
  }
1314
2910
  /**
1315
2911
  * Gets logs for a specific run
@@ -1317,7 +2913,44 @@ var MastraClient = class extends BaseResource {
1317
2913
  * @returns Promise containing array of log messages
1318
2914
  */
1319
2915
  getLogForRun(params) {
1320
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2916
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2917
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2918
+ const searchParams = new URLSearchParams();
2919
+ if (runId) {
2920
+ searchParams.set("runId", runId);
2921
+ }
2922
+ if (transportId) {
2923
+ searchParams.set("transportId", transportId);
2924
+ }
2925
+ if (fromDate) {
2926
+ searchParams.set("fromDate", fromDate.toISOString());
2927
+ }
2928
+ if (toDate) {
2929
+ searchParams.set("toDate", toDate.toISOString());
2930
+ }
2931
+ if (logLevel) {
2932
+ searchParams.set("logLevel", logLevel);
2933
+ }
2934
+ if (page) {
2935
+ searchParams.set("page", String(page));
2936
+ }
2937
+ if (perPage) {
2938
+ searchParams.set("perPage", String(perPage));
2939
+ }
2940
+ if (_filters) {
2941
+ if (Array.isArray(_filters)) {
2942
+ for (const filter of _filters) {
2943
+ searchParams.append("filters", filter);
2944
+ }
2945
+ } else {
2946
+ searchParams.set("filters", _filters);
2947
+ }
2948
+ }
2949
+ if (searchParams.size) {
2950
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2951
+ } else {
2952
+ return this.request(`/api/logs/${runId}`);
2953
+ }
1321
2954
  }
1322
2955
  /**
1323
2956
  * List of all log transports
@@ -1375,6 +3008,13 @@ var MastraClient = class extends BaseResource {
1375
3008
  getNetworks() {
1376
3009
  return this.request("/api/networks");
1377
3010
  }
3011
+ /**
3012
+ * Retrieves all available vNext networks
3013
+ * @returns Promise containing map of vNext network IDs to vNext network details
3014
+ */
3015
+ getVNextNetworks() {
3016
+ return this.request("/api/networks/v-next");
3017
+ }
1378
3018
  /**
1379
3019
  * Gets a network instance by ID
1380
3020
  * @param networkId - ID of the network to retrieve
@@ -1383,6 +3023,14 @@ var MastraClient = class extends BaseResource {
1383
3023
  getNetwork(networkId) {
1384
3024
  return new Network(this.options, networkId);
1385
3025
  }
3026
+ /**
3027
+ * Gets a vNext network instance by ID
3028
+ * @param networkId - ID of the vNext network to retrieve
3029
+ * @returns vNext Network instance
3030
+ */
3031
+ getVNextNetwork(networkId) {
3032
+ return new VNextNetwork(this.options, networkId);
3033
+ }
1386
3034
  /**
1387
3035
  * Retrieves a list of available MCP servers.
1388
3036
  * @param params - Optional parameters for pagination (limit, offset).
@@ -1439,6 +3087,134 @@ var MastraClient = class extends BaseResource {
1439
3087
  getA2A(agentId) {
1440
3088
  return new A2A(this.options, agentId);
1441
3089
  }
3090
+ /**
3091
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3092
+ * @param agentId - ID of the agent.
3093
+ * @param threadId - ID of the thread.
3094
+ * @param resourceId - Optional ID of the resource.
3095
+ * @returns Working memory for the specified thread or resource.
3096
+ */
3097
+ getWorkingMemory({
3098
+ agentId,
3099
+ threadId,
3100
+ resourceId
3101
+ }) {
3102
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3103
+ }
3104
+ /**
3105
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3106
+ * @param agentId - ID of the agent.
3107
+ * @param threadId - ID of the thread.
3108
+ * @param workingMemory - The new working memory content.
3109
+ * @param resourceId - Optional ID of the resource.
3110
+ */
3111
+ updateWorkingMemory({
3112
+ agentId,
3113
+ threadId,
3114
+ workingMemory,
3115
+ resourceId
3116
+ }) {
3117
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
3118
+ method: "POST",
3119
+ body: {
3120
+ workingMemory,
3121
+ resourceId
3122
+ }
3123
+ });
3124
+ }
3125
+ /**
3126
+ * Retrieves all available scorers
3127
+ * @returns Promise containing list of available scorers
3128
+ */
3129
+ getScorers() {
3130
+ return this.request("/api/scores/scorers");
3131
+ }
3132
+ /**
3133
+ * Retrieves a scorer by ID
3134
+ * @param scorerId - ID of the scorer to retrieve
3135
+ * @returns Promise containing the scorer
3136
+ */
3137
+ getScorer(scorerId) {
3138
+ return this.request(`/api/scores/scorers/${scorerId}`);
3139
+ }
3140
+ getScoresByScorerId(params) {
3141
+ const { page, perPage, scorerId, entityId, entityType } = params;
3142
+ const searchParams = new URLSearchParams();
3143
+ if (entityId) {
3144
+ searchParams.set("entityId", entityId);
3145
+ }
3146
+ if (entityType) {
3147
+ searchParams.set("entityType", entityType);
3148
+ }
3149
+ if (page !== void 0) {
3150
+ searchParams.set("page", String(page));
3151
+ }
3152
+ if (perPage !== void 0) {
3153
+ searchParams.set("perPage", String(perPage));
3154
+ }
3155
+ const queryString = searchParams.toString();
3156
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3157
+ }
3158
+ /**
3159
+ * Retrieves scores by run ID
3160
+ * @param params - Parameters containing run ID and pagination options
3161
+ * @returns Promise containing scores and pagination info
3162
+ */
3163
+ getScoresByRunId(params) {
3164
+ const { runId, page, perPage } = params;
3165
+ const searchParams = new URLSearchParams();
3166
+ if (page !== void 0) {
3167
+ searchParams.set("page", String(page));
3168
+ }
3169
+ if (perPage !== void 0) {
3170
+ searchParams.set("perPage", String(perPage));
3171
+ }
3172
+ const queryString = searchParams.toString();
3173
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3174
+ }
3175
+ /**
3176
+ * Retrieves scores by entity ID and type
3177
+ * @param params - Parameters containing entity ID, type, and pagination options
3178
+ * @returns Promise containing scores and pagination info
3179
+ */
3180
+ getScoresByEntityId(params) {
3181
+ const { entityId, entityType, page, perPage } = params;
3182
+ const searchParams = new URLSearchParams();
3183
+ if (page !== void 0) {
3184
+ searchParams.set("page", String(page));
3185
+ }
3186
+ if (perPage !== void 0) {
3187
+ searchParams.set("perPage", String(perPage));
3188
+ }
3189
+ const queryString = searchParams.toString();
3190
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3191
+ }
3192
+ /**
3193
+ * Saves a score
3194
+ * @param params - Parameters containing the score data to save
3195
+ * @returns Promise containing the saved score
3196
+ */
3197
+ saveScore(params) {
3198
+ return this.request("/api/scores", {
3199
+ method: "POST",
3200
+ body: params
3201
+ });
3202
+ }
3203
+ /**
3204
+ * Retrieves model providers with available keys
3205
+ * @returns Promise containing model providers with available keys
3206
+ */
3207
+ getModelProviders() {
3208
+ return this.request(`/api/model-providers`);
3209
+ }
3210
+ getAITrace(traceId) {
3211
+ return this.observability.getTrace(traceId);
3212
+ }
3213
+ getAITraces(params) {
3214
+ return this.observability.getTraces(params);
3215
+ }
1442
3216
  };
1443
3217
 
1444
3218
  exports.MastraClient = MastraClient;
3219
+ //# sourceMappingURL=index.cjs.map
3220
+ //# sourceMappingURL=index.cjs.map