@mastra/client-js 0.0.0-consolidate-changesets-20250904042643 → 0.0.0-cor235-20251008190353

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 (43) hide show
  1. package/CHANGELOG.md +511 -35
  2. package/README.md +6 -10
  3. package/dist/client.d.ts +37 -43
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/index.cjs +670 -797
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +669 -798
  10. package/dist/index.js.map +1 -1
  11. package/dist/resources/agent-builder.d.ts +14 -2
  12. package/dist/resources/agent-builder.d.ts.map +1 -1
  13. package/dist/resources/agent.d.ts +66 -37
  14. package/dist/resources/agent.d.ts.map +1 -1
  15. package/dist/resources/index.d.ts +0 -2
  16. package/dist/resources/index.d.ts.map +1 -1
  17. package/dist/resources/mcp-tool.d.ts +2 -1
  18. package/dist/resources/mcp-tool.d.ts.map +1 -1
  19. package/dist/resources/observability.d.ts +17 -1
  20. package/dist/resources/observability.d.ts.map +1 -1
  21. package/dist/resources/tool.d.ts +2 -1
  22. package/dist/resources/tool.d.ts.map +1 -1
  23. package/dist/resources/vector.d.ts +5 -2
  24. package/dist/resources/vector.d.ts.map +1 -1
  25. package/dist/resources/workflow.d.ts +128 -13
  26. package/dist/resources/workflow.d.ts.map +1 -1
  27. package/dist/tools.d.ts +22 -0
  28. package/dist/tools.d.ts.map +1 -0
  29. package/dist/types.d.ts +66 -64
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/utils/index.d.ts +2 -0
  32. package/dist/utils/index.d.ts.map +1 -1
  33. package/dist/utils/process-mastra-stream.d.ts +5 -1
  34. package/dist/utils/process-mastra-stream.d.ts.map +1 -1
  35. package/package.json +8 -11
  36. package/dist/adapters/agui.d.ts +0 -23
  37. package/dist/adapters/agui.d.ts.map +0 -1
  38. package/dist/resources/legacy-workflow.d.ts +0 -87
  39. package/dist/resources/legacy-workflow.d.ts.map +0 -1
  40. package/dist/resources/network.d.ts +0 -30
  41. package/dist/resources/network.d.ts.map +0 -1
  42. package/dist/resources/vNextNetwork.d.ts +0 -42
  43. package/dist/resources/vNextNetwork.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var client = require('@ag-ui/client');
4
- var rxjs = require('rxjs');
5
3
  var uiUtils = require('@ai-sdk/ui-utils');
6
4
  var uuid = require('@lukeed/uuid');
7
5
  var runtimeContext = require('@mastra/core/runtime-context');
@@ -13,205 +11,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
11
 
14
12
  var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
15
13
 
16
- // src/adapters/agui.ts
17
- var AGUIAdapter = class extends client.AbstractAgent {
18
- agent;
19
- resourceId;
20
- constructor({ agent, agentId, resourceId, ...rest }) {
21
- super({
22
- agentId,
23
- ...rest
24
- });
25
- this.agent = agent;
26
- this.resourceId = resourceId;
27
- }
28
- run(input) {
29
- return new rxjs.Observable((subscriber) => {
30
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
31
- subscriber.next({
32
- type: client.EventType.RUN_STARTED,
33
- threadId: input.threadId,
34
- runId: input.runId
35
- });
36
- this.agent.stream({
37
- threadId: input.threadId,
38
- resourceId: this.resourceId ?? "",
39
- runId: input.runId,
40
- messages: convertedMessages,
41
- clientTools: input.tools.reduce(
42
- (acc, tool) => {
43
- acc[tool.name] = {
44
- id: tool.name,
45
- description: tool.description,
46
- inputSchema: tool.parameters
47
- };
48
- return acc;
49
- },
50
- {}
51
- )
52
- }).then((response) => {
53
- let currentMessageId = void 0;
54
- let isInTextMessage = false;
55
- return response.processDataStream({
56
- onTextPart: (text) => {
57
- if (currentMessageId === void 0) {
58
- currentMessageId = generateUUID();
59
- const message2 = {
60
- type: client.EventType.TEXT_MESSAGE_START,
61
- messageId: currentMessageId,
62
- role: "assistant"
63
- };
64
- subscriber.next(message2);
65
- isInTextMessage = true;
66
- }
67
- const message = {
68
- type: client.EventType.TEXT_MESSAGE_CONTENT,
69
- messageId: currentMessageId,
70
- delta: text
71
- };
72
- subscriber.next(message);
73
- },
74
- onFinishMessagePart: () => {
75
- if (currentMessageId !== void 0) {
76
- const message = {
77
- type: client.EventType.TEXT_MESSAGE_END,
78
- messageId: currentMessageId
79
- };
80
- subscriber.next(message);
81
- isInTextMessage = false;
82
- }
83
- subscriber.next({
84
- type: client.EventType.RUN_FINISHED,
85
- threadId: input.threadId,
86
- runId: input.runId
87
- });
88
- subscriber.complete();
89
- },
90
- onToolCallPart(streamPart) {
91
- const parentMessageId = currentMessageId || generateUUID();
92
- if (isInTextMessage) {
93
- const message = {
94
- type: client.EventType.TEXT_MESSAGE_END,
95
- messageId: parentMessageId
96
- };
97
- subscriber.next(message);
98
- isInTextMessage = false;
99
- }
100
- subscriber.next({
101
- type: client.EventType.TOOL_CALL_START,
102
- toolCallId: streamPart.toolCallId,
103
- toolCallName: streamPart.toolName,
104
- parentMessageId
105
- });
106
- subscriber.next({
107
- type: client.EventType.TOOL_CALL_ARGS,
108
- toolCallId: streamPart.toolCallId,
109
- delta: JSON.stringify(streamPart.args),
110
- parentMessageId
111
- });
112
- subscriber.next({
113
- type: client.EventType.TOOL_CALL_END,
114
- toolCallId: streamPart.toolCallId,
115
- parentMessageId
116
- });
117
- }
118
- });
119
- }).catch((error) => {
120
- console.error("error", error);
121
- subscriber.error(error);
122
- });
123
- return () => {
124
- };
125
- });
126
- }
127
- };
128
- function generateUUID() {
129
- if (typeof crypto !== "undefined") {
130
- if (typeof crypto.randomUUID === "function") {
131
- return crypto.randomUUID();
132
- }
133
- if (typeof crypto.getRandomValues === "function") {
134
- const buffer = new Uint8Array(16);
135
- crypto.getRandomValues(buffer);
136
- buffer[6] = buffer[6] & 15 | 64;
137
- buffer[8] = buffer[8] & 63 | 128;
138
- let hex = "";
139
- for (let i = 0; i < 16; i++) {
140
- hex += buffer[i].toString(16).padStart(2, "0");
141
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
142
- }
143
- return hex;
144
- }
145
- }
146
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
147
- const r = Math.random() * 16 | 0;
148
- const v = c === "x" ? r : r & 3 | 8;
149
- return v.toString(16);
150
- });
151
- }
152
- function convertMessagesToMastraMessages(messages) {
153
- const result = [];
154
- const toolCallsWithResults = /* @__PURE__ */ new Set();
155
- for (const message of messages) {
156
- if (message.role === "tool" && message.toolCallId) {
157
- toolCallsWithResults.add(message.toolCallId);
158
- }
159
- }
160
- for (const message of messages) {
161
- if (message.role === "assistant") {
162
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
163
- for (const toolCall of message.toolCalls ?? []) {
164
- parts.push({
165
- type: "tool-call",
166
- toolCallId: toolCall.id,
167
- toolName: toolCall.function.name,
168
- args: JSON.parse(toolCall.function.arguments)
169
- });
170
- }
171
- result.push({
172
- role: "assistant",
173
- content: parts
174
- });
175
- if (message.toolCalls?.length) {
176
- for (const toolCall of message.toolCalls) {
177
- if (!toolCallsWithResults.has(toolCall.id)) {
178
- result.push({
179
- role: "tool",
180
- content: [
181
- {
182
- type: "tool-result",
183
- toolCallId: toolCall.id,
184
- toolName: toolCall.function.name,
185
- result: JSON.parse(toolCall.function.arguments)
186
- // This is still wrong but matches test expectations
187
- }
188
- ]
189
- });
190
- }
191
- }
192
- }
193
- } else if (message.role === "user") {
194
- result.push({
195
- role: "user",
196
- content: message.content || ""
197
- });
198
- } else if (message.role === "tool") {
199
- result.push({
200
- role: "tool",
201
- content: [
202
- {
203
- type: "tool-result",
204
- toolCallId: message.toolCallId || "unknown",
205
- toolName: "unknown",
206
- // toolName is not available in tool messages from CopilotKit
207
- result: message.content
208
- }
209
- ]
210
- });
211
- }
212
- }
213
- return result;
214
- }
14
+ // src/resources/agent.ts
215
15
  function parseClientRuntimeContext(runtimeContext$1) {
216
16
  if (runtimeContext$1) {
217
17
  if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
@@ -221,6 +21,20 @@ function parseClientRuntimeContext(runtimeContext$1) {
221
21
  }
222
22
  return void 0;
223
23
  }
24
+ function base64RuntimeContext(runtimeContext) {
25
+ if (runtimeContext) {
26
+ return btoa(JSON.stringify(runtimeContext));
27
+ }
28
+ return void 0;
29
+ }
30
+ function runtimeContextQueryString(runtimeContext) {
31
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
32
+ if (!runtimeContextParam) return "";
33
+ const searchParams = new URLSearchParams();
34
+ searchParams.set("runtimeContext", runtimeContextParam);
35
+ const queryString = searchParams.toString();
36
+ return queryString ? `?${queryString}` : "";
37
+ }
224
38
  function isZodType(value) {
225
39
  return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
226
40
  }
@@ -232,7 +46,7 @@ function zodToJsonSchema(zodSchema) {
232
46
  const fn = "toJSONSchema";
233
47
  return zod.z[fn].call(zod.z, zodSchema);
234
48
  }
235
- return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
49
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "relative" });
236
50
  }
237
51
 
238
52
  // src/utils/process-client-tools.ts
@@ -265,7 +79,7 @@ function processClientTools(clientTools) {
265
79
  }
266
80
 
267
81
  // src/utils/process-mastra-stream.ts
268
- async function processMastraStream({
82
+ async function sharedProcessMastraStream({
269
83
  stream,
270
84
  onChunk
271
85
  }) {
@@ -283,7 +97,7 @@ async function processMastraStream({
283
97
  if (line.startsWith("data: ")) {
284
98
  const data = line.slice(6);
285
99
  if (data === "[DONE]") {
286
- console.log("\u{1F3C1} Stream finished");
100
+ console.info("\u{1F3C1} Stream finished");
287
101
  return;
288
102
  }
289
103
  try {
@@ -299,6 +113,24 @@ async function processMastraStream({
299
113
  reader.releaseLock();
300
114
  }
301
115
  }
116
+ async function processMastraNetworkStream({
117
+ stream,
118
+ onChunk
119
+ }) {
120
+ return sharedProcessMastraStream({
121
+ stream,
122
+ onChunk
123
+ });
124
+ }
125
+ async function processMastraStream({
126
+ stream,
127
+ onChunk
128
+ }) {
129
+ return sharedProcessMastraStream({
130
+ stream,
131
+ onChunk
132
+ });
133
+ }
302
134
 
303
135
  // src/resources/base.ts
304
136
  var BaseResource = class {
@@ -387,7 +219,9 @@ async function executeToolCallAndRespond({
387
219
  resourceId,
388
220
  threadId,
389
221
  runtimeContext,
390
- tracingContext: { currentSpan: void 0 }
222
+ tracingContext: { currentSpan: void 0 },
223
+ suspend: async () => {
224
+ }
391
225
  },
392
226
  {
393
227
  messages: response.messages,
@@ -395,11 +229,7 @@ async function executeToolCallAndRespond({
395
229
  }
396
230
  );
397
231
  const updatedMessages = [
398
- {
399
- role: "user",
400
- content: params.messages
401
- },
402
- ...response.response.messages,
232
+ ...response.response.messages || [],
403
233
  {
404
234
  role: "tool",
405
235
  content: [
@@ -461,17 +291,21 @@ var AgentVoice = class extends BaseResource {
461
291
  }
462
292
  /**
463
293
  * Get available speakers for the agent's voice provider
294
+ * @param runtimeContext - Optional runtime context to pass as query parameter
295
+ * @param runtimeContext - Optional runtime context to pass as query parameter
464
296
  * @returns Promise containing list of available speakers
465
297
  */
466
- getSpeakers() {
467
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
298
+ getSpeakers(runtimeContext) {
299
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
468
300
  }
469
301
  /**
470
302
  * Get the listener configuration for the agent's voice provider
303
+ * @param runtimeContext - Optional runtime context to pass as query parameter
304
+ * @param runtimeContext - Optional runtime context to pass as query parameter
471
305
  * @returns Promise containing a check if the agent has listening capabilities
472
306
  */
473
- getListener() {
474
- return this.request(`/api/agents/${this.agentId}/voice/listener`);
307
+ getListener(runtimeContext) {
308
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
475
309
  }
476
310
  };
477
311
  var Agent = class extends BaseResource {
@@ -483,16 +317,11 @@ var Agent = class extends BaseResource {
483
317
  voice;
484
318
  /**
485
319
  * Retrieves details about the agent
320
+ * @param runtimeContext - Optional runtime context to pass as query parameter
486
321
  * @returns Promise containing agent details including model and instructions
487
322
  */
488
- details() {
489
- return this.request(`/api/agents/${this.agentId}`);
490
- }
491
- async generate(params) {
492
- console.warn(
493
- "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th. Please use generateLegacy if you don't want to upgrade just yet."
494
- );
495
- return this.generateLegacy(params);
323
+ details(runtimeContext) {
324
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
496
325
  }
497
326
  async generateLegacy(params) {
498
327
  const processedParams = {
@@ -525,7 +354,9 @@ var Agent = class extends BaseResource {
525
354
  resourceId,
526
355
  threadId,
527
356
  runtimeContext,
528
- tracingContext: { currentSpan: void 0 }
357
+ tracingContext: { currentSpan: void 0 },
358
+ suspend: async () => {
359
+ }
529
360
  },
530
361
  {
531
362
  messages: response.messages,
@@ -533,10 +364,6 @@ var Agent = class extends BaseResource {
533
364
  }
534
365
  );
535
366
  const updatedMessages = [
536
- {
537
- role: "user",
538
- content: params.messages
539
- },
540
367
  ...response.response.messages,
541
368
  {
542
369
  role: "tool",
@@ -559,16 +386,29 @@ var Agent = class extends BaseResource {
559
386
  }
560
387
  return response;
561
388
  }
562
- async generateVNext(params) {
389
+ async generate(messagesOrParams, options) {
390
+ let params;
391
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
392
+ params = messagesOrParams;
393
+ } else {
394
+ params = {
395
+ messages: messagesOrParams,
396
+ ...options
397
+ };
398
+ }
563
399
  const processedParams = {
564
400
  ...params,
565
401
  output: params.output ? zodToJsonSchema(params.output) : void 0,
566
402
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
567
- clientTools: processClientTools(params.clientTools)
403
+ clientTools: processClientTools(params.clientTools),
404
+ structuredOutput: params.structuredOutput ? {
405
+ ...params.structuredOutput,
406
+ schema: zodToJsonSchema(params.structuredOutput.schema)
407
+ } : void 0
568
408
  };
569
409
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
570
410
  const response = await this.request(
571
- `/api/agents/${this.agentId}/generate/vnext`,
411
+ `/api/agents/${this.agentId}/generate`,
572
412
  {
573
413
  method: "POST",
574
414
  body: processedParams
@@ -582,7 +422,7 @@ var Agent = class extends BaseResource {
582
422
  resourceId,
583
423
  threadId,
584
424
  runtimeContext,
585
- respondFn: this.generateVNext.bind(this)
425
+ respondFn: this.generate.bind(this)
586
426
  });
587
427
  }
588
428
  return response;
@@ -849,17 +689,6 @@ var Agent = class extends BaseResource {
849
689
  });
850
690
  onFinish?.({ message, finishReason, usage });
851
691
  }
852
- /**
853
- * Streams a response from the agent
854
- * @param params - Stream parameters including prompt
855
- * @returns Promise containing the enhanced Response object with processDataStream method
856
- */
857
- async stream(params) {
858
- console.warn(
859
- "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th. Please use streamLegacy if you don't want to upgrade just yet."
860
- );
861
- return this.streamLegacy(params);
862
- }
863
692
  /**
864
693
  * Streams a response from the agent
865
694
  * @param params - Stream parameters including prompt
@@ -961,6 +790,14 @@ var Agent = class extends BaseResource {
961
790
  // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
962
791
  onChunk: async (chunk) => {
963
792
  switch (chunk.type) {
793
+ case "tripwire": {
794
+ message.parts.push({
795
+ type: "text",
796
+ text: chunk.payload.tripwireReason
797
+ });
798
+ execUpdate();
799
+ break;
800
+ }
964
801
  case "step-start": {
965
802
  if (!replaceLastMessage) {
966
803
  message.id = chunk.payload.messageId;
@@ -1069,7 +906,7 @@ var Agent = class extends BaseResource {
1069
906
  step,
1070
907
  toolCallId: chunk.payload.toolCallId,
1071
908
  toolName: chunk.payload.toolName,
1072
- args: void 0
909
+ args: chunk.payload.args
1073
910
  };
1074
911
  message.toolInvocations.push(invocation);
1075
912
  updateToolInvocationPart(chunk.payload.toolCallId, invocation);
@@ -1123,14 +960,14 @@ var Agent = class extends BaseResource {
1123
960
  }
1124
961
  case "step-finish": {
1125
962
  step += 1;
1126
- currentTextPart = chunk.payload.isContinued ? currentTextPart : void 0;
963
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
1127
964
  currentReasoningPart = void 0;
1128
965
  currentReasoningTextDetail = void 0;
1129
966
  execUpdate();
1130
967
  break;
1131
968
  }
1132
969
  case "finish": {
1133
- finishReason = chunk.payload.finishReason;
970
+ finishReason = chunk.payload.stepResult.reason;
1134
971
  if (chunk.payload.usage != null) {
1135
972
  usage = chunk.payload.usage;
1136
973
  }
@@ -1142,7 +979,7 @@ var Agent = class extends BaseResource {
1142
979
  onFinish?.({ message, finishReason, usage });
1143
980
  }
1144
981
  async processStreamResponse_vNext(processedParams, writable) {
1145
- const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
982
+ const response = await this.request(`/api/agents/${this.agentId}/stream`, {
1146
983
  method: "POST",
1147
984
  body: processedParams,
1148
985
  stream: true
@@ -1154,9 +991,27 @@ var Agent = class extends BaseResource {
1154
991
  let toolCalls = [];
1155
992
  let messages = [];
1156
993
  const [streamForWritable, streamForProcessing] = response.body.tee();
1157
- streamForWritable.pipeTo(writable, {
1158
- preventClose: true
1159
- }).catch((error) => {
994
+ streamForWritable.pipeTo(
995
+ new WritableStream({
996
+ async write(chunk) {
997
+ let writer;
998
+ try {
999
+ writer = writable.getWriter();
1000
+ const text = new TextDecoder().decode(chunk);
1001
+ const lines = text.split("\n\n");
1002
+ const readableLines = lines.filter((line) => line !== "[DONE]").join("\n\n");
1003
+ await writer.write(new TextEncoder().encode(readableLines));
1004
+ } catch {
1005
+ await writer?.write(chunk);
1006
+ } finally {
1007
+ writer?.releaseLock();
1008
+ }
1009
+ }
1010
+ }),
1011
+ {
1012
+ preventClose: true
1013
+ }
1014
+ ).catch((error) => {
1160
1015
  console.error("Error piping to writable stream:", error);
1161
1016
  });
1162
1017
  this.processChatResponse_vNext({
@@ -1175,9 +1030,11 @@ var Agent = class extends BaseResource {
1175
1030
  if (toolCall) {
1176
1031
  toolCalls.push(toolCall);
1177
1032
  }
1033
+ let shouldExecuteClientTool = false;
1178
1034
  for (const toolCall2 of toolCalls) {
1179
1035
  const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1180
1036
  if (clientTool && clientTool.execute) {
1037
+ shouldExecuteClientTool = true;
1181
1038
  const result = await clientTool.execute(
1182
1039
  {
1183
1040
  context: toolCall2?.args,
@@ -1186,14 +1043,17 @@ var Agent = class extends BaseResource {
1186
1043
  threadId: processedParams.threadId,
1187
1044
  runtimeContext: processedParams.runtimeContext,
1188
1045
  // TODO: Pass proper tracing context when client-js supports tracing
1189
- tracingContext: { currentSpan: void 0 }
1046
+ tracingContext: { currentSpan: void 0 },
1047
+ suspend: async () => {
1048
+ }
1190
1049
  },
1191
1050
  {
1192
1051
  messages: response.messages,
1193
1052
  toolCallId: toolCall2?.toolCallId
1194
1053
  }
1195
1054
  );
1196
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1055
+ const lastMessageRaw = messages[messages.length - 1];
1056
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1197
1057
  const toolInvocationPart = lastMessage?.parts?.find(
1198
1058
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1199
1059
  );
@@ -1211,25 +1071,11 @@ var Agent = class extends BaseResource {
1211
1071
  toolInvocation.state = "result";
1212
1072
  toolInvocation.result = result;
1213
1073
  }
1214
- const writer = writable.getWriter();
1215
- try {
1216
- await writer.write(
1217
- new TextEncoder().encode(
1218
- "a:" + JSON.stringify({
1219
- toolCallId: toolCall2.toolCallId,
1220
- result
1221
- }) + "\n"
1222
- )
1223
- );
1224
- } finally {
1225
- writer.releaseLock();
1226
- }
1227
- const originalMessages = processedParams.messages;
1228
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1074
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1229
1075
  this.processStreamResponse_vNext(
1230
1076
  {
1231
1077
  ...processedParams,
1232
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1078
+ messages: updatedMessages
1233
1079
  },
1234
1080
  writable
1235
1081
  ).catch((error) => {
@@ -1237,6 +1083,11 @@ var Agent = class extends BaseResource {
1237
1083
  });
1238
1084
  }
1239
1085
  }
1086
+ if (!shouldExecuteClientTool) {
1087
+ setTimeout(() => {
1088
+ writable.close();
1089
+ }, 0);
1090
+ }
1240
1091
  } else {
1241
1092
  setTimeout(() => {
1242
1093
  writable.close();
@@ -1252,12 +1103,49 @@ var Agent = class extends BaseResource {
1252
1103
  }
1253
1104
  return response;
1254
1105
  }
1255
- async streamVNext(params) {
1106
+ async network(params) {
1107
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1108
+ method: "POST",
1109
+ body: params,
1110
+ stream: true
1111
+ });
1112
+ if (!response.body) {
1113
+ throw new Error("No response body");
1114
+ }
1115
+ const streamResponse = new Response(response.body, {
1116
+ status: response.status,
1117
+ statusText: response.statusText,
1118
+ headers: response.headers
1119
+ });
1120
+ streamResponse.processDataStream = async ({
1121
+ onChunk
1122
+ }) => {
1123
+ await processMastraNetworkStream({
1124
+ stream: streamResponse.body,
1125
+ onChunk
1126
+ });
1127
+ };
1128
+ return streamResponse;
1129
+ }
1130
+ async stream(messagesOrParams, options) {
1131
+ let params;
1132
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1133
+ params = messagesOrParams;
1134
+ } else {
1135
+ params = {
1136
+ messages: messagesOrParams,
1137
+ ...options
1138
+ };
1139
+ }
1256
1140
  const processedParams = {
1257
1141
  ...params,
1258
1142
  output: params.output ? zodToJsonSchema(params.output) : void 0,
1259
1143
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1260
- clientTools: processClientTools(params.clientTools)
1144
+ clientTools: processClientTools(params.clientTools),
1145
+ structuredOutput: params.structuredOutput ? {
1146
+ ...params.structuredOutput,
1147
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1148
+ } : void 0
1261
1149
  };
1262
1150
  const { readable, writable } = new TransformStream();
1263
1151
  const response = await this.processStreamResponse_vNext(processedParams, writable);
@@ -1324,7 +1212,9 @@ var Agent = class extends BaseResource {
1324
1212
  threadId: processedParams.threadId,
1325
1213
  runtimeContext: processedParams.runtimeContext,
1326
1214
  // TODO: Pass proper tracing context when client-js supports tracing
1327
- tracingContext: { currentSpan: void 0 }
1215
+ tracingContext: { currentSpan: void 0 },
1216
+ suspend: async () => {
1217
+ }
1328
1218
  },
1329
1219
  {
1330
1220
  messages: response.messages,
@@ -1362,12 +1252,10 @@ var Agent = class extends BaseResource {
1362
1252
  } finally {
1363
1253
  writer.releaseLock();
1364
1254
  }
1365
- const originalMessages = processedParams.messages;
1366
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1367
1255
  this.processStreamResponse(
1368
1256
  {
1369
1257
  ...processedParams,
1370
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1258
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1371
1259
  },
1372
1260
  writable
1373
1261
  ).catch((error) => {
@@ -1393,10 +1281,11 @@ var Agent = class extends BaseResource {
1393
1281
  /**
1394
1282
  * Gets details about a specific tool available to the agent
1395
1283
  * @param toolId - ID of the tool to retrieve
1284
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1396
1285
  * @returns Promise containing tool details
1397
1286
  */
1398
- getTool(toolId) {
1399
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1287
+ getTool(toolId, runtimeContext) {
1288
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
1400
1289
  }
1401
1290
  /**
1402
1291
  * Executes a tool for the agent
@@ -1407,7 +1296,7 @@ var Agent = class extends BaseResource {
1407
1296
  executeTool(toolId, params) {
1408
1297
  const body = {
1409
1298
  data: params.data,
1410
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1299
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1411
1300
  };
1412
1301
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1413
1302
  method: "POST",
@@ -1416,17 +1305,19 @@ var Agent = class extends BaseResource {
1416
1305
  }
1417
1306
  /**
1418
1307
  * Retrieves evaluation results for the agent
1308
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1419
1309
  * @returns Promise containing agent evaluations
1420
1310
  */
1421
- evals() {
1422
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1311
+ evals(runtimeContext) {
1312
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
1423
1313
  }
1424
1314
  /**
1425
1315
  * Retrieves live evaluation results for the agent
1316
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1426
1317
  * @returns Promise containing live agent evaluations
1427
1318
  */
1428
- liveEvals() {
1429
- return this.request(`/api/agents/${this.agentId}/evals/live`);
1319
+ liveEvals(runtimeContext) {
1320
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
1430
1321
  }
1431
1322
  /**
1432
1323
  * Updates the model for the agent
@@ -1439,61 +1330,33 @@ var Agent = class extends BaseResource {
1439
1330
  body: params
1440
1331
  });
1441
1332
  }
1442
- };
1443
- var Network = class extends BaseResource {
1444
- constructor(options, networkId) {
1445
- super(options);
1446
- this.networkId = networkId;
1447
- }
1448
- /**
1449
- * Retrieves details about the network
1450
- * @returns Promise containing network details
1451
- */
1452
- details() {
1453
- return this.request(`/api/networks/${this.networkId}`);
1454
- }
1455
1333
  /**
1456
- * Generates a response from the agent
1457
- * @param params - Generation parameters including prompt
1458
- * @returns Promise containing the generated response
1334
+ * Updates the model for the agent in the model list
1335
+ * @param params - Parameters for updating the model
1336
+ * @returns Promise containing the updated model
1459
1337
  */
1460
- generate(params) {
1461
- const processedParams = {
1462
- ...params,
1463
- output: zodToJsonSchema(params.output),
1464
- experimental_output: zodToJsonSchema(params.experimental_output)
1465
- };
1466
- return this.request(`/api/networks/${this.networkId}/generate`, {
1338
+ updateModelInModelList({ modelConfigId, ...params }) {
1339
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
1467
1340
  method: "POST",
1468
- body: processedParams
1341
+ body: params
1469
1342
  });
1470
1343
  }
1471
1344
  /**
1472
- * Streams a response from the agent
1473
- * @param params - Stream parameters including prompt
1474
- * @returns Promise containing the enhanced Response object with processDataStream method
1345
+ * Reorders the models for the agent
1346
+ * @param params - Parameters for reordering the model list
1347
+ * @returns Promise containing the updated model list
1475
1348
  */
1476
- async stream(params) {
1477
- const processedParams = {
1478
- ...params,
1479
- output: zodToJsonSchema(params.output),
1480
- experimental_output: zodToJsonSchema(params.experimental_output)
1481
- };
1482
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1349
+ reorderModelList(params) {
1350
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
1483
1351
  method: "POST",
1484
- body: processedParams,
1485
- stream: true
1352
+ body: params
1486
1353
  });
1487
- if (!response.body) {
1488
- throw new Error("No response body");
1489
- }
1490
- response.processDataStream = async (options = {}) => {
1491
- await uiUtils.processDataStream({
1492
- stream: response.body,
1493
- ...options
1494
- });
1495
- };
1496
- return response;
1354
+ }
1355
+ async generateVNext(_messagesOrParams, _options) {
1356
+ throw new Error("generateVNext has been renamed to generate. Please use generate instead.");
1357
+ }
1358
+ async streamVNext(_messagesOrParams, _options) {
1359
+ throw new Error("streamVNext has been renamed to stream. Please use stream instead.");
1497
1360
  }
1498
1361
  };
1499
1362
 
@@ -1584,10 +1447,13 @@ var Vector = class extends BaseResource {
1584
1447
  /**
1585
1448
  * Retrieves details about a specific vector index
1586
1449
  * @param indexName - Name of the index to get details for
1450
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1587
1451
  * @returns Promise containing vector index details
1588
1452
  */
1589
- details(indexName) {
1590
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1453
+ details(indexName, runtimeContext) {
1454
+ return this.request(
1455
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1456
+ );
1591
1457
  }
1592
1458
  /**
1593
1459
  * Deletes a vector index
@@ -1601,10 +1467,11 @@ var Vector = class extends BaseResource {
1601
1467
  }
1602
1468
  /**
1603
1469
  * Retrieves a list of all available indexes
1470
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1604
1471
  * @returns Promise containing array of index names
1605
1472
  */
1606
- getIndexes() {
1607
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1473
+ getIndexes(runtimeContext) {
1474
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
1608
1475
  }
1609
1476
  /**
1610
1477
  * Creates a new vector index
@@ -1641,127 +1508,54 @@ var Vector = class extends BaseResource {
1641
1508
  }
1642
1509
  };
1643
1510
 
1644
- // src/resources/legacy-workflow.ts
1645
- var RECORD_SEPARATOR = "";
1646
- var LegacyWorkflow = class extends BaseResource {
1647
- constructor(options, workflowId) {
1511
+ // src/resources/tool.ts
1512
+ var Tool = class extends BaseResource {
1513
+ constructor(options, toolId) {
1648
1514
  super(options);
1649
- this.workflowId = workflowId;
1650
- }
1651
- /**
1652
- * Retrieves details about the legacy workflow
1653
- * @returns Promise containing legacy workflow details including steps and graphs
1654
- */
1655
- details() {
1656
- return this.request(`/api/workflows/legacy/${this.workflowId}`);
1515
+ this.toolId = toolId;
1657
1516
  }
1658
1517
  /**
1659
- * Retrieves all runs for a legacy workflow
1660
- * @param params - Parameters for filtering runs
1661
- * @returns Promise containing legacy workflow runs array
1518
+ * Retrieves details about the tool
1519
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1520
+ * @returns Promise containing tool details including description and schemas
1662
1521
  */
1663
- runs(params) {
1664
- const searchParams = new URLSearchParams();
1665
- if (params?.fromDate) {
1666
- searchParams.set("fromDate", params.fromDate.toISOString());
1667
- }
1668
- if (params?.toDate) {
1669
- searchParams.set("toDate", params.toDate.toISOString());
1670
- }
1671
- if (params?.limit) {
1672
- searchParams.set("limit", String(params.limit));
1673
- }
1674
- if (params?.offset) {
1675
- searchParams.set("offset", String(params.offset));
1676
- }
1677
- if (params?.resourceId) {
1678
- searchParams.set("resourceId", params.resourceId);
1679
- }
1680
- if (searchParams.size) {
1681
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1682
- } else {
1683
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1684
- }
1522
+ details(runtimeContext) {
1523
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1685
1524
  }
1686
1525
  /**
1687
- * Creates a new legacy workflow run
1688
- * @returns Promise containing the generated run ID
1526
+ * Executes the tool with the provided parameters
1527
+ * @param params - Parameters required for tool execution
1528
+ * @returns Promise containing the tool execution results
1689
1529
  */
1690
- createRun(params) {
1691
- const searchParams = new URLSearchParams();
1692
- if (!!params?.runId) {
1693
- searchParams.set("runId", params.runId);
1530
+ execute(params) {
1531
+ const url = new URLSearchParams();
1532
+ if (params.runId) {
1533
+ url.set("runId", params.runId);
1694
1534
  }
1695
- return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1696
- method: "POST"
1697
- });
1698
- }
1699
- /**
1700
- * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1701
- * @param params - Object containing the runId and triggerData
1702
- * @returns Promise containing success message
1703
- */
1704
- start(params) {
1705
- return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1535
+ const body = {
1536
+ data: params.data,
1537
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1538
+ };
1539
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1706
1540
  method: "POST",
1707
- body: params?.triggerData
1541
+ body
1708
1542
  });
1709
1543
  }
1710
- /**
1711
- * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
1712
- * @param stepId - ID of the step to resume
1713
- * @param runId - ID of the legacy workflow run
1714
- * @param context - Context to resume the legacy workflow with
1715
- * @returns Promise containing the legacy workflow resume results
1716
- */
1717
- resume({
1718
- stepId,
1719
- runId,
1720
- context
1721
- }) {
1722
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
1723
- method: "POST",
1724
- body: {
1725
- stepId,
1726
- context
1727
- }
1728
- });
1544
+ };
1545
+
1546
+ // src/resources/workflow.ts
1547
+ var RECORD_SEPARATOR = "";
1548
+ var Workflow = class extends BaseResource {
1549
+ constructor(options, workflowId) {
1550
+ super(options);
1551
+ this.workflowId = workflowId;
1729
1552
  }
1730
1553
  /**
1731
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1732
- * @param params - Object containing the optional runId and triggerData
1733
- * @returns Promise containing the workflow execution results
1734
- */
1735
- startAsync(params) {
1736
- const searchParams = new URLSearchParams();
1737
- if (!!params?.runId) {
1738
- searchParams.set("runId", params.runId);
1739
- }
1740
- return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1741
- method: "POST",
1742
- body: params?.triggerData
1743
- });
1744
- }
1745
- /**
1746
- * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1747
- * @param params - Object containing the runId, stepId, and context
1748
- * @returns Promise containing the workflow resume results
1749
- */
1750
- resumeAsync(params) {
1751
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1752
- method: "POST",
1753
- body: {
1754
- stepId: params.stepId,
1755
- context: params.context
1756
- }
1757
- });
1758
- }
1759
- /**
1760
- * Creates an async generator that processes a readable stream and yields records
1761
- * separated by the Record Separator character (\x1E)
1762
- *
1763
- * @param stream - The readable stream to process
1764
- * @returns An async generator that yields parsed records
1554
+ * Creates an async generator that processes a readable stream and yields workflow records
1555
+ * separated by the Record Separator character (\x1E)
1556
+ *
1557
+ * @param stream - The readable stream to process
1558
+ * @returns An async generator that yields parsed records
1765
1559
  */
1766
1560
  async *streamProcessor(stream) {
1767
1561
  const reader = stream.getReader();
@@ -1801,126 +1595,22 @@ var LegacyWorkflow = class extends BaseResource {
1801
1595
  });
1802
1596
  }
1803
1597
  }
1804
- /**
1805
- * Watches legacy workflow transitions in real-time
1806
- * @param runId - Optional run ID to filter the watch stream
1807
- * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1808
- */
1809
- async watch({ runId }, onRecord) {
1810
- const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1811
- stream: true
1812
- });
1813
- if (!response.ok) {
1814
- throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1815
- }
1816
- if (!response.body) {
1817
- throw new Error("Response body is null");
1818
- }
1819
- for await (const record of this.streamProcessor(response.body)) {
1820
- onRecord(record);
1821
- }
1822
- }
1823
- };
1824
-
1825
- // src/resources/tool.ts
1826
- var Tool = class extends BaseResource {
1827
- constructor(options, toolId) {
1828
- super(options);
1829
- this.toolId = toolId;
1830
- }
1831
- /**
1832
- * Retrieves details about the tool
1833
- * @returns Promise containing tool details including description and schemas
1834
- */
1835
- details() {
1836
- return this.request(`/api/tools/${this.toolId}`);
1837
- }
1838
- /**
1839
- * Executes the tool with the provided parameters
1840
- * @param params - Parameters required for tool execution
1841
- * @returns Promise containing the tool execution results
1842
- */
1843
- execute(params) {
1844
- const url = new URLSearchParams();
1845
- if (params.runId) {
1846
- url.set("runId", params.runId);
1847
- }
1848
- const body = {
1849
- data: params.data,
1850
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1851
- };
1852
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1853
- method: "POST",
1854
- body
1855
- });
1856
- }
1857
- };
1858
-
1859
- // src/resources/workflow.ts
1860
- var RECORD_SEPARATOR2 = "";
1861
- var Workflow = class extends BaseResource {
1862
- constructor(options, workflowId) {
1863
- super(options);
1864
- this.workflowId = workflowId;
1865
- }
1866
- /**
1867
- * Creates an async generator that processes a readable stream and yields workflow records
1868
- * separated by the Record Separator character (\x1E)
1869
- *
1870
- * @param stream - The readable stream to process
1871
- * @returns An async generator that yields parsed records
1872
- */
1873
- async *streamProcessor(stream) {
1874
- const reader = stream.getReader();
1875
- let doneReading = false;
1876
- let buffer = "";
1877
- try {
1878
- while (!doneReading) {
1879
- const { done, value } = await reader.read();
1880
- doneReading = done;
1881
- if (done && !value) continue;
1882
- try {
1883
- const decoded = value ? new TextDecoder().decode(value) : "";
1884
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1885
- buffer = chunks.pop() || "";
1886
- for (const chunk of chunks) {
1887
- if (chunk) {
1888
- if (typeof chunk === "string") {
1889
- try {
1890
- const parsedChunk = JSON.parse(chunk);
1891
- yield parsedChunk;
1892
- } catch {
1893
- }
1894
- }
1895
- }
1896
- }
1897
- } catch {
1898
- }
1899
- }
1900
- if (buffer) {
1901
- try {
1902
- yield JSON.parse(buffer);
1903
- } catch {
1904
- }
1905
- }
1906
- } finally {
1907
- reader.cancel().catch(() => {
1908
- });
1909
- }
1910
- }
1911
1598
  /**
1912
1599
  * Retrieves details about the workflow
1600
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1913
1601
  * @returns Promise containing workflow details including steps and graphs
1914
1602
  */
1915
- details() {
1916
- return this.request(`/api/workflows/${this.workflowId}`);
1603
+ details(runtimeContext) {
1604
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1917
1605
  }
1918
1606
  /**
1919
1607
  * Retrieves all runs for a workflow
1920
1608
  * @param params - Parameters for filtering runs
1609
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1921
1610
  * @returns Promise containing workflow runs array
1922
1611
  */
1923
- runs(params) {
1612
+ runs(params, runtimeContext) {
1613
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1924
1614
  const searchParams = new URLSearchParams();
1925
1615
  if (params?.fromDate) {
1926
1616
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1937,6 +1627,9 @@ var Workflow = class extends BaseResource {
1937
1627
  if (params?.resourceId) {
1938
1628
  searchParams.set("resourceId", params.resourceId);
1939
1629
  }
1630
+ if (runtimeContextParam) {
1631
+ searchParams.set("runtimeContext", runtimeContextParam);
1632
+ }
1940
1633
  if (searchParams.size) {
1941
1634
  return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1942
1635
  } else {
@@ -1946,18 +1639,22 @@ var Workflow = class extends BaseResource {
1946
1639
  /**
1947
1640
  * Retrieves a specific workflow run by its ID
1948
1641
  * @param runId - The ID of the workflow run to retrieve
1642
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1949
1643
  * @returns Promise containing the workflow run details
1950
1644
  */
1951
- runById(runId) {
1952
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1645
+ runById(runId, runtimeContext) {
1646
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1953
1647
  }
1954
1648
  /**
1955
1649
  * Retrieves the execution result for a specific workflow run by its ID
1956
1650
  * @param runId - The ID of the workflow run to retrieve the execution result for
1651
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1957
1652
  * @returns Promise containing the workflow run execution result
1958
1653
  */
1959
- runExecutionResult(runId) {
1960
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1654
+ runExecutionResult(runId, runtimeContext) {
1655
+ return this.request(
1656
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1657
+ );
1961
1658
  }
1962
1659
  /**
1963
1660
  * Cancels a specific workflow run by its ID
@@ -1980,27 +1677,83 @@ var Workflow = class extends BaseResource {
1980
1677
  body: { event: params.event, data: params.data }
1981
1678
  });
1982
1679
  }
1680
+ /**
1681
+ * @deprecated Use createRunAsync() instead.
1682
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1683
+ */
1684
+ async createRun(_params) {
1685
+ throw new Error(
1686
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = workflow.createRun();\n After: const run = await workflow.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
1687
+ );
1688
+ }
1983
1689
  /**
1984
1690
  * Creates a new workflow run
1985
1691
  * @param params - Optional object containing the optional runId
1986
- * @returns Promise containing the runId of the created run
1692
+ * @returns Promise containing the runId of the created run with methods to control execution
1987
1693
  */
1988
- createRun(params) {
1694
+ async createRunAsync(params) {
1989
1695
  const searchParams = new URLSearchParams();
1990
1696
  if (!!params?.runId) {
1991
1697
  searchParams.set("runId", params.runId);
1992
1698
  }
1993
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1994
- method: "POST"
1995
- });
1996
- }
1997
- /**
1998
- * Creates a new workflow run (alias for createRun)
1999
- * @param params - Optional object containing the optional runId
2000
- * @returns Promise containing the runId of the created run
2001
- */
2002
- createRunAsync(params) {
2003
- return this.createRun(params);
1699
+ const res = await this.request(
1700
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1701
+ {
1702
+ method: "POST"
1703
+ }
1704
+ );
1705
+ const runId = res.runId;
1706
+ return {
1707
+ runId,
1708
+ start: async (p) => {
1709
+ return this.start({
1710
+ runId,
1711
+ inputData: p.inputData,
1712
+ runtimeContext: p.runtimeContext,
1713
+ tracingOptions: p.tracingOptions
1714
+ });
1715
+ },
1716
+ startAsync: async (p) => {
1717
+ return this.startAsync({
1718
+ runId,
1719
+ inputData: p.inputData,
1720
+ runtimeContext: p.runtimeContext,
1721
+ tracingOptions: p.tracingOptions
1722
+ });
1723
+ },
1724
+ watch: async (onRecord) => {
1725
+ return this.watch({ runId }, onRecord);
1726
+ },
1727
+ stream: async (p) => {
1728
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1729
+ },
1730
+ resume: async (p) => {
1731
+ return this.resume({
1732
+ runId,
1733
+ step: p.step,
1734
+ resumeData: p.resumeData,
1735
+ runtimeContext: p.runtimeContext,
1736
+ tracingOptions: p.tracingOptions
1737
+ });
1738
+ },
1739
+ resumeAsync: async (p) => {
1740
+ return this.resumeAsync({
1741
+ runId,
1742
+ step: p.step,
1743
+ resumeData: p.resumeData,
1744
+ runtimeContext: p.runtimeContext,
1745
+ tracingOptions: p.tracingOptions
1746
+ });
1747
+ },
1748
+ resumeStreamVNext: async (p) => {
1749
+ return this.resumeStreamVNext({
1750
+ runId,
1751
+ step: p.step,
1752
+ resumeData: p.resumeData,
1753
+ runtimeContext: p.runtimeContext
1754
+ });
1755
+ }
1756
+ };
2004
1757
  }
2005
1758
  /**
2006
1759
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -2011,7 +1764,7 @@ var Workflow = class extends BaseResource {
2011
1764
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2012
1765
  return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
2013
1766
  method: "POST",
2014
- body: { inputData: params?.inputData, runtimeContext }
1767
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
2015
1768
  });
2016
1769
  }
2017
1770
  /**
@@ -2023,16 +1776,17 @@ var Workflow = class extends BaseResource {
2023
1776
  step,
2024
1777
  runId,
2025
1778
  resumeData,
1779
+ tracingOptions,
2026
1780
  ...rest
2027
1781
  }) {
2028
1782
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
2029
1783
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
2030
1784
  method: "POST",
2031
- stream: true,
2032
1785
  body: {
2033
1786
  step,
2034
1787
  resumeData,
2035
- runtimeContext
1788
+ runtimeContext,
1789
+ tracingOptions
2036
1790
  }
2037
1791
  });
2038
1792
  }
@@ -2049,7 +1803,7 @@ var Workflow = class extends BaseResource {
2049
1803
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2050
1804
  return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
2051
1805
  method: "POST",
2052
- body: { inputData: params.inputData, runtimeContext }
1806
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
2053
1807
  });
2054
1808
  }
2055
1809
  /**
@@ -2067,7 +1821,110 @@ var Workflow = class extends BaseResource {
2067
1821
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
2068
1822
  {
2069
1823
  method: "POST",
2070
- body: { inputData: params.inputData, runtimeContext },
1824
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions },
1825
+ stream: true
1826
+ }
1827
+ );
1828
+ if (!response.ok) {
1829
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1830
+ }
1831
+ if (!response.body) {
1832
+ throw new Error("Response body is null");
1833
+ }
1834
+ let failedChunk = void 0;
1835
+ const transformStream = new TransformStream({
1836
+ start() {
1837
+ },
1838
+ async transform(chunk, controller) {
1839
+ try {
1840
+ const decoded = new TextDecoder().decode(chunk);
1841
+ const chunks = decoded.split(RECORD_SEPARATOR);
1842
+ for (const chunk2 of chunks) {
1843
+ if (chunk2) {
1844
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1845
+ try {
1846
+ const parsedChunk = JSON.parse(newChunk);
1847
+ controller.enqueue(parsedChunk);
1848
+ failedChunk = void 0;
1849
+ } catch {
1850
+ failedChunk = newChunk;
1851
+ }
1852
+ }
1853
+ }
1854
+ } catch {
1855
+ }
1856
+ }
1857
+ });
1858
+ return response.body.pipeThrough(transformStream);
1859
+ }
1860
+ /**
1861
+ * Observes workflow stream for a workflow run
1862
+ * @param params - Object containing the runId
1863
+ * @returns Promise containing the workflow execution results
1864
+ */
1865
+ async observeStream(params) {
1866
+ const searchParams = new URLSearchParams();
1867
+ searchParams.set("runId", params.runId);
1868
+ const response = await this.request(
1869
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1870
+ {
1871
+ method: "POST",
1872
+ stream: true
1873
+ }
1874
+ );
1875
+ if (!response.ok) {
1876
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1877
+ }
1878
+ if (!response.body) {
1879
+ throw new Error("Response body is null");
1880
+ }
1881
+ let failedChunk = void 0;
1882
+ const transformStream = new TransformStream({
1883
+ start() {
1884
+ },
1885
+ async transform(chunk, controller) {
1886
+ try {
1887
+ const decoded = new TextDecoder().decode(chunk);
1888
+ const chunks = decoded.split(RECORD_SEPARATOR);
1889
+ for (const chunk2 of chunks) {
1890
+ if (chunk2) {
1891
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1892
+ try {
1893
+ const parsedChunk = JSON.parse(newChunk);
1894
+ controller.enqueue(parsedChunk);
1895
+ failedChunk = void 0;
1896
+ } catch {
1897
+ failedChunk = newChunk;
1898
+ }
1899
+ }
1900
+ }
1901
+ } catch {
1902
+ }
1903
+ }
1904
+ });
1905
+ return response.body.pipeThrough(transformStream);
1906
+ }
1907
+ /**
1908
+ * Starts a workflow run and returns a stream
1909
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1910
+ * @returns Promise containing the workflow execution results
1911
+ */
1912
+ async streamVNext(params) {
1913
+ const searchParams = new URLSearchParams();
1914
+ if (!!params?.runId) {
1915
+ searchParams.set("runId", params.runId);
1916
+ }
1917
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1918
+ const response = await this.request(
1919
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1920
+ {
1921
+ method: "POST",
1922
+ body: {
1923
+ inputData: params.inputData,
1924
+ runtimeContext,
1925
+ closeOnSuspend: params.closeOnSuspend,
1926
+ tracingOptions: params.tracingOptions
1927
+ },
2071
1928
  stream: true
2072
1929
  }
2073
1930
  );
@@ -2084,7 +1941,54 @@ var Workflow = class extends BaseResource {
2084
1941
  async transform(chunk, controller) {
2085
1942
  try {
2086
1943
  const decoded = new TextDecoder().decode(chunk);
2087
- const chunks = decoded.split(RECORD_SEPARATOR2);
1944
+ const chunks = decoded.split(RECORD_SEPARATOR);
1945
+ for (const chunk2 of chunks) {
1946
+ if (chunk2) {
1947
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1948
+ try {
1949
+ const parsedChunk = JSON.parse(newChunk);
1950
+ controller.enqueue(parsedChunk);
1951
+ failedChunk = void 0;
1952
+ } catch {
1953
+ failedChunk = newChunk;
1954
+ }
1955
+ }
1956
+ }
1957
+ } catch {
1958
+ }
1959
+ }
1960
+ });
1961
+ return response.body.pipeThrough(transformStream);
1962
+ }
1963
+ /**
1964
+ * Observes workflow vNext stream for a workflow run
1965
+ * @param params - Object containing the runId
1966
+ * @returns Promise containing the workflow execution results
1967
+ */
1968
+ async observeStreamVNext(params) {
1969
+ const searchParams = new URLSearchParams();
1970
+ searchParams.set("runId", params.runId);
1971
+ const response = await this.request(
1972
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
1973
+ {
1974
+ method: "POST",
1975
+ stream: true
1976
+ }
1977
+ );
1978
+ if (!response.ok) {
1979
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
1980
+ }
1981
+ if (!response.body) {
1982
+ throw new Error("Response body is null");
1983
+ }
1984
+ let failedChunk = void 0;
1985
+ const transformStream = new TransformStream({
1986
+ start() {
1987
+ },
1988
+ async transform(chunk, controller) {
1989
+ try {
1990
+ const decoded = new TextDecoder().decode(chunk);
1991
+ const chunks = decoded.split(RECORD_SEPARATOR);
2088
1992
  for (const chunk2 of chunks) {
2089
1993
  if (chunk2) {
2090
1994
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2115,9 +2019,64 @@ var Workflow = class extends BaseResource {
2115
2019
  body: {
2116
2020
  step: params.step,
2117
2021
  resumeData: params.resumeData,
2118
- runtimeContext
2022
+ runtimeContext,
2023
+ tracingOptions: params.tracingOptions
2024
+ }
2025
+ });
2026
+ }
2027
+ /**
2028
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2029
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2030
+ * @returns Promise containing the workflow resume results
2031
+ */
2032
+ async resumeStreamVNext(params) {
2033
+ const searchParams = new URLSearchParams();
2034
+ searchParams.set("runId", params.runId);
2035
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2036
+ const response = await this.request(
2037
+ `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
2038
+ {
2039
+ method: "POST",
2040
+ body: {
2041
+ step: params.step,
2042
+ resumeData: params.resumeData,
2043
+ runtimeContext,
2044
+ tracingOptions: params.tracingOptions
2045
+ },
2046
+ stream: true
2047
+ }
2048
+ );
2049
+ if (!response.ok) {
2050
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2051
+ }
2052
+ if (!response.body) {
2053
+ throw new Error("Response body is null");
2054
+ }
2055
+ let failedChunk = void 0;
2056
+ const transformStream = new TransformStream({
2057
+ start() {
2058
+ },
2059
+ async transform(chunk, controller) {
2060
+ try {
2061
+ const decoded = new TextDecoder().decode(chunk);
2062
+ const chunks = decoded.split(RECORD_SEPARATOR);
2063
+ for (const chunk2 of chunks) {
2064
+ if (chunk2) {
2065
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2066
+ try {
2067
+ const parsedChunk = JSON.parse(newChunk);
2068
+ controller.enqueue(parsedChunk);
2069
+ failedChunk = void 0;
2070
+ } catch {
2071
+ failedChunk = newChunk;
2072
+ }
2073
+ }
2074
+ }
2075
+ } catch {
2076
+ }
2119
2077
  }
2120
2078
  });
2079
+ return response.body.pipeThrough(transformStream);
2121
2080
  }
2122
2081
  /**
2123
2082
  * Watches workflow transitions in real-time
@@ -2155,7 +2114,7 @@ var Workflow = class extends BaseResource {
2155
2114
  async start(controller) {
2156
2115
  try {
2157
2116
  for await (const record of records) {
2158
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2117
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
2159
2118
  controller.enqueue(encoder.encode(json));
2160
2119
  }
2161
2120
  controller.close();
@@ -2253,10 +2212,11 @@ var MCPTool = class extends BaseResource {
2253
2212
  }
2254
2213
  /**
2255
2214
  * Retrieves details about this specific tool from the MCP server.
2215
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2256
2216
  * @returns Promise containing the tool's information (name, description, schema).
2257
2217
  */
2258
- details() {
2259
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2218
+ details(runtimeContext) {
2219
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2260
2220
  }
2261
2221
  /**
2262
2222
  * Executes this specific tool on the MCP server.
@@ -2277,7 +2237,7 @@ var MCPTool = class extends BaseResource {
2277
2237
  };
2278
2238
 
2279
2239
  // src/resources/agent-builder.ts
2280
- var RECORD_SEPARATOR3 = "";
2240
+ var RECORD_SEPARATOR2 = "";
2281
2241
  var AgentBuilder = class extends BaseResource {
2282
2242
  constructor(options, actionId) {
2283
2243
  super(options);
@@ -2312,21 +2272,27 @@ var AgentBuilder = class extends BaseResource {
2312
2272
  };
2313
2273
  }
2314
2274
  }
2275
+ /**
2276
+ * @deprecated Use createRunAsync() instead.
2277
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2278
+ */
2279
+ async createRun(_params) {
2280
+ throw new Error(
2281
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = agentBuilder.createRun();\n After: const run = await agentBuilder.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
2282
+ );
2283
+ }
2315
2284
  /**
2316
2285
  * Creates a new agent builder action run and returns the runId.
2317
2286
  * This calls `/api/agent-builder/:actionId/create-run`.
2318
2287
  */
2319
- async createRun(params, runId) {
2288
+ async createRunAsync(params) {
2320
2289
  const searchParams = new URLSearchParams();
2321
- if (runId) {
2322
- searchParams.set("runId", runId);
2290
+ if (!!params?.runId) {
2291
+ searchParams.set("runId", params.runId);
2323
2292
  }
2324
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2325
- const { runtimeContext: _, ...actionParams } = params;
2326
2293
  const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2327
2294
  return this.request(url, {
2328
- method: "POST",
2329
- body: { ...actionParams, runtimeContext }
2295
+ method: "POST"
2330
2296
  });
2331
2297
  }
2332
2298
  /**
@@ -2411,7 +2377,7 @@ var AgentBuilder = class extends BaseResource {
2411
2377
  if (done && !value) continue;
2412
2378
  try {
2413
2379
  const decoded = value ? new TextDecoder().decode(value) : "";
2414
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2380
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2415
2381
  buffer = chunks.pop() || "";
2416
2382
  for (const chunk of chunks) {
2417
2383
  if (chunk) {
@@ -2468,7 +2434,7 @@ var AgentBuilder = class extends BaseResource {
2468
2434
  async transform(chunk, controller) {
2469
2435
  try {
2470
2436
  const decoded = new TextDecoder().decode(chunk);
2471
- const chunks = decoded.split(RECORD_SEPARATOR3);
2437
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2472
2438
  for (const chunk2 of chunks) {
2473
2439
  if (chunk2) {
2474
2440
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2517,7 +2483,7 @@ var AgentBuilder = class extends BaseResource {
2517
2483
  async transform(chunk, controller) {
2518
2484
  try {
2519
2485
  const decoded = new TextDecoder().decode(chunk);
2520
- const chunks = decoded.split(RECORD_SEPARATOR3);
2486
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2521
2487
  for (const chunk2 of chunks) {
2522
2488
  if (chunk2) {
2523
2489
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2542,8 +2508,8 @@ var AgentBuilder = class extends BaseResource {
2542
2508
  * and streams any remaining progress.
2543
2509
  * This calls `/api/agent-builder/:actionId/watch`.
2544
2510
  */
2545
- async watch({ runId }, onRecord) {
2546
- const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}`;
2511
+ async watch({ runId, eventType }, onRecord) {
2512
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2547
2513
  const response = await this.request(url, {
2548
2514
  method: "GET",
2549
2515
  stream: true
@@ -2660,7 +2626,7 @@ var Observability = class extends BaseResource {
2660
2626
  getTraces(params) {
2661
2627
  const { pagination, filters } = params;
2662
2628
  const { page, perPage, dateRange } = pagination || {};
2663
- const { name, spanType } = filters || {};
2629
+ const { name, spanType, entityId, entityType } = filters || {};
2664
2630
  const searchParams = new URLSearchParams();
2665
2631
  if (page !== void 0) {
2666
2632
  searchParams.set("page", String(page));
@@ -2674,6 +2640,10 @@ var Observability = class extends BaseResource {
2674
2640
  if (spanType !== void 0) {
2675
2641
  searchParams.set("spanType", String(spanType));
2676
2642
  }
2643
+ if (entityId && entityType) {
2644
+ searchParams.set("entityId", entityId);
2645
+ searchParams.set("entityType", entityType);
2646
+ }
2677
2647
  if (dateRange) {
2678
2648
  const dateRangeStr = JSON.stringify({
2679
2649
  start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
@@ -2684,6 +2654,31 @@ var Observability = class extends BaseResource {
2684
2654
  const queryString = searchParams.toString();
2685
2655
  return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2686
2656
  }
2657
+ /**
2658
+ * Retrieves scores by trace ID and span ID
2659
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2660
+ * @returns Promise containing scores and pagination info
2661
+ */
2662
+ getScoresBySpan(params) {
2663
+ const { traceId, spanId, page, perPage } = params;
2664
+ const searchParams = new URLSearchParams();
2665
+ if (page !== void 0) {
2666
+ searchParams.set("page", String(page));
2667
+ }
2668
+ if (perPage !== void 0) {
2669
+ searchParams.set("perPage", String(perPage));
2670
+ }
2671
+ const queryString = searchParams.toString();
2672
+ return this.request(
2673
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2674
+ );
2675
+ }
2676
+ score(params) {
2677
+ return this.request(`/api/observability/traces/score`, {
2678
+ method: "POST",
2679
+ body: { ...params }
2680
+ });
2681
+ }
2687
2682
  };
2688
2683
 
2689
2684
  // src/resources/network-memory-thread.ts
@@ -2749,144 +2744,6 @@ var NetworkMemoryThread = class extends BaseResource {
2749
2744
  }
2750
2745
  };
2751
2746
 
2752
- // src/resources/vNextNetwork.ts
2753
- var RECORD_SEPARATOR4 = "";
2754
- var VNextNetwork = class extends BaseResource {
2755
- constructor(options, networkId) {
2756
- super(options);
2757
- this.networkId = networkId;
2758
- }
2759
- /**
2760
- * Retrieves details about the network
2761
- * @returns Promise containing vNext network details
2762
- */
2763
- details() {
2764
- return this.request(`/api/networks/v-next/${this.networkId}`);
2765
- }
2766
- /**
2767
- * Generates a response from the v-next network
2768
- * @param params - Generation parameters including message
2769
- * @returns Promise containing the generated response
2770
- */
2771
- generate(params) {
2772
- return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
2773
- method: "POST",
2774
- body: {
2775
- ...params,
2776
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2777
- }
2778
- });
2779
- }
2780
- /**
2781
- * Generates a response from the v-next network using multiple primitives
2782
- * @param params - Generation parameters including message
2783
- * @returns Promise containing the generated response
2784
- */
2785
- loop(params) {
2786
- return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
2787
- method: "POST",
2788
- body: {
2789
- ...params,
2790
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2791
- }
2792
- });
2793
- }
2794
- async *streamProcessor(stream) {
2795
- const reader = stream.getReader();
2796
- let doneReading = false;
2797
- let buffer = "";
2798
- try {
2799
- while (!doneReading) {
2800
- const { done, value } = await reader.read();
2801
- doneReading = done;
2802
- if (done && !value) continue;
2803
- try {
2804
- const decoded = value ? new TextDecoder().decode(value) : "";
2805
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
2806
- buffer = chunks.pop() || "";
2807
- for (const chunk of chunks) {
2808
- if (chunk) {
2809
- if (typeof chunk === "string") {
2810
- try {
2811
- const parsedChunk = JSON.parse(chunk);
2812
- yield parsedChunk;
2813
- } catch {
2814
- }
2815
- }
2816
- }
2817
- }
2818
- } catch {
2819
- }
2820
- }
2821
- if (buffer) {
2822
- try {
2823
- yield JSON.parse(buffer);
2824
- } catch {
2825
- }
2826
- }
2827
- } finally {
2828
- reader.cancel().catch(() => {
2829
- });
2830
- }
2831
- }
2832
- /**
2833
- * Streams a response from the v-next network
2834
- * @param params - Stream parameters including message
2835
- * @returns Promise containing the results
2836
- */
2837
- async stream(params, onRecord) {
2838
- const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
2839
- method: "POST",
2840
- body: {
2841
- ...params,
2842
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2843
- },
2844
- stream: true
2845
- });
2846
- if (!response.ok) {
2847
- throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2848
- }
2849
- if (!response.body) {
2850
- throw new Error("Response body is null");
2851
- }
2852
- for await (const record of this.streamProcessor(response.body)) {
2853
- if (typeof record === "string") {
2854
- onRecord(JSON.parse(record));
2855
- } else {
2856
- onRecord(record);
2857
- }
2858
- }
2859
- }
2860
- /**
2861
- * Streams a response from the v-next network loop
2862
- * @param params - Stream parameters including message
2863
- * @returns Promise containing the results
2864
- */
2865
- async loopStream(params, onRecord) {
2866
- const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
2867
- method: "POST",
2868
- body: {
2869
- ...params,
2870
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2871
- },
2872
- stream: true
2873
- });
2874
- if (!response.ok) {
2875
- throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2876
- }
2877
- if (!response.body) {
2878
- throw new Error("Response body is null");
2879
- }
2880
- for await (const record of this.streamProcessor(response.body)) {
2881
- if (typeof record === "string") {
2882
- onRecord(JSON.parse(record));
2883
- } else {
2884
- onRecord(record);
2885
- }
2886
- }
2887
- }
2888
- };
2889
-
2890
2747
  // src/client.ts
2891
2748
  var MastraClient = class extends BaseResource {
2892
2749
  observability;
@@ -2896,25 +2753,17 @@ var MastraClient = class extends BaseResource {
2896
2753
  }
2897
2754
  /**
2898
2755
  * Retrieves all available agents
2756
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2899
2757
  * @returns Promise containing map of agent IDs to agent details
2900
2758
  */
2901
- getAgents() {
2902
- return this.request("/api/agents");
2903
- }
2904
- async getAGUI({ resourceId }) {
2905
- const agents = await this.getAgents();
2906
- return Object.entries(agents).reduce(
2907
- (acc, [agentId]) => {
2908
- const agent = this.getAgent(agentId);
2909
- acc[agentId] = new AGUIAdapter({
2910
- agentId,
2911
- agent,
2912
- resourceId
2913
- });
2914
- return acc;
2915
- },
2916
- {}
2917
- );
2759
+ getAgents(runtimeContext) {
2760
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2761
+ const searchParams = new URLSearchParams();
2762
+ if (runtimeContextParam) {
2763
+ searchParams.set("runtimeContext", runtimeContextParam);
2764
+ }
2765
+ const queryString = searchParams.toString();
2766
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
2918
2767
  }
2919
2768
  /**
2920
2769
  * Gets an agent instance by ID
@@ -2932,6 +2781,14 @@ var MastraClient = class extends BaseResource {
2932
2781
  getMemoryThreads(params) {
2933
2782
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
2934
2783
  }
2784
+ /**
2785
+ * Retrieves memory config for a resource
2786
+ * @param params - Parameters containing the resource ID
2787
+ * @returns Promise containing array of memory threads
2788
+ */
2789
+ getMemoryConfig(params) {
2790
+ return this.request(`/api/memory/config?agentId=${params.agentId}`);
2791
+ }
2935
2792
  /**
2936
2793
  * Creates a new memory thread
2937
2794
  * @param params - Parameters for creating the memory thread
@@ -2948,6 +2805,24 @@ var MastraClient = class extends BaseResource {
2948
2805
  getMemoryThread(threadId, agentId) {
2949
2806
  return new MemoryThread(this.options, threadId, agentId);
2950
2807
  }
2808
+ getThreadMessages(threadId, opts = {}) {
2809
+ let url = "";
2810
+ if (opts.agentId) {
2811
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}`;
2812
+ } else if (opts.networkId) {
2813
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}`;
2814
+ }
2815
+ return this.request(url);
2816
+ }
2817
+ deleteThread(threadId, opts = {}) {
2818
+ let url = "";
2819
+ if (opts.agentId) {
2820
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}`;
2821
+ } else if (opts.networkId) {
2822
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}`;
2823
+ }
2824
+ return this.request(url, { method: "DELETE" });
2825
+ }
2951
2826
  /**
2952
2827
  * Saves messages to memory
2953
2828
  * @param params - Parameters containing messages to save
@@ -3010,10 +2885,17 @@ var MastraClient = class extends BaseResource {
3010
2885
  }
3011
2886
  /**
3012
2887
  * Retrieves all available tools
2888
+ * @param runtimeContext - Optional runtime context to pass as query parameter
3013
2889
  * @returns Promise containing map of tool IDs to tool details
3014
2890
  */
3015
- getTools() {
3016
- return this.request("/api/tools");
2891
+ getTools(runtimeContext) {
2892
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2893
+ const searchParams = new URLSearchParams();
2894
+ if (runtimeContextParam) {
2895
+ searchParams.set("runtimeContext", runtimeContextParam);
2896
+ }
2897
+ const queryString = searchParams.toString();
2898
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
3017
2899
  }
3018
2900
  /**
3019
2901
  * Gets a tool instance by ID
@@ -3023,27 +2905,19 @@ var MastraClient = class extends BaseResource {
3023
2905
  getTool(toolId) {
3024
2906
  return new Tool(this.options, toolId);
3025
2907
  }
3026
- /**
3027
- * Retrieves all available legacy workflows
3028
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
3029
- */
3030
- getLegacyWorkflows() {
3031
- return this.request("/api/workflows/legacy");
3032
- }
3033
- /**
3034
- * Gets a legacy workflow instance by ID
3035
- * @param workflowId - ID of the legacy workflow to retrieve
3036
- * @returns Legacy Workflow instance
3037
- */
3038
- getLegacyWorkflow(workflowId) {
3039
- return new LegacyWorkflow(this.options, workflowId);
3040
- }
3041
2908
  /**
3042
2909
  * Retrieves all available workflows
2910
+ * @param runtimeContext - Optional runtime context to pass as query parameter
3043
2911
  * @returns Promise containing map of workflow IDs to workflow details
3044
2912
  */
3045
- getWorkflows() {
3046
- return this.request("/api/workflows");
2913
+ getWorkflows(runtimeContext) {
2914
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2915
+ const searchParams = new URLSearchParams();
2916
+ if (runtimeContextParam) {
2917
+ searchParams.set("runtimeContext", runtimeContextParam);
2918
+ }
2919
+ const queryString = searchParams.toString();
2920
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
3047
2921
  }
3048
2922
  /**
3049
2923
  * Gets a workflow instance by ID
@@ -3211,36 +3085,6 @@ var MastraClient = class extends BaseResource {
3211
3085
  return this.request(`/api/telemetry`);
3212
3086
  }
3213
3087
  }
3214
- /**
3215
- * Retrieves all available networks
3216
- * @returns Promise containing map of network IDs to network details
3217
- */
3218
- getNetworks() {
3219
- return this.request("/api/networks");
3220
- }
3221
- /**
3222
- * Retrieves all available vNext networks
3223
- * @returns Promise containing map of vNext network IDs to vNext network details
3224
- */
3225
- getVNextNetworks() {
3226
- return this.request("/api/networks/v-next");
3227
- }
3228
- /**
3229
- * Gets a network instance by ID
3230
- * @param networkId - ID of the network to retrieve
3231
- * @returns Network instance
3232
- */
3233
- getNetwork(networkId) {
3234
- return new Network(this.options, networkId);
3235
- }
3236
- /**
3237
- * Gets a vNext network instance by ID
3238
- * @param networkId - ID of the vNext network to retrieve
3239
- * @returns vNext Network instance
3240
- */
3241
- getVNextNetwork(networkId) {
3242
- return new VNextNetwork(this.options, networkId);
3243
- }
3244
3088
  /**
3245
3089
  * Retrieves a list of available MCP servers.
3246
3090
  * @param params - Optional parameters for pagination (limit, offset).
@@ -3345,7 +3189,7 @@ var MastraClient = class extends BaseResource {
3345
3189
  * @returns Promise containing the scorer
3346
3190
  */
3347
3191
  getScorer(scorerId) {
3348
- return this.request(`/api/scores/scorers/${scorerId}`);
3192
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3349
3193
  }
3350
3194
  getScoresByScorerId(params) {
3351
3195
  const { page, perPage, scorerId, entityId, entityType } = params;
@@ -3363,7 +3207,7 @@ var MastraClient = class extends BaseResource {
3363
3207
  searchParams.set("perPage", String(perPage));
3364
3208
  }
3365
3209
  const queryString = searchParams.toString();
3366
- return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3210
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3367
3211
  }
3368
3212
  /**
3369
3213
  * Retrieves scores by run ID
@@ -3380,7 +3224,7 @@ var MastraClient = class extends BaseResource {
3380
3224
  searchParams.set("perPage", String(perPage));
3381
3225
  }
3382
3226
  const queryString = searchParams.toString();
3383
- return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3227
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
3384
3228
  }
3385
3229
  /**
3386
3230
  * Retrieves scores by entity ID and type
@@ -3397,7 +3241,9 @@ var MastraClient = class extends BaseResource {
3397
3241
  searchParams.set("perPage", String(perPage));
3398
3242
  }
3399
3243
  const queryString = searchParams.toString();
3400
- return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3244
+ return this.request(
3245
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3246
+ );
3401
3247
  }
3402
3248
  /**
3403
3249
  * Saves a score
@@ -3423,8 +3269,35 @@ var MastraClient = class extends BaseResource {
3423
3269
  getAITraces(params) {
3424
3270
  return this.observability.getTraces(params);
3425
3271
  }
3272
+ getScoresBySpan(params) {
3273
+ return this.observability.getScoresBySpan(params);
3274
+ }
3275
+ score(params) {
3276
+ return this.observability.score(params);
3277
+ }
3426
3278
  };
3427
3279
 
3280
+ // src/tools.ts
3281
+ var ClientTool = class {
3282
+ id;
3283
+ description;
3284
+ inputSchema;
3285
+ outputSchema;
3286
+ execute;
3287
+ constructor(opts) {
3288
+ this.id = opts.id;
3289
+ this.description = opts.description;
3290
+ this.inputSchema = opts.inputSchema;
3291
+ this.outputSchema = opts.outputSchema;
3292
+ this.execute = opts.execute;
3293
+ }
3294
+ };
3295
+ function createTool(opts) {
3296
+ return new ClientTool(opts);
3297
+ }
3298
+
3299
+ exports.ClientTool = ClientTool;
3428
3300
  exports.MastraClient = MastraClient;
3301
+ exports.createTool = createTool;
3429
3302
  //# sourceMappingURL=index.cjs.map
3430
3303
  //# sourceMappingURL=index.cjs.map