@mastra/client-js 0.0.0-pgvector-index-fix-20250905222058 → 0.0.0-playground-studio-cloud-20251031080052

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 (41) hide show
  1. package/CHANGELOG.md +590 -10
  2. package/README.md +6 -10
  3. package/dist/client.d.ts +45 -45
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/index.cjs +802 -690
  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 +801 -691
  10. package/dist/index.js.map +1 -1
  11. package/dist/resources/agent-builder.d.ts +5 -6
  12. package/dist/resources/agent-builder.d.ts.map +1 -1
  13. package/dist/resources/agent.d.ts +91 -42
  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 +105 -96
  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 +6 -6
  36. package/dist/resources/legacy-workflow.d.ts +0 -87
  37. package/dist/resources/legacy-workflow.d.ts.map +0 -1
  38. package/dist/resources/network.d.ts +0 -30
  39. package/dist/resources/network.d.ts.map +0 -1
  40. package/dist/resources/vNextNetwork.d.ts +0 -42
  41. package/dist/resources/vNextNetwork.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
2
2
  import { v4 } from '@lukeed/uuid';
3
+ import { getErrorFromUnknown } from '@mastra/core/error';
3
4
  import { RuntimeContext } from '@mastra/core/runtime-context';
4
5
  import { isVercelTool } from '@mastra/core/tools/is-vercel-tool';
5
6
  import { z } from 'zod';
@@ -15,6 +16,20 @@ function parseClientRuntimeContext(runtimeContext) {
15
16
  }
16
17
  return void 0;
17
18
  }
19
+ function base64RuntimeContext(runtimeContext) {
20
+ if (runtimeContext) {
21
+ return btoa(JSON.stringify(runtimeContext));
22
+ }
23
+ return void 0;
24
+ }
25
+ function runtimeContextQueryString(runtimeContext) {
26
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
27
+ if (!runtimeContextParam) return "";
28
+ const searchParams = new URLSearchParams();
29
+ searchParams.set("runtimeContext", runtimeContextParam);
30
+ const queryString = searchParams.toString();
31
+ return queryString ? `?${queryString}` : "";
32
+ }
18
33
  function isZodType(value) {
19
34
  return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
20
35
  }
@@ -26,7 +41,7 @@ function zodToJsonSchema(zodSchema) {
26
41
  const fn = "toJSONSchema";
27
42
  return z[fn].call(z, zodSchema);
28
43
  }
29
- return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
44
+ return originalZodToJsonSchema(zodSchema, { $refStrategy: "relative" });
30
45
  }
31
46
 
32
47
  // src/utils/process-client-tools.ts
@@ -59,7 +74,7 @@ function processClientTools(clientTools) {
59
74
  }
60
75
 
61
76
  // src/utils/process-mastra-stream.ts
62
- async function processMastraStream({
77
+ async function sharedProcessMastraStream({
63
78
  stream,
64
79
  onChunk
65
80
  }) {
@@ -77,14 +92,18 @@ async function processMastraStream({
77
92
  if (line.startsWith("data: ")) {
78
93
  const data = line.slice(6);
79
94
  if (data === "[DONE]") {
80
- console.log("\u{1F3C1} Stream finished");
95
+ console.info("\u{1F3C1} Stream finished");
81
96
  return;
82
97
  }
98
+ let json;
83
99
  try {
84
- const json = JSON.parse(data);
85
- await onChunk(json);
100
+ json = JSON.parse(data);
86
101
  } catch (error) {
87
102
  console.error("\u274C JSON parse error:", error, "Data:", data);
103
+ continue;
104
+ }
105
+ if (json) {
106
+ await onChunk(json);
88
107
  }
89
108
  }
90
109
  }
@@ -93,6 +112,24 @@ async function processMastraStream({
93
112
  reader.releaseLock();
94
113
  }
95
114
  }
115
+ async function processMastraNetworkStream({
116
+ stream,
117
+ onChunk
118
+ }) {
119
+ return sharedProcessMastraStream({
120
+ stream,
121
+ onChunk
122
+ });
123
+ }
124
+ async function processMastraStream({
125
+ stream,
126
+ onChunk
127
+ }) {
128
+ return sharedProcessMastraStream({
129
+ stream,
130
+ onChunk
131
+ });
132
+ }
96
133
 
97
134
  // src/resources/base.ts
98
135
  var BaseResource = class {
@@ -181,7 +218,9 @@ async function executeToolCallAndRespond({
181
218
  resourceId,
182
219
  threadId,
183
220
  runtimeContext,
184
- tracingContext: { currentSpan: void 0 }
221
+ tracingContext: { currentSpan: void 0 },
222
+ suspend: async () => {
223
+ }
185
224
  },
186
225
  {
187
226
  messages: response.messages,
@@ -189,11 +228,7 @@ async function executeToolCallAndRespond({
189
228
  }
190
229
  );
191
230
  const updatedMessages = [
192
- {
193
- role: "user",
194
- content: params.messages
195
- },
196
- ...response.response.messages,
231
+ ...response.response.messages || [],
197
232
  {
198
233
  role: "tool",
199
234
  content: [
@@ -255,17 +290,21 @@ var AgentVoice = class extends BaseResource {
255
290
  }
256
291
  /**
257
292
  * Get available speakers for the agent's voice provider
293
+ * @param runtimeContext - Optional runtime context to pass as query parameter
294
+ * @param runtimeContext - Optional runtime context to pass as query parameter
258
295
  * @returns Promise containing list of available speakers
259
296
  */
260
- getSpeakers() {
261
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
297
+ getSpeakers(runtimeContext) {
298
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
262
299
  }
263
300
  /**
264
301
  * Get the listener configuration for the agent's voice provider
302
+ * @param runtimeContext - Optional runtime context to pass as query parameter
303
+ * @param runtimeContext - Optional runtime context to pass as query parameter
265
304
  * @returns Promise containing a check if the agent has listening capabilities
266
305
  */
267
- getListener() {
268
- return this.request(`/api/agents/${this.agentId}/voice/listener`);
306
+ getListener(runtimeContext) {
307
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
269
308
  }
270
309
  };
271
310
  var Agent = class extends BaseResource {
@@ -277,16 +316,17 @@ var Agent = class extends BaseResource {
277
316
  voice;
278
317
  /**
279
318
  * Retrieves details about the agent
319
+ * @param runtimeContext - Optional runtime context to pass as query parameter
280
320
  * @returns Promise containing agent details including model and instructions
281
321
  */
282
- details() {
283
- return this.request(`/api/agents/${this.agentId}`);
322
+ details(runtimeContext) {
323
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
284
324
  }
285
- async generate(params) {
286
- console.warn(
287
- "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th. Please use generateLegacy if you don't want to upgrade just yet."
288
- );
289
- return this.generateLegacy(params);
325
+ enhanceInstructions(instructions, comment) {
326
+ return this.request(`/api/agents/${this.agentId}/instructions/enhance`, {
327
+ method: "POST",
328
+ body: { instructions, comment }
329
+ });
290
330
  }
291
331
  async generateLegacy(params) {
292
332
  const processedParams = {
@@ -319,7 +359,9 @@ var Agent = class extends BaseResource {
319
359
  resourceId,
320
360
  threadId,
321
361
  runtimeContext,
322
- tracingContext: { currentSpan: void 0 }
362
+ tracingContext: { currentSpan: void 0 },
363
+ suspend: async () => {
364
+ }
323
365
  },
324
366
  {
325
367
  messages: response.messages,
@@ -327,10 +369,6 @@ var Agent = class extends BaseResource {
327
369
  }
328
370
  );
329
371
  const updatedMessages = [
330
- {
331
- role: "user",
332
- content: params.messages
333
- },
334
372
  ...response.response.messages,
335
373
  {
336
374
  role: "tool",
@@ -353,16 +391,28 @@ var Agent = class extends BaseResource {
353
391
  }
354
392
  return response;
355
393
  }
356
- async generateVNext(params) {
394
+ async generate(messagesOrParams, options) {
395
+ let params;
396
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
397
+ params = messagesOrParams;
398
+ } else {
399
+ params = {
400
+ messages: messagesOrParams,
401
+ ...options
402
+ };
403
+ }
357
404
  const processedParams = {
358
405
  ...params,
359
- output: params.output ? zodToJsonSchema(params.output) : void 0,
360
406
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
361
- clientTools: processClientTools(params.clientTools)
407
+ clientTools: processClientTools(params.clientTools),
408
+ structuredOutput: params.structuredOutput ? {
409
+ ...params.structuredOutput,
410
+ schema: zodToJsonSchema(params.structuredOutput.schema)
411
+ } : void 0
362
412
  };
363
413
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
364
414
  const response = await this.request(
365
- `/api/agents/${this.agentId}/generate/vnext`,
415
+ `/api/agents/${this.agentId}/generate`,
366
416
  {
367
417
  method: "POST",
368
418
  body: processedParams
@@ -376,7 +426,7 @@ var Agent = class extends BaseResource {
376
426
  resourceId,
377
427
  threadId,
378
428
  runtimeContext,
379
- respondFn: this.generateVNext.bind(this)
429
+ respondFn: this.generate.bind(this)
380
430
  });
381
431
  }
382
432
  return response;
@@ -643,17 +693,6 @@ var Agent = class extends BaseResource {
643
693
  });
644
694
  onFinish?.({ message, finishReason, usage });
645
695
  }
646
- /**
647
- * Streams a response from the agent
648
- * @param params - Stream parameters including prompt
649
- * @returns Promise containing the enhanced Response object with processDataStream method
650
- */
651
- async stream(params) {
652
- console.warn(
653
- "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th. Please use streamLegacy if you don't want to upgrade just yet."
654
- );
655
- return this.streamLegacy(params);
656
- }
657
696
  /**
658
697
  * Streams a response from the agent
659
698
  * @param params - Stream parameters including prompt
@@ -668,7 +707,7 @@ var Agent = class extends BaseResource {
668
707
  clientTools: processClientTools(params.clientTools)
669
708
  };
670
709
  const { readable, writable } = new TransformStream();
671
- const response = await this.processStreamResponse(processedParams, writable);
710
+ const response = await this.processStreamResponseLegacy(processedParams, writable);
672
711
  const streamResponse = new Response(readable, {
673
712
  status: response.status,
674
713
  statusText: response.statusText,
@@ -755,6 +794,14 @@ var Agent = class extends BaseResource {
755
794
  // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
756
795
  onChunk: async (chunk) => {
757
796
  switch (chunk.type) {
797
+ case "tripwire": {
798
+ message.parts.push({
799
+ type: "text",
800
+ text: chunk.payload.tripwireReason
801
+ });
802
+ execUpdate();
803
+ break;
804
+ }
758
805
  case "step-start": {
759
806
  if (!replaceLastMessage) {
760
807
  message.id = chunk.payload.messageId;
@@ -863,7 +910,7 @@ var Agent = class extends BaseResource {
863
910
  step,
864
911
  toolCallId: chunk.payload.toolCallId,
865
912
  toolName: chunk.payload.toolName,
866
- args: void 0
913
+ args: chunk.payload.args
867
914
  };
868
915
  message.toolInvocations.push(invocation);
869
916
  updateToolInvocationPart(chunk.payload.toolCallId, invocation);
@@ -908,7 +955,10 @@ var Agent = class extends BaseResource {
908
955
  break;
909
956
  }
910
957
  case "error": {
911
- throw new Error(chunk.payload.error);
958
+ throw getErrorFromUnknown(chunk.payload.error, {
959
+ fallbackMessage: "Unknown error in stream",
960
+ supportSerialization: false
961
+ });
912
962
  }
913
963
  case "data": {
914
964
  data.push(...chunk.payload.data);
@@ -917,14 +967,14 @@ var Agent = class extends BaseResource {
917
967
  }
918
968
  case "step-finish": {
919
969
  step += 1;
920
- currentTextPart = chunk.payload.isContinued ? currentTextPart : void 0;
970
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
921
971
  currentReasoningPart = void 0;
922
972
  currentReasoningTextDetail = void 0;
923
973
  execUpdate();
924
974
  break;
925
975
  }
926
976
  case "finish": {
927
- finishReason = chunk.payload.finishReason;
977
+ finishReason = chunk.payload.stepResult.reason;
928
978
  if (chunk.payload.usage != null) {
929
979
  usage = chunk.payload.usage;
930
980
  }
@@ -935,8 +985,8 @@ var Agent = class extends BaseResource {
935
985
  });
936
986
  onFinish?.({ message, finishReason, usage });
937
987
  }
938
- async processStreamResponse_vNext(processedParams, writable) {
939
- const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
988
+ async processStreamResponse(processedParams, writable, route = "stream") {
989
+ const response = await this.request(`/api/agents/${this.agentId}/${route}`, {
940
990
  method: "POST",
941
991
  body: processedParams,
942
992
  stream: true
@@ -948,9 +998,27 @@ var Agent = class extends BaseResource {
948
998
  let toolCalls = [];
949
999
  let messages = [];
950
1000
  const [streamForWritable, streamForProcessing] = response.body.tee();
951
- streamForWritable.pipeTo(writable, {
952
- preventClose: true
953
- }).catch((error) => {
1001
+ streamForWritable.pipeTo(
1002
+ new WritableStream({
1003
+ async write(chunk) {
1004
+ let writer;
1005
+ try {
1006
+ writer = writable.getWriter();
1007
+ const text = new TextDecoder().decode(chunk);
1008
+ const lines = text.split("\n\n");
1009
+ const readableLines = lines.filter((line) => line !== "[DONE]").join("\n\n");
1010
+ await writer.write(new TextEncoder().encode(readableLines));
1011
+ } catch {
1012
+ await writer?.write(chunk);
1013
+ } finally {
1014
+ writer?.releaseLock();
1015
+ }
1016
+ }
1017
+ }),
1018
+ {
1019
+ preventClose: true
1020
+ }
1021
+ ).catch((error) => {
954
1022
  console.error("Error piping to writable stream:", error);
955
1023
  });
956
1024
  this.processChatResponse_vNext({
@@ -969,9 +1037,11 @@ var Agent = class extends BaseResource {
969
1037
  if (toolCall) {
970
1038
  toolCalls.push(toolCall);
971
1039
  }
1040
+ let shouldExecuteClientTool = false;
972
1041
  for (const toolCall2 of toolCalls) {
973
1042
  const clientTool = processedParams.clientTools?.[toolCall2.toolName];
974
1043
  if (clientTool && clientTool.execute) {
1044
+ shouldExecuteClientTool = true;
975
1045
  const result = await clientTool.execute(
976
1046
  {
977
1047
  context: toolCall2?.args,
@@ -980,14 +1050,17 @@ var Agent = class extends BaseResource {
980
1050
  threadId: processedParams.threadId,
981
1051
  runtimeContext: processedParams.runtimeContext,
982
1052
  // TODO: Pass proper tracing context when client-js supports tracing
983
- tracingContext: { currentSpan: void 0 }
1053
+ tracingContext: { currentSpan: void 0 },
1054
+ suspend: async () => {
1055
+ }
984
1056
  },
985
1057
  {
986
1058
  messages: response.messages,
987
1059
  toolCallId: toolCall2?.toolCallId
988
1060
  }
989
1061
  );
990
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1062
+ const lastMessageRaw = messages[messages.length - 1];
1063
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
991
1064
  const toolInvocationPart = lastMessage?.parts?.find(
992
1065
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
993
1066
  );
@@ -1005,25 +1078,11 @@ var Agent = class extends BaseResource {
1005
1078
  toolInvocation.state = "result";
1006
1079
  toolInvocation.result = result;
1007
1080
  }
1008
- const writer = writable.getWriter();
1009
- try {
1010
- await writer.write(
1011
- new TextEncoder().encode(
1012
- "a:" + JSON.stringify({
1013
- toolCallId: toolCall2.toolCallId,
1014
- result
1015
- }) + "\n"
1016
- )
1017
- );
1018
- } finally {
1019
- writer.releaseLock();
1020
- }
1021
- const originalMessages = processedParams.messages;
1022
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1023
- this.processStreamResponse_vNext(
1081
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1082
+ this.processStreamResponse(
1024
1083
  {
1025
1084
  ...processedParams,
1026
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1085
+ messages: updatedMessages
1027
1086
  },
1028
1087
  writable
1029
1088
  ).catch((error) => {
@@ -1031,6 +1090,11 @@ var Agent = class extends BaseResource {
1031
1090
  });
1032
1091
  }
1033
1092
  }
1093
+ if (!shouldExecuteClientTool) {
1094
+ setTimeout(() => {
1095
+ writable.close();
1096
+ }, 0);
1097
+ }
1034
1098
  } else {
1035
1099
  setTimeout(() => {
1036
1100
  writable.close();
@@ -1046,15 +1110,87 @@ var Agent = class extends BaseResource {
1046
1110
  }
1047
1111
  return response;
1048
1112
  }
1049
- async streamVNext(params) {
1113
+ async network(params) {
1114
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1115
+ method: "POST",
1116
+ body: params,
1117
+ stream: true
1118
+ });
1119
+ if (!response.body) {
1120
+ throw new Error("No response body");
1121
+ }
1122
+ const streamResponse = new Response(response.body, {
1123
+ status: response.status,
1124
+ statusText: response.statusText,
1125
+ headers: response.headers
1126
+ });
1127
+ streamResponse.processDataStream = async ({
1128
+ onChunk
1129
+ }) => {
1130
+ await processMastraNetworkStream({
1131
+ stream: streamResponse.body,
1132
+ onChunk
1133
+ });
1134
+ };
1135
+ return streamResponse;
1136
+ }
1137
+ async stream(messagesOrParams, options) {
1138
+ let params;
1139
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1140
+ params = messagesOrParams;
1141
+ } else {
1142
+ params = {
1143
+ messages: messagesOrParams,
1144
+ ...options
1145
+ };
1146
+ }
1050
1147
  const processedParams = {
1051
1148
  ...params,
1052
- output: params.output ? zodToJsonSchema(params.output) : void 0,
1053
1149
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1054
- clientTools: processClientTools(params.clientTools)
1150
+ clientTools: processClientTools(params.clientTools),
1151
+ structuredOutput: params.structuredOutput ? {
1152
+ ...params.structuredOutput,
1153
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1154
+ } : void 0
1155
+ };
1156
+ const { readable, writable } = new TransformStream();
1157
+ const response = await this.processStreamResponse(processedParams, writable);
1158
+ const streamResponse = new Response(readable, {
1159
+ status: response.status,
1160
+ statusText: response.statusText,
1161
+ headers: response.headers
1162
+ });
1163
+ streamResponse.processDataStream = async ({
1164
+ onChunk
1165
+ }) => {
1166
+ await processMastraStream({
1167
+ stream: streamResponse.body,
1168
+ onChunk
1169
+ });
1170
+ };
1171
+ return streamResponse;
1172
+ }
1173
+ async approveToolCall(params) {
1174
+ const { readable, writable } = new TransformStream();
1175
+ const response = await this.processStreamResponse(params, writable, "approve-tool-call");
1176
+ const streamResponse = new Response(readable, {
1177
+ status: response.status,
1178
+ statusText: response.statusText,
1179
+ headers: response.headers
1180
+ });
1181
+ streamResponse.processDataStream = async ({
1182
+ onChunk
1183
+ }) => {
1184
+ await processMastraStream({
1185
+ stream: streamResponse.body,
1186
+ onChunk
1187
+ });
1055
1188
  };
1189
+ return streamResponse;
1190
+ }
1191
+ async declineToolCall(params) {
1056
1192
  const { readable, writable } = new TransformStream();
1057
- const response = await this.processStreamResponse_vNext(processedParams, writable);
1193
+ const response = await this.processStreamResponse(params, writable, "decline-tool-call");
1058
1194
  const streamResponse = new Response(readable, {
1059
1195
  status: response.status,
1060
1196
  statusText: response.statusText,
@@ -1073,7 +1209,7 @@ var Agent = class extends BaseResource {
1073
1209
  /**
1074
1210
  * Processes the stream response and handles tool calls
1075
1211
  */
1076
- async processStreamResponse(processedParams, writable) {
1212
+ async processStreamResponseLegacy(processedParams, writable) {
1077
1213
  const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1078
1214
  method: "POST",
1079
1215
  body: processedParams,
@@ -1118,7 +1254,9 @@ var Agent = class extends BaseResource {
1118
1254
  threadId: processedParams.threadId,
1119
1255
  runtimeContext: processedParams.runtimeContext,
1120
1256
  // TODO: Pass proper tracing context when client-js supports tracing
1121
- tracingContext: { currentSpan: void 0 }
1257
+ tracingContext: { currentSpan: void 0 },
1258
+ suspend: async () => {
1259
+ }
1122
1260
  },
1123
1261
  {
1124
1262
  messages: response.messages,
@@ -1156,12 +1294,10 @@ var Agent = class extends BaseResource {
1156
1294
  } finally {
1157
1295
  writer.releaseLock();
1158
1296
  }
1159
- const originalMessages = processedParams.messages;
1160
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1161
- this.processStreamResponse(
1297
+ this.processStreamResponseLegacy(
1162
1298
  {
1163
1299
  ...processedParams,
1164
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1300
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1165
1301
  },
1166
1302
  writable
1167
1303
  ).catch((error) => {
@@ -1187,10 +1323,11 @@ var Agent = class extends BaseResource {
1187
1323
  /**
1188
1324
  * Gets details about a specific tool available to the agent
1189
1325
  * @param toolId - ID of the tool to retrieve
1326
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1190
1327
  * @returns Promise containing tool details
1191
1328
  */
1192
- getTool(toolId) {
1193
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1329
+ getTool(toolId, runtimeContext) {
1330
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
1194
1331
  }
1195
1332
  /**
1196
1333
  * Executes a tool for the agent
@@ -1201,7 +1338,7 @@ var Agent = class extends BaseResource {
1201
1338
  executeTool(toolId, params) {
1202
1339
  const body = {
1203
1340
  data: params.data,
1204
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1341
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1205
1342
  };
1206
1343
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1207
1344
  method: "POST",
@@ -1210,17 +1347,19 @@ var Agent = class extends BaseResource {
1210
1347
  }
1211
1348
  /**
1212
1349
  * Retrieves evaluation results for the agent
1350
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1213
1351
  * @returns Promise containing agent evaluations
1214
1352
  */
1215
- evals() {
1216
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1353
+ evals(runtimeContext) {
1354
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
1217
1355
  }
1218
1356
  /**
1219
1357
  * Retrieves live evaluation results for the agent
1358
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1220
1359
  * @returns Promise containing live agent evaluations
1221
1360
  */
1222
- liveEvals() {
1223
- return this.request(`/api/agents/${this.agentId}/evals/live`);
1361
+ liveEvals(runtimeContext) {
1362
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
1224
1363
  }
1225
1364
  /**
1226
1365
  * Updates the model for the agent
@@ -1233,61 +1372,33 @@ var Agent = class extends BaseResource {
1233
1372
  body: params
1234
1373
  });
1235
1374
  }
1236
- };
1237
- var Network = class extends BaseResource {
1238
- constructor(options, networkId) {
1239
- super(options);
1240
- this.networkId = networkId;
1241
- }
1242
- /**
1243
- * Retrieves details about the network
1244
- * @returns Promise containing network details
1245
- */
1246
- details() {
1247
- return this.request(`/api/networks/${this.networkId}`);
1248
- }
1249
1375
  /**
1250
- * Generates a response from the agent
1251
- * @param params - Generation parameters including prompt
1252
- * @returns Promise containing the generated response
1376
+ * Updates the model for the agent in the model list
1377
+ * @param params - Parameters for updating the model
1378
+ * @returns Promise containing the updated model
1253
1379
  */
1254
- generate(params) {
1255
- const processedParams = {
1256
- ...params,
1257
- output: zodToJsonSchema(params.output),
1258
- experimental_output: zodToJsonSchema(params.experimental_output)
1259
- };
1260
- return this.request(`/api/networks/${this.networkId}/generate`, {
1380
+ updateModelInModelList({ modelConfigId, ...params }) {
1381
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
1261
1382
  method: "POST",
1262
- body: processedParams
1383
+ body: params
1263
1384
  });
1264
1385
  }
1265
1386
  /**
1266
- * Streams a response from the agent
1267
- * @param params - Stream parameters including prompt
1268
- * @returns Promise containing the enhanced Response object with processDataStream method
1387
+ * Reorders the models for the agent
1388
+ * @param params - Parameters for reordering the model list
1389
+ * @returns Promise containing the updated model list
1269
1390
  */
1270
- async stream(params) {
1271
- const processedParams = {
1272
- ...params,
1273
- output: zodToJsonSchema(params.output),
1274
- experimental_output: zodToJsonSchema(params.experimental_output)
1275
- };
1276
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1391
+ reorderModelList(params) {
1392
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
1277
1393
  method: "POST",
1278
- body: processedParams,
1279
- stream: true
1394
+ body: params
1280
1395
  });
1281
- if (!response.body) {
1282
- throw new Error("No response body");
1283
- }
1284
- response.processDataStream = async (options = {}) => {
1285
- await processDataStream({
1286
- stream: response.body,
1287
- ...options
1288
- });
1289
- };
1290
- return response;
1396
+ }
1397
+ async generateVNext(_messagesOrParams, _options) {
1398
+ throw new Error("generateVNext has been renamed to generate. Please use generate instead.");
1399
+ }
1400
+ async streamVNext(_messagesOrParams, _options) {
1401
+ throw new Error("streamVNext has been renamed to stream. Please use stream instead.");
1291
1402
  }
1292
1403
  };
1293
1404
 
@@ -1378,10 +1489,13 @@ var Vector = class extends BaseResource {
1378
1489
  /**
1379
1490
  * Retrieves details about a specific vector index
1380
1491
  * @param indexName - Name of the index to get details for
1492
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1381
1493
  * @returns Promise containing vector index details
1382
1494
  */
1383
- details(indexName) {
1384
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1495
+ details(indexName, runtimeContext) {
1496
+ return this.request(
1497
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1498
+ );
1385
1499
  }
1386
1500
  /**
1387
1501
  * Deletes a vector index
@@ -1395,10 +1509,11 @@ var Vector = class extends BaseResource {
1395
1509
  }
1396
1510
  /**
1397
1511
  * Retrieves a list of all available indexes
1512
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1398
1513
  * @returns Promise containing array of index names
1399
1514
  */
1400
- getIndexes() {
1401
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1515
+ getIndexes(runtimeContext) {
1516
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
1402
1517
  }
1403
1518
  /**
1404
1519
  * Creates a new vector index
@@ -1435,26 +1550,109 @@ var Vector = class extends BaseResource {
1435
1550
  }
1436
1551
  };
1437
1552
 
1438
- // src/resources/legacy-workflow.ts
1553
+ // src/resources/tool.ts
1554
+ var Tool = class extends BaseResource {
1555
+ constructor(options, toolId) {
1556
+ super(options);
1557
+ this.toolId = toolId;
1558
+ }
1559
+ /**
1560
+ * Retrieves details about the tool
1561
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1562
+ * @returns Promise containing tool details including description and schemas
1563
+ */
1564
+ details(runtimeContext) {
1565
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1566
+ }
1567
+ /**
1568
+ * Executes the tool with the provided parameters
1569
+ * @param params - Parameters required for tool execution
1570
+ * @returns Promise containing the tool execution results
1571
+ */
1572
+ execute(params) {
1573
+ const url = new URLSearchParams();
1574
+ if (params.runId) {
1575
+ url.set("runId", params.runId);
1576
+ }
1577
+ const body = {
1578
+ data: params.data,
1579
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1580
+ };
1581
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1582
+ method: "POST",
1583
+ body
1584
+ });
1585
+ }
1586
+ };
1587
+
1588
+ // src/resources/workflow.ts
1439
1589
  var RECORD_SEPARATOR = "";
1440
- var LegacyWorkflow = class extends BaseResource {
1590
+ var Workflow = class extends BaseResource {
1441
1591
  constructor(options, workflowId) {
1442
1592
  super(options);
1443
1593
  this.workflowId = workflowId;
1444
1594
  }
1445
1595
  /**
1446
- * Retrieves details about the legacy workflow
1447
- * @returns Promise containing legacy workflow details including steps and graphs
1596
+ * Creates an async generator that processes a readable stream and yields workflow records
1597
+ * separated by the Record Separator character (\x1E)
1598
+ *
1599
+ * @param stream - The readable stream to process
1600
+ * @returns An async generator that yields parsed records
1601
+ */
1602
+ async *streamProcessor(stream) {
1603
+ const reader = stream.getReader();
1604
+ let doneReading = false;
1605
+ let buffer = "";
1606
+ try {
1607
+ while (!doneReading) {
1608
+ const { done, value } = await reader.read();
1609
+ doneReading = done;
1610
+ if (done && !value) continue;
1611
+ try {
1612
+ const decoded = value ? new TextDecoder().decode(value) : "";
1613
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1614
+ buffer = chunks.pop() || "";
1615
+ for (const chunk of chunks) {
1616
+ if (chunk) {
1617
+ if (typeof chunk === "string") {
1618
+ try {
1619
+ const parsedChunk = JSON.parse(chunk);
1620
+ yield parsedChunk;
1621
+ } catch {
1622
+ }
1623
+ }
1624
+ }
1625
+ }
1626
+ } catch {
1627
+ }
1628
+ }
1629
+ if (buffer) {
1630
+ try {
1631
+ yield JSON.parse(buffer);
1632
+ } catch {
1633
+ }
1634
+ }
1635
+ } finally {
1636
+ reader.cancel().catch(() => {
1637
+ });
1638
+ }
1639
+ }
1640
+ /**
1641
+ * Retrieves details about the workflow
1642
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1643
+ * @returns Promise containing workflow details including steps and graphs
1448
1644
  */
1449
- details() {
1450
- return this.request(`/api/workflows/legacy/${this.workflowId}`);
1645
+ details(runtimeContext) {
1646
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1451
1647
  }
1452
1648
  /**
1453
- * Retrieves all runs for a legacy workflow
1649
+ * Retrieves all runs for a workflow
1454
1650
  * @param params - Parameters for filtering runs
1455
- * @returns Promise containing legacy workflow runs array
1651
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1652
+ * @returns Promise containing workflow runs array
1456
1653
  */
1457
- runs(params) {
1654
+ runs(params, runtimeContext) {
1655
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1458
1656
  const searchParams = new URLSearchParams();
1459
1657
  if (params?.fromDate) {
1460
1658
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1462,296 +1660,43 @@ var LegacyWorkflow = class extends BaseResource {
1462
1660
  if (params?.toDate) {
1463
1661
  searchParams.set("toDate", params.toDate.toISOString());
1464
1662
  }
1465
- if (params?.limit) {
1663
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1466
1664
  searchParams.set("limit", String(params.limit));
1467
1665
  }
1468
- if (params?.offset) {
1666
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1469
1667
  searchParams.set("offset", String(params.offset));
1470
1668
  }
1471
1669
  if (params?.resourceId) {
1472
1670
  searchParams.set("resourceId", params.resourceId);
1473
1671
  }
1672
+ if (runtimeContextParam) {
1673
+ searchParams.set("runtimeContext", runtimeContextParam);
1674
+ }
1474
1675
  if (searchParams.size) {
1475
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1676
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1476
1677
  } else {
1477
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1478
- }
1479
- }
1480
- /**
1481
- * Creates a new legacy workflow run
1482
- * @returns Promise containing the generated run ID
1483
- */
1484
- createRun(params) {
1485
- const searchParams = new URLSearchParams();
1486
- if (!!params?.runId) {
1487
- searchParams.set("runId", params.runId);
1488
- }
1489
- return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1490
- method: "POST"
1491
- });
1492
- }
1493
- /**
1494
- * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1495
- * @param params - Object containing the runId and triggerData
1496
- * @returns Promise containing success message
1497
- */
1498
- start(params) {
1499
- return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1500
- method: "POST",
1501
- body: params?.triggerData
1502
- });
1503
- }
1504
- /**
1505
- * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
1506
- * @param stepId - ID of the step to resume
1507
- * @param runId - ID of the legacy workflow run
1508
- * @param context - Context to resume the legacy workflow with
1509
- * @returns Promise containing the legacy workflow resume results
1510
- */
1511
- resume({
1512
- stepId,
1513
- runId,
1514
- context
1515
- }) {
1516
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
1517
- method: "POST",
1518
- body: {
1519
- stepId,
1520
- context
1521
- }
1522
- });
1523
- }
1524
- /**
1525
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1526
- * @param params - Object containing the optional runId and triggerData
1527
- * @returns Promise containing the workflow execution results
1528
- */
1529
- startAsync(params) {
1530
- const searchParams = new URLSearchParams();
1531
- if (!!params?.runId) {
1532
- searchParams.set("runId", params.runId);
1533
- }
1534
- return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1535
- method: "POST",
1536
- body: params?.triggerData
1537
- });
1538
- }
1539
- /**
1540
- * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1541
- * @param params - Object containing the runId, stepId, and context
1542
- * @returns Promise containing the workflow resume results
1543
- */
1544
- resumeAsync(params) {
1545
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1546
- method: "POST",
1547
- body: {
1548
- stepId: params.stepId,
1549
- context: params.context
1550
- }
1551
- });
1552
- }
1553
- /**
1554
- * Creates an async generator that processes a readable stream and yields 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
1559
- */
1560
- async *streamProcessor(stream) {
1561
- const reader = stream.getReader();
1562
- let doneReading = false;
1563
- let buffer = "";
1564
- try {
1565
- while (!doneReading) {
1566
- const { done, value } = await reader.read();
1567
- doneReading = done;
1568
- if (done && !value) continue;
1569
- try {
1570
- const decoded = value ? new TextDecoder().decode(value) : "";
1571
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1572
- buffer = chunks.pop() || "";
1573
- for (const chunk of chunks) {
1574
- if (chunk) {
1575
- if (typeof chunk === "string") {
1576
- try {
1577
- const parsedChunk = JSON.parse(chunk);
1578
- yield parsedChunk;
1579
- } catch {
1580
- }
1581
- }
1582
- }
1583
- }
1584
- } catch {
1585
- }
1586
- }
1587
- if (buffer) {
1588
- try {
1589
- yield JSON.parse(buffer);
1590
- } catch {
1591
- }
1592
- }
1593
- } finally {
1594
- reader.cancel().catch(() => {
1595
- });
1596
- }
1597
- }
1598
- /**
1599
- * Watches legacy workflow transitions in real-time
1600
- * @param runId - Optional run ID to filter the watch stream
1601
- * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1602
- */
1603
- async watch({ runId }, onRecord) {
1604
- const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1605
- stream: true
1606
- });
1607
- if (!response.ok) {
1608
- throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1609
- }
1610
- if (!response.body) {
1611
- throw new Error("Response body is null");
1612
- }
1613
- for await (const record of this.streamProcessor(response.body)) {
1614
- onRecord(record);
1615
- }
1616
- }
1617
- };
1618
-
1619
- // src/resources/tool.ts
1620
- var Tool = class extends BaseResource {
1621
- constructor(options, toolId) {
1622
- super(options);
1623
- this.toolId = toolId;
1624
- }
1625
- /**
1626
- * Retrieves details about the tool
1627
- * @returns Promise containing tool details including description and schemas
1628
- */
1629
- details() {
1630
- return this.request(`/api/tools/${this.toolId}`);
1631
- }
1632
- /**
1633
- * Executes the tool with the provided parameters
1634
- * @param params - Parameters required for tool execution
1635
- * @returns Promise containing the tool execution results
1636
- */
1637
- execute(params) {
1638
- const url = new URLSearchParams();
1639
- if (params.runId) {
1640
- url.set("runId", params.runId);
1641
- }
1642
- const body = {
1643
- data: params.data,
1644
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1645
- };
1646
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1647
- method: "POST",
1648
- body
1649
- });
1650
- }
1651
- };
1652
-
1653
- // src/resources/workflow.ts
1654
- var RECORD_SEPARATOR2 = "";
1655
- var Workflow = class extends BaseResource {
1656
- constructor(options, workflowId) {
1657
- super(options);
1658
- this.workflowId = workflowId;
1659
- }
1660
- /**
1661
- * Creates an async generator that processes a readable stream and yields workflow records
1662
- * separated by the Record Separator character (\x1E)
1663
- *
1664
- * @param stream - The readable stream to process
1665
- * @returns An async generator that yields parsed records
1666
- */
1667
- async *streamProcessor(stream) {
1668
- const reader = stream.getReader();
1669
- let doneReading = false;
1670
- let buffer = "";
1671
- try {
1672
- while (!doneReading) {
1673
- const { done, value } = await reader.read();
1674
- doneReading = done;
1675
- if (done && !value) continue;
1676
- try {
1677
- const decoded = value ? new TextDecoder().decode(value) : "";
1678
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1679
- buffer = chunks.pop() || "";
1680
- for (const chunk of chunks) {
1681
- if (chunk) {
1682
- if (typeof chunk === "string") {
1683
- try {
1684
- const parsedChunk = JSON.parse(chunk);
1685
- yield parsedChunk;
1686
- } catch {
1687
- }
1688
- }
1689
- }
1690
- }
1691
- } catch {
1692
- }
1693
- }
1694
- if (buffer) {
1695
- try {
1696
- yield JSON.parse(buffer);
1697
- } catch {
1698
- }
1699
- }
1700
- } finally {
1701
- reader.cancel().catch(() => {
1702
- });
1703
- }
1704
- }
1705
- /**
1706
- * Retrieves details about the workflow
1707
- * @returns Promise containing workflow details including steps and graphs
1708
- */
1709
- details() {
1710
- return this.request(`/api/workflows/${this.workflowId}`);
1711
- }
1712
- /**
1713
- * Retrieves all runs for a workflow
1714
- * @param params - Parameters for filtering runs
1715
- * @returns Promise containing workflow runs array
1716
- */
1717
- runs(params) {
1718
- const searchParams = new URLSearchParams();
1719
- if (params?.fromDate) {
1720
- searchParams.set("fromDate", params.fromDate.toISOString());
1721
- }
1722
- if (params?.toDate) {
1723
- searchParams.set("toDate", params.toDate.toISOString());
1724
- }
1725
- if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1726
- searchParams.set("limit", String(params.limit));
1727
- }
1728
- if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1729
- searchParams.set("offset", String(params.offset));
1730
- }
1731
- if (params?.resourceId) {
1732
- searchParams.set("resourceId", params.resourceId);
1733
- }
1734
- if (searchParams.size) {
1735
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1736
- } else {
1737
- return this.request(`/api/workflows/${this.workflowId}/runs`);
1678
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1738
1679
  }
1739
1680
  }
1740
1681
  /**
1741
1682
  * Retrieves a specific workflow run by its ID
1742
1683
  * @param runId - The ID of the workflow run to retrieve
1684
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1743
1685
  * @returns Promise containing the workflow run details
1744
1686
  */
1745
- runById(runId) {
1746
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1687
+ runById(runId, runtimeContext) {
1688
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1747
1689
  }
1748
1690
  /**
1749
1691
  * Retrieves the execution result for a specific workflow run by its ID
1750
1692
  * @param runId - The ID of the workflow run to retrieve the execution result for
1693
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1751
1694
  * @returns Promise containing the workflow run execution result
1752
1695
  */
1753
- runExecutionResult(runId) {
1754
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1696
+ runExecutionResult(runId, runtimeContext) {
1697
+ return this.request(
1698
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1699
+ );
1755
1700
  }
1756
1701
  /**
1757
1702
  * Cancels a specific workflow run by its ID
@@ -1774,27 +1719,83 @@ var Workflow = class extends BaseResource {
1774
1719
  body: { event: params.event, data: params.data }
1775
1720
  });
1776
1721
  }
1722
+ /**
1723
+ * @deprecated Use createRunAsync() instead.
1724
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1725
+ */
1726
+ async createRun(_params) {
1727
+ throw new Error(
1728
+ "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."
1729
+ );
1730
+ }
1777
1731
  /**
1778
1732
  * Creates a new workflow run
1779
1733
  * @param params - Optional object containing the optional runId
1780
- * @returns Promise containing the runId of the created run
1734
+ * @returns Promise containing the runId of the created run with methods to control execution
1781
1735
  */
1782
- createRun(params) {
1736
+ async createRunAsync(params) {
1783
1737
  const searchParams = new URLSearchParams();
1784
1738
  if (!!params?.runId) {
1785
1739
  searchParams.set("runId", params.runId);
1786
1740
  }
1787
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1788
- method: "POST"
1789
- });
1790
- }
1791
- /**
1792
- * Creates a new workflow run (alias for createRun)
1793
- * @param params - Optional object containing the optional runId
1794
- * @returns Promise containing the runId of the created run
1795
- */
1796
- createRunAsync(params) {
1797
- return this.createRun(params);
1741
+ const res = await this.request(
1742
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1743
+ {
1744
+ method: "POST"
1745
+ }
1746
+ );
1747
+ const runId = res.runId;
1748
+ return {
1749
+ runId,
1750
+ start: async (p) => {
1751
+ return this.start({
1752
+ runId,
1753
+ inputData: p.inputData,
1754
+ runtimeContext: p.runtimeContext,
1755
+ tracingOptions: p.tracingOptions
1756
+ });
1757
+ },
1758
+ startAsync: async (p) => {
1759
+ return this.startAsync({
1760
+ runId,
1761
+ inputData: p.inputData,
1762
+ runtimeContext: p.runtimeContext,
1763
+ tracingOptions: p.tracingOptions
1764
+ });
1765
+ },
1766
+ watch: async (onRecord) => {
1767
+ return this.watch({ runId }, onRecord);
1768
+ },
1769
+ stream: async (p) => {
1770
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1771
+ },
1772
+ resume: async (p) => {
1773
+ return this.resume({
1774
+ runId,
1775
+ step: p.step,
1776
+ resumeData: p.resumeData,
1777
+ runtimeContext: p.runtimeContext,
1778
+ tracingOptions: p.tracingOptions
1779
+ });
1780
+ },
1781
+ resumeAsync: async (p) => {
1782
+ return this.resumeAsync({
1783
+ runId,
1784
+ step: p.step,
1785
+ resumeData: p.resumeData,
1786
+ runtimeContext: p.runtimeContext,
1787
+ tracingOptions: p.tracingOptions
1788
+ });
1789
+ },
1790
+ resumeStreamVNext: async (p) => {
1791
+ return this.resumeStreamVNext({
1792
+ runId,
1793
+ step: p.step,
1794
+ resumeData: p.resumeData,
1795
+ runtimeContext: p.runtimeContext
1796
+ });
1797
+ }
1798
+ };
1798
1799
  }
1799
1800
  /**
1800
1801
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -1805,7 +1806,7 @@ var Workflow = class extends BaseResource {
1805
1806
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1806
1807
  return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1807
1808
  method: "POST",
1808
- body: { inputData: params?.inputData, runtimeContext }
1809
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1809
1810
  });
1810
1811
  }
1811
1812
  /**
@@ -1817,16 +1818,17 @@ var Workflow = class extends BaseResource {
1817
1818
  step,
1818
1819
  runId,
1819
1820
  resumeData,
1821
+ tracingOptions,
1820
1822
  ...rest
1821
1823
  }) {
1822
1824
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1823
1825
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1824
1826
  method: "POST",
1825
- stream: true,
1826
1827
  body: {
1827
1828
  step,
1828
1829
  resumeData,
1829
- runtimeContext
1830
+ runtimeContext,
1831
+ tracingOptions
1830
1832
  }
1831
1833
  });
1832
1834
  }
@@ -1843,7 +1845,7 @@ var Workflow = class extends BaseResource {
1843
1845
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1844
1846
  return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1845
1847
  method: "POST",
1846
- body: { inputData: params.inputData, runtimeContext }
1848
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1847
1849
  });
1848
1850
  }
1849
1851
  /**
@@ -1858,15 +1860,165 @@ var Workflow = class extends BaseResource {
1858
1860
  }
1859
1861
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1860
1862
  const response = await this.request(
1861
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1863
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1864
+ {
1865
+ method: "POST",
1866
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions },
1867
+ stream: true
1868
+ }
1869
+ );
1870
+ if (!response.ok) {
1871
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1872
+ }
1873
+ if (!response.body) {
1874
+ throw new Error("Response body is null");
1875
+ }
1876
+ let failedChunk = void 0;
1877
+ const transformStream = new TransformStream({
1878
+ start() {
1879
+ },
1880
+ async transform(chunk, controller) {
1881
+ try {
1882
+ const decoded = new TextDecoder().decode(chunk);
1883
+ const chunks = decoded.split(RECORD_SEPARATOR);
1884
+ for (const chunk2 of chunks) {
1885
+ if (chunk2) {
1886
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1887
+ try {
1888
+ const parsedChunk = JSON.parse(newChunk);
1889
+ controller.enqueue(parsedChunk);
1890
+ failedChunk = void 0;
1891
+ } catch {
1892
+ failedChunk = newChunk;
1893
+ }
1894
+ }
1895
+ }
1896
+ } catch {
1897
+ }
1898
+ }
1899
+ });
1900
+ return response.body.pipeThrough(transformStream);
1901
+ }
1902
+ /**
1903
+ * Observes workflow stream for a workflow run
1904
+ * @param params - Object containing the runId
1905
+ * @returns Promise containing the workflow execution results
1906
+ */
1907
+ async observeStream(params) {
1908
+ const searchParams = new URLSearchParams();
1909
+ searchParams.set("runId", params.runId);
1910
+ const response = await this.request(
1911
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1912
+ {
1913
+ method: "POST",
1914
+ stream: true
1915
+ }
1916
+ );
1917
+ if (!response.ok) {
1918
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1919
+ }
1920
+ if (!response.body) {
1921
+ throw new Error("Response body is null");
1922
+ }
1923
+ let failedChunk = void 0;
1924
+ const transformStream = new TransformStream({
1925
+ start() {
1926
+ },
1927
+ async transform(chunk, controller) {
1928
+ try {
1929
+ const decoded = new TextDecoder().decode(chunk);
1930
+ const chunks = decoded.split(RECORD_SEPARATOR);
1931
+ for (const chunk2 of chunks) {
1932
+ if (chunk2) {
1933
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1934
+ try {
1935
+ const parsedChunk = JSON.parse(newChunk);
1936
+ controller.enqueue(parsedChunk);
1937
+ failedChunk = void 0;
1938
+ } catch {
1939
+ failedChunk = newChunk;
1940
+ }
1941
+ }
1942
+ }
1943
+ } catch {
1944
+ }
1945
+ }
1946
+ });
1947
+ return response.body.pipeThrough(transformStream);
1948
+ }
1949
+ /**
1950
+ * Starts a workflow run and returns a stream
1951
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1952
+ * @returns Promise containing the workflow execution results
1953
+ */
1954
+ async streamVNext(params) {
1955
+ const searchParams = new URLSearchParams();
1956
+ if (!!params?.runId) {
1957
+ searchParams.set("runId", params.runId);
1958
+ }
1959
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1960
+ const response = await this.request(
1961
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1962
+ {
1963
+ method: "POST",
1964
+ body: {
1965
+ inputData: params.inputData,
1966
+ runtimeContext,
1967
+ closeOnSuspend: params.closeOnSuspend,
1968
+ tracingOptions: params.tracingOptions
1969
+ },
1970
+ stream: true
1971
+ }
1972
+ );
1973
+ if (!response.ok) {
1974
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1975
+ }
1976
+ if (!response.body) {
1977
+ throw new Error("Response body is null");
1978
+ }
1979
+ let failedChunk = void 0;
1980
+ const transformStream = new TransformStream({
1981
+ start() {
1982
+ },
1983
+ async transform(chunk, controller) {
1984
+ try {
1985
+ const decoded = new TextDecoder().decode(chunk);
1986
+ const chunks = decoded.split(RECORD_SEPARATOR);
1987
+ for (const chunk2 of chunks) {
1988
+ if (chunk2) {
1989
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1990
+ try {
1991
+ const parsedChunk = JSON.parse(newChunk);
1992
+ controller.enqueue(parsedChunk);
1993
+ failedChunk = void 0;
1994
+ } catch {
1995
+ failedChunk = newChunk;
1996
+ }
1997
+ }
1998
+ }
1999
+ } catch {
2000
+ }
2001
+ }
2002
+ });
2003
+ return response.body.pipeThrough(transformStream);
2004
+ }
2005
+ /**
2006
+ * Observes workflow vNext stream for a workflow run
2007
+ * @param params - Object containing the runId
2008
+ * @returns Promise containing the workflow execution results
2009
+ */
2010
+ async observeStreamVNext(params) {
2011
+ const searchParams = new URLSearchParams();
2012
+ searchParams.set("runId", params.runId);
2013
+ const response = await this.request(
2014
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
1862
2015
  {
1863
2016
  method: "POST",
1864
- body: { inputData: params.inputData, runtimeContext },
1865
2017
  stream: true
1866
2018
  }
1867
2019
  );
1868
2020
  if (!response.ok) {
1869
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2021
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
1870
2022
  }
1871
2023
  if (!response.body) {
1872
2024
  throw new Error("Response body is null");
@@ -1878,7 +2030,7 @@ var Workflow = class extends BaseResource {
1878
2030
  async transform(chunk, controller) {
1879
2031
  try {
1880
2032
  const decoded = new TextDecoder().decode(chunk);
1881
- const chunks = decoded.split(RECORD_SEPARATOR2);
2033
+ const chunks = decoded.split(RECORD_SEPARATOR);
1882
2034
  for (const chunk2 of chunks) {
1883
2035
  if (chunk2) {
1884
2036
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -1909,9 +2061,64 @@ var Workflow = class extends BaseResource {
1909
2061
  body: {
1910
2062
  step: params.step,
1911
2063
  resumeData: params.resumeData,
1912
- runtimeContext
2064
+ runtimeContext,
2065
+ tracingOptions: params.tracingOptions
2066
+ }
2067
+ });
2068
+ }
2069
+ /**
2070
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2071
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2072
+ * @returns Promise containing the workflow resume results
2073
+ */
2074
+ async resumeStreamVNext(params) {
2075
+ const searchParams = new URLSearchParams();
2076
+ searchParams.set("runId", params.runId);
2077
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2078
+ const response = await this.request(
2079
+ `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
2080
+ {
2081
+ method: "POST",
2082
+ body: {
2083
+ step: params.step,
2084
+ resumeData: params.resumeData,
2085
+ runtimeContext,
2086
+ tracingOptions: params.tracingOptions
2087
+ },
2088
+ stream: true
2089
+ }
2090
+ );
2091
+ if (!response.ok) {
2092
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2093
+ }
2094
+ if (!response.body) {
2095
+ throw new Error("Response body is null");
2096
+ }
2097
+ let failedChunk = void 0;
2098
+ const transformStream = new TransformStream({
2099
+ start() {
2100
+ },
2101
+ async transform(chunk, controller) {
2102
+ try {
2103
+ const decoded = new TextDecoder().decode(chunk);
2104
+ const chunks = decoded.split(RECORD_SEPARATOR);
2105
+ for (const chunk2 of chunks) {
2106
+ if (chunk2) {
2107
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2108
+ try {
2109
+ const parsedChunk = JSON.parse(newChunk);
2110
+ controller.enqueue(parsedChunk);
2111
+ failedChunk = void 0;
2112
+ } catch {
2113
+ failedChunk = newChunk;
2114
+ }
2115
+ }
2116
+ }
2117
+ } catch {
2118
+ }
1913
2119
  }
1914
2120
  });
2121
+ return response.body.pipeThrough(transformStream);
1915
2122
  }
1916
2123
  /**
1917
2124
  * Watches workflow transitions in real-time
@@ -1949,7 +2156,7 @@ var Workflow = class extends BaseResource {
1949
2156
  async start(controller) {
1950
2157
  try {
1951
2158
  for await (const record of records) {
1952
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2159
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
1953
2160
  controller.enqueue(encoder.encode(json));
1954
2161
  }
1955
2162
  controller.close();
@@ -2047,10 +2254,11 @@ var MCPTool = class extends BaseResource {
2047
2254
  }
2048
2255
  /**
2049
2256
  * Retrieves details about this specific tool from the MCP server.
2257
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2050
2258
  * @returns Promise containing the tool's information (name, description, schema).
2051
2259
  */
2052
- details() {
2053
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2260
+ details(runtimeContext) {
2261
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2054
2262
  }
2055
2263
  /**
2056
2264
  * Executes this specific tool on the MCP server.
@@ -2071,7 +2279,7 @@ var MCPTool = class extends BaseResource {
2071
2279
  };
2072
2280
 
2073
2281
  // src/resources/agent-builder.ts
2074
- var RECORD_SEPARATOR3 = "";
2282
+ var RECORD_SEPARATOR2 = "";
2075
2283
  var AgentBuilder = class extends BaseResource {
2076
2284
  constructor(options, actionId) {
2077
2285
  super(options);
@@ -2106,11 +2314,20 @@ var AgentBuilder = class extends BaseResource {
2106
2314
  };
2107
2315
  }
2108
2316
  }
2317
+ /**
2318
+ * @deprecated Use createRunAsync() instead.
2319
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2320
+ */
2321
+ async createRun(_params) {
2322
+ throw new Error(
2323
+ "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."
2324
+ );
2325
+ }
2109
2326
  /**
2110
2327
  * Creates a new agent builder action run and returns the runId.
2111
2328
  * This calls `/api/agent-builder/:actionId/create-run`.
2112
2329
  */
2113
- async createRun(params) {
2330
+ async createRunAsync(params) {
2114
2331
  const searchParams = new URLSearchParams();
2115
2332
  if (!!params?.runId) {
2116
2333
  searchParams.set("runId", params.runId);
@@ -2120,14 +2337,6 @@ var AgentBuilder = class extends BaseResource {
2120
2337
  method: "POST"
2121
2338
  });
2122
2339
  }
2123
- /**
2124
- * Creates a new workflow run (alias for createRun)
2125
- * @param params - Optional object containing the optional runId
2126
- * @returns Promise containing the runId of the created run
2127
- */
2128
- createRunAsync(params) {
2129
- return this.createRun(params);
2130
- }
2131
2340
  /**
2132
2341
  * Starts agent builder action asynchronously and waits for completion.
2133
2342
  * This calls `/api/agent-builder/:actionId/start-async`.
@@ -2210,7 +2419,7 @@ var AgentBuilder = class extends BaseResource {
2210
2419
  if (done && !value) continue;
2211
2420
  try {
2212
2421
  const decoded = value ? new TextDecoder().decode(value) : "";
2213
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2422
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2214
2423
  buffer = chunks.pop() || "";
2215
2424
  for (const chunk of chunks) {
2216
2425
  if (chunk) {
@@ -2267,7 +2476,7 @@ var AgentBuilder = class extends BaseResource {
2267
2476
  async transform(chunk, controller) {
2268
2477
  try {
2269
2478
  const decoded = new TextDecoder().decode(chunk);
2270
- const chunks = decoded.split(RECORD_SEPARATOR3);
2479
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2271
2480
  for (const chunk2 of chunks) {
2272
2481
  if (chunk2) {
2273
2482
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2316,7 +2525,7 @@ var AgentBuilder = class extends BaseResource {
2316
2525
  async transform(chunk, controller) {
2317
2526
  try {
2318
2527
  const decoded = new TextDecoder().decode(chunk);
2319
- const chunks = decoded.split(RECORD_SEPARATOR3);
2528
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2320
2529
  for (const chunk2 of chunks) {
2321
2530
  if (chunk2) {
2322
2531
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2459,7 +2668,7 @@ var Observability = class extends BaseResource {
2459
2668
  getTraces(params) {
2460
2669
  const { pagination, filters } = params;
2461
2670
  const { page, perPage, dateRange } = pagination || {};
2462
- const { name, spanType } = filters || {};
2671
+ const { name, spanType, entityId, entityType } = filters || {};
2463
2672
  const searchParams = new URLSearchParams();
2464
2673
  if (page !== void 0) {
2465
2674
  searchParams.set("page", String(page));
@@ -2473,6 +2682,10 @@ var Observability = class extends BaseResource {
2473
2682
  if (spanType !== void 0) {
2474
2683
  searchParams.set("spanType", String(spanType));
2475
2684
  }
2685
+ if (entityId && entityType) {
2686
+ searchParams.set("entityId", entityId);
2687
+ searchParams.set("entityType", entityType);
2688
+ }
2476
2689
  if (dateRange) {
2477
2690
  const dateRangeStr = JSON.stringify({
2478
2691
  start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
@@ -2483,6 +2696,31 @@ var Observability = class extends BaseResource {
2483
2696
  const queryString = searchParams.toString();
2484
2697
  return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2485
2698
  }
2699
+ /**
2700
+ * Retrieves scores by trace ID and span ID
2701
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2702
+ * @returns Promise containing scores and pagination info
2703
+ */
2704
+ getScoresBySpan(params) {
2705
+ const { traceId, spanId, page, perPage } = params;
2706
+ const searchParams = new URLSearchParams();
2707
+ if (page !== void 0) {
2708
+ searchParams.set("page", String(page));
2709
+ }
2710
+ if (perPage !== void 0) {
2711
+ searchParams.set("perPage", String(perPage));
2712
+ }
2713
+ const queryString = searchParams.toString();
2714
+ return this.request(
2715
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2716
+ );
2717
+ }
2718
+ score(params) {
2719
+ return this.request(`/api/observability/traces/score`, {
2720
+ method: "POST",
2721
+ body: { ...params }
2722
+ });
2723
+ }
2486
2724
  };
2487
2725
 
2488
2726
  // src/resources/network-memory-thread.ts
@@ -2548,144 +2786,6 @@ var NetworkMemoryThread = class extends BaseResource {
2548
2786
  }
2549
2787
  };
2550
2788
 
2551
- // src/resources/vNextNetwork.ts
2552
- var RECORD_SEPARATOR4 = "";
2553
- var VNextNetwork = class extends BaseResource {
2554
- constructor(options, networkId) {
2555
- super(options);
2556
- this.networkId = networkId;
2557
- }
2558
- /**
2559
- * Retrieves details about the network
2560
- * @returns Promise containing vNext network details
2561
- */
2562
- details() {
2563
- return this.request(`/api/networks/v-next/${this.networkId}`);
2564
- }
2565
- /**
2566
- * Generates a response from the v-next network
2567
- * @param params - Generation parameters including message
2568
- * @returns Promise containing the generated response
2569
- */
2570
- generate(params) {
2571
- return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
2572
- method: "POST",
2573
- body: {
2574
- ...params,
2575
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2576
- }
2577
- });
2578
- }
2579
- /**
2580
- * Generates a response from the v-next network using multiple primitives
2581
- * @param params - Generation parameters including message
2582
- * @returns Promise containing the generated response
2583
- */
2584
- loop(params) {
2585
- return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
2586
- method: "POST",
2587
- body: {
2588
- ...params,
2589
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2590
- }
2591
- });
2592
- }
2593
- async *streamProcessor(stream) {
2594
- const reader = stream.getReader();
2595
- let doneReading = false;
2596
- let buffer = "";
2597
- try {
2598
- while (!doneReading) {
2599
- const { done, value } = await reader.read();
2600
- doneReading = done;
2601
- if (done && !value) continue;
2602
- try {
2603
- const decoded = value ? new TextDecoder().decode(value) : "";
2604
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
2605
- buffer = chunks.pop() || "";
2606
- for (const chunk of chunks) {
2607
- if (chunk) {
2608
- if (typeof chunk === "string") {
2609
- try {
2610
- const parsedChunk = JSON.parse(chunk);
2611
- yield parsedChunk;
2612
- } catch {
2613
- }
2614
- }
2615
- }
2616
- }
2617
- } catch {
2618
- }
2619
- }
2620
- if (buffer) {
2621
- try {
2622
- yield JSON.parse(buffer);
2623
- } catch {
2624
- }
2625
- }
2626
- } finally {
2627
- reader.cancel().catch(() => {
2628
- });
2629
- }
2630
- }
2631
- /**
2632
- * Streams a response from the v-next network
2633
- * @param params - Stream parameters including message
2634
- * @returns Promise containing the results
2635
- */
2636
- async stream(params, onRecord) {
2637
- const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
2638
- method: "POST",
2639
- body: {
2640
- ...params,
2641
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2642
- },
2643
- stream: true
2644
- });
2645
- if (!response.ok) {
2646
- throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2647
- }
2648
- if (!response.body) {
2649
- throw new Error("Response body is null");
2650
- }
2651
- for await (const record of this.streamProcessor(response.body)) {
2652
- if (typeof record === "string") {
2653
- onRecord(JSON.parse(record));
2654
- } else {
2655
- onRecord(record);
2656
- }
2657
- }
2658
- }
2659
- /**
2660
- * Streams a response from the v-next network loop
2661
- * @param params - Stream parameters including message
2662
- * @returns Promise containing the results
2663
- */
2664
- async loopStream(params, onRecord) {
2665
- const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
2666
- method: "POST",
2667
- body: {
2668
- ...params,
2669
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2670
- },
2671
- stream: true
2672
- });
2673
- if (!response.ok) {
2674
- throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2675
- }
2676
- if (!response.body) {
2677
- throw new Error("Response body is null");
2678
- }
2679
- for await (const record of this.streamProcessor(response.body)) {
2680
- if (typeof record === "string") {
2681
- onRecord(JSON.parse(record));
2682
- } else {
2683
- onRecord(record);
2684
- }
2685
- }
2686
- }
2687
- };
2688
-
2689
2789
  // src/client.ts
2690
2790
  var MastraClient = class extends BaseResource {
2691
2791
  observability;
@@ -2695,10 +2795,20 @@ var MastraClient = class extends BaseResource {
2695
2795
  }
2696
2796
  /**
2697
2797
  * Retrieves all available agents
2798
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2698
2799
  * @returns Promise containing map of agent IDs to agent details
2699
2800
  */
2700
- getAgents() {
2701
- return this.request("/api/agents");
2801
+ getAgents(runtimeContext) {
2802
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2803
+ const searchParams = new URLSearchParams();
2804
+ if (runtimeContextParam) {
2805
+ searchParams.set("runtimeContext", runtimeContextParam);
2806
+ }
2807
+ const queryString = searchParams.toString();
2808
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
2809
+ }
2810
+ getAgentsModelProviders() {
2811
+ return this.request(`/api/agents/providers`);
2702
2812
  }
2703
2813
  /**
2704
2814
  * Gets an agent instance by ID
@@ -2716,6 +2826,14 @@ var MastraClient = class extends BaseResource {
2716
2826
  getMemoryThreads(params) {
2717
2827
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
2718
2828
  }
2829
+ /**
2830
+ * Retrieves memory config for a resource
2831
+ * @param params - Parameters containing the resource ID
2832
+ * @returns Promise containing array of memory threads
2833
+ */
2834
+ getMemoryConfig(params) {
2835
+ return this.request(`/api/memory/config?agentId=${params.agentId}`);
2836
+ }
2719
2837
  /**
2720
2838
  * Creates a new memory thread
2721
2839
  * @param params - Parameters for creating the memory thread
@@ -2732,6 +2850,24 @@ var MastraClient = class extends BaseResource {
2732
2850
  getMemoryThread(threadId, agentId) {
2733
2851
  return new MemoryThread(this.options, threadId, agentId);
2734
2852
  }
2853
+ getThreadMessages(threadId, opts = {}) {
2854
+ let url = "";
2855
+ if (opts.agentId) {
2856
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}`;
2857
+ } else if (opts.networkId) {
2858
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}`;
2859
+ }
2860
+ return this.request(url);
2861
+ }
2862
+ deleteThread(threadId, opts = {}) {
2863
+ let url = "";
2864
+ if (opts.agentId) {
2865
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}`;
2866
+ } else if (opts.networkId) {
2867
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}`;
2868
+ }
2869
+ return this.request(url, { method: "DELETE" });
2870
+ }
2735
2871
  /**
2736
2872
  * Saves messages to memory
2737
2873
  * @param params - Parameters containing messages to save
@@ -2794,10 +2930,17 @@ var MastraClient = class extends BaseResource {
2794
2930
  }
2795
2931
  /**
2796
2932
  * Retrieves all available tools
2933
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2797
2934
  * @returns Promise containing map of tool IDs to tool details
2798
2935
  */
2799
- getTools() {
2800
- return this.request("/api/tools");
2936
+ getTools(runtimeContext) {
2937
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2938
+ const searchParams = new URLSearchParams();
2939
+ if (runtimeContextParam) {
2940
+ searchParams.set("runtimeContext", runtimeContextParam);
2941
+ }
2942
+ const queryString = searchParams.toString();
2943
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
2801
2944
  }
2802
2945
  /**
2803
2946
  * Gets a tool instance by ID
@@ -2807,27 +2950,19 @@ var MastraClient = class extends BaseResource {
2807
2950
  getTool(toolId) {
2808
2951
  return new Tool(this.options, toolId);
2809
2952
  }
2810
- /**
2811
- * Retrieves all available legacy workflows
2812
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2813
- */
2814
- getLegacyWorkflows() {
2815
- return this.request("/api/workflows/legacy");
2816
- }
2817
- /**
2818
- * Gets a legacy workflow instance by ID
2819
- * @param workflowId - ID of the legacy workflow to retrieve
2820
- * @returns Legacy Workflow instance
2821
- */
2822
- getLegacyWorkflow(workflowId) {
2823
- return new LegacyWorkflow(this.options, workflowId);
2824
- }
2825
2953
  /**
2826
2954
  * Retrieves all available workflows
2955
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2827
2956
  * @returns Promise containing map of workflow IDs to workflow details
2828
2957
  */
2829
- getWorkflows() {
2830
- return this.request("/api/workflows");
2958
+ getWorkflows(runtimeContext) {
2959
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2960
+ const searchParams = new URLSearchParams();
2961
+ if (runtimeContextParam) {
2962
+ searchParams.set("runtimeContext", runtimeContextParam);
2963
+ }
2964
+ const queryString = searchParams.toString();
2965
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
2831
2966
  }
2832
2967
  /**
2833
2968
  * Gets a workflow instance by ID
@@ -2953,78 +3088,6 @@ var MastraClient = class extends BaseResource {
2953
3088
  getLogTransports() {
2954
3089
  return this.request("/api/logs/transports");
2955
3090
  }
2956
- /**
2957
- * List of all traces (paged)
2958
- * @param params - Parameters for filtering traces
2959
- * @returns Promise containing telemetry data
2960
- */
2961
- getTelemetry(params) {
2962
- const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
2963
- const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
2964
- const searchParams = new URLSearchParams();
2965
- if (name) {
2966
- searchParams.set("name", name);
2967
- }
2968
- if (scope) {
2969
- searchParams.set("scope", scope);
2970
- }
2971
- if (page) {
2972
- searchParams.set("page", String(page));
2973
- }
2974
- if (perPage) {
2975
- searchParams.set("perPage", String(perPage));
2976
- }
2977
- if (_attribute) {
2978
- if (Array.isArray(_attribute)) {
2979
- for (const attr of _attribute) {
2980
- searchParams.append("attribute", attr);
2981
- }
2982
- } else {
2983
- searchParams.set("attribute", _attribute);
2984
- }
2985
- }
2986
- if (fromDate) {
2987
- searchParams.set("fromDate", fromDate.toISOString());
2988
- }
2989
- if (toDate) {
2990
- searchParams.set("toDate", toDate.toISOString());
2991
- }
2992
- if (searchParams.size) {
2993
- return this.request(`/api/telemetry?${searchParams}`);
2994
- } else {
2995
- return this.request(`/api/telemetry`);
2996
- }
2997
- }
2998
- /**
2999
- * Retrieves all available networks
3000
- * @returns Promise containing map of network IDs to network details
3001
- */
3002
- getNetworks() {
3003
- return this.request("/api/networks");
3004
- }
3005
- /**
3006
- * Retrieves all available vNext networks
3007
- * @returns Promise containing map of vNext network IDs to vNext network details
3008
- */
3009
- getVNextNetworks() {
3010
- return this.request("/api/networks/v-next");
3011
- }
3012
- /**
3013
- * Gets a network instance by ID
3014
- * @param networkId - ID of the network to retrieve
3015
- * @returns Network instance
3016
- */
3017
- getNetwork(networkId) {
3018
- return new Network(this.options, networkId);
3019
- }
3020
- /**
3021
- * Gets a vNext network instance by ID
3022
- * @param networkId - ID of the vNext network to retrieve
3023
- * @returns vNext Network instance
3024
- */
3025
- getVNextNetwork(networkId) {
3026
- return new VNextNetwork(this.options, networkId);
3027
- }
3028
3091
  /**
3029
3092
  * Retrieves a list of available MCP servers.
3030
3093
  * @param params - Optional parameters for pagination (limit, offset).
@@ -3095,6 +3158,26 @@ var MastraClient = class extends BaseResource {
3095
3158
  }) {
3096
3159
  return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3097
3160
  }
3161
+ searchMemory({
3162
+ agentId,
3163
+ resourceId,
3164
+ threadId,
3165
+ searchQuery,
3166
+ memoryConfig
3167
+ }) {
3168
+ const params = new URLSearchParams({
3169
+ searchQuery,
3170
+ resourceId,
3171
+ agentId
3172
+ });
3173
+ if (threadId) {
3174
+ params.append("threadId", threadId);
3175
+ }
3176
+ if (memoryConfig) {
3177
+ params.append("memoryConfig", JSON.stringify(memoryConfig));
3178
+ }
3179
+ return this.request(`/api/memory/search?${params}`);
3180
+ }
3098
3181
  /**
3099
3182
  * Updates the working memory for a specific thread (optionally resource-scoped).
3100
3183
  * @param agentId - ID of the agent.
@@ -3129,7 +3212,7 @@ var MastraClient = class extends BaseResource {
3129
3212
  * @returns Promise containing the scorer
3130
3213
  */
3131
3214
  getScorer(scorerId) {
3132
- return this.request(`/api/scores/scorers/${scorerId}`);
3215
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3133
3216
  }
3134
3217
  getScoresByScorerId(params) {
3135
3218
  const { page, perPage, scorerId, entityId, entityType } = params;
@@ -3147,7 +3230,7 @@ var MastraClient = class extends BaseResource {
3147
3230
  searchParams.set("perPage", String(perPage));
3148
3231
  }
3149
3232
  const queryString = searchParams.toString();
3150
- return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3233
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3151
3234
  }
3152
3235
  /**
3153
3236
  * Retrieves scores by run ID
@@ -3164,7 +3247,7 @@ var MastraClient = class extends BaseResource {
3164
3247
  searchParams.set("perPage", String(perPage));
3165
3248
  }
3166
3249
  const queryString = searchParams.toString();
3167
- return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3250
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
3168
3251
  }
3169
3252
  /**
3170
3253
  * Retrieves scores by entity ID and type
@@ -3181,7 +3264,9 @@ var MastraClient = class extends BaseResource {
3181
3264
  searchParams.set("perPage", String(perPage));
3182
3265
  }
3183
3266
  const queryString = searchParams.toString();
3184
- return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3267
+ return this.request(
3268
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3269
+ );
3185
3270
  }
3186
3271
  /**
3187
3272
  * Saves a score
@@ -3207,8 +3292,33 @@ var MastraClient = class extends BaseResource {
3207
3292
  getAITraces(params) {
3208
3293
  return this.observability.getTraces(params);
3209
3294
  }
3295
+ getScoresBySpan(params) {
3296
+ return this.observability.getScoresBySpan(params);
3297
+ }
3298
+ score(params) {
3299
+ return this.observability.score(params);
3300
+ }
3210
3301
  };
3211
3302
 
3212
- export { MastraClient };
3303
+ // src/tools.ts
3304
+ var ClientTool = class {
3305
+ id;
3306
+ description;
3307
+ inputSchema;
3308
+ outputSchema;
3309
+ execute;
3310
+ constructor(opts) {
3311
+ this.id = opts.id;
3312
+ this.description = opts.description;
3313
+ this.inputSchema = opts.inputSchema;
3314
+ this.outputSchema = opts.outputSchema;
3315
+ this.execute = opts.execute;
3316
+ }
3317
+ };
3318
+ function createTool(opts) {
3319
+ return new ClientTool(opts);
3320
+ }
3321
+
3322
+ export { ClientTool, MastraClient, createTool };
3213
3323
  //# sourceMappingURL=index.js.map
3214
3324
  //# sourceMappingURL=index.js.map