@mastra/client-js 0.0.0-consolidate-changesets-20250904042643 → 0.0.0-createToolOptions-20250926094418

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 +369 -35
  2. package/README.md +2 -6
  3. package/dist/client.d.ts +36 -31
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/index.cjs +476 -591
  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 +475 -592
  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 +47 -11
  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 +10 -0
  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/vNextNetwork.d.ts +2 -1
  24. package/dist/resources/vNextNetwork.d.ts.map +1 -1
  25. package/dist/resources/vector.d.ts +5 -2
  26. package/dist/resources/vector.d.ts.map +1 -1
  27. package/dist/resources/workflow.d.ts +110 -10
  28. package/dist/resources/workflow.d.ts.map +1 -1
  29. package/dist/tools.d.ts +22 -0
  30. package/dist/tools.d.ts.map +1 -0
  31. package/dist/types.d.ts +51 -63
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/utils/index.d.ts +2 -0
  34. package/dist/utils/index.d.ts.map +1 -1
  35. package/dist/utils/process-mastra-stream.d.ts +5 -1
  36. package/dist/utils/process-mastra-stream.d.ts.map +1 -1
  37. package/package.json +8 -11
  38. package/dist/adapters/agui.d.ts +0 -23
  39. package/dist/adapters/agui.d.ts.map +0 -1
  40. package/dist/resources/legacy-workflow.d.ts +0 -87
  41. package/dist/resources/legacy-workflow.d.ts.map +0 -1
  42. package/dist/resources/network.d.ts +0 -30
  43. package/dist/resources/network.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,3 @@
1
- import { AbstractAgent, EventType } from '@ag-ui/client';
2
- import { Observable } from 'rxjs';
3
1
  import { processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
4
2
  import { v4 } from '@lukeed/uuid';
5
3
  import { RuntimeContext } from '@mastra/core/runtime-context';
@@ -7,205 +5,7 @@ import { isVercelTool } from '@mastra/core/tools/is-vercel-tool';
7
5
  import { z } from 'zod';
8
6
  import originalZodToJsonSchema from 'zod-to-json-schema';
9
7
 
10
- // src/adapters/agui.ts
11
- var AGUIAdapter = class extends AbstractAgent {
12
- agent;
13
- resourceId;
14
- constructor({ agent, agentId, resourceId, ...rest }) {
15
- super({
16
- agentId,
17
- ...rest
18
- });
19
- this.agent = agent;
20
- this.resourceId = resourceId;
21
- }
22
- run(input) {
23
- return new Observable((subscriber) => {
24
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
25
- subscriber.next({
26
- type: EventType.RUN_STARTED,
27
- threadId: input.threadId,
28
- runId: input.runId
29
- });
30
- this.agent.stream({
31
- threadId: input.threadId,
32
- resourceId: this.resourceId ?? "",
33
- runId: input.runId,
34
- messages: convertedMessages,
35
- clientTools: input.tools.reduce(
36
- (acc, tool) => {
37
- acc[tool.name] = {
38
- id: tool.name,
39
- description: tool.description,
40
- inputSchema: tool.parameters
41
- };
42
- return acc;
43
- },
44
- {}
45
- )
46
- }).then((response) => {
47
- let currentMessageId = void 0;
48
- let isInTextMessage = false;
49
- return response.processDataStream({
50
- onTextPart: (text) => {
51
- if (currentMessageId === void 0) {
52
- currentMessageId = generateUUID();
53
- const message2 = {
54
- type: EventType.TEXT_MESSAGE_START,
55
- messageId: currentMessageId,
56
- role: "assistant"
57
- };
58
- subscriber.next(message2);
59
- isInTextMessage = true;
60
- }
61
- const message = {
62
- type: EventType.TEXT_MESSAGE_CONTENT,
63
- messageId: currentMessageId,
64
- delta: text
65
- };
66
- subscriber.next(message);
67
- },
68
- onFinishMessagePart: () => {
69
- if (currentMessageId !== void 0) {
70
- const message = {
71
- type: EventType.TEXT_MESSAGE_END,
72
- messageId: currentMessageId
73
- };
74
- subscriber.next(message);
75
- isInTextMessage = false;
76
- }
77
- subscriber.next({
78
- type: EventType.RUN_FINISHED,
79
- threadId: input.threadId,
80
- runId: input.runId
81
- });
82
- subscriber.complete();
83
- },
84
- onToolCallPart(streamPart) {
85
- const parentMessageId = currentMessageId || generateUUID();
86
- if (isInTextMessage) {
87
- const message = {
88
- type: EventType.TEXT_MESSAGE_END,
89
- messageId: parentMessageId
90
- };
91
- subscriber.next(message);
92
- isInTextMessage = false;
93
- }
94
- subscriber.next({
95
- type: EventType.TOOL_CALL_START,
96
- toolCallId: streamPart.toolCallId,
97
- toolCallName: streamPart.toolName,
98
- parentMessageId
99
- });
100
- subscriber.next({
101
- type: EventType.TOOL_CALL_ARGS,
102
- toolCallId: streamPart.toolCallId,
103
- delta: JSON.stringify(streamPart.args),
104
- parentMessageId
105
- });
106
- subscriber.next({
107
- type: EventType.TOOL_CALL_END,
108
- toolCallId: streamPart.toolCallId,
109
- parentMessageId
110
- });
111
- }
112
- });
113
- }).catch((error) => {
114
- console.error("error", error);
115
- subscriber.error(error);
116
- });
117
- return () => {
118
- };
119
- });
120
- }
121
- };
122
- function generateUUID() {
123
- if (typeof crypto !== "undefined") {
124
- if (typeof crypto.randomUUID === "function") {
125
- return crypto.randomUUID();
126
- }
127
- if (typeof crypto.getRandomValues === "function") {
128
- const buffer = new Uint8Array(16);
129
- crypto.getRandomValues(buffer);
130
- buffer[6] = buffer[6] & 15 | 64;
131
- buffer[8] = buffer[8] & 63 | 128;
132
- let hex = "";
133
- for (let i = 0; i < 16; i++) {
134
- hex += buffer[i].toString(16).padStart(2, "0");
135
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
136
- }
137
- return hex;
138
- }
139
- }
140
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
141
- const r = Math.random() * 16 | 0;
142
- const v = c === "x" ? r : r & 3 | 8;
143
- return v.toString(16);
144
- });
145
- }
146
- function convertMessagesToMastraMessages(messages) {
147
- const result = [];
148
- const toolCallsWithResults = /* @__PURE__ */ new Set();
149
- for (const message of messages) {
150
- if (message.role === "tool" && message.toolCallId) {
151
- toolCallsWithResults.add(message.toolCallId);
152
- }
153
- }
154
- for (const message of messages) {
155
- if (message.role === "assistant") {
156
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
157
- for (const toolCall of message.toolCalls ?? []) {
158
- parts.push({
159
- type: "tool-call",
160
- toolCallId: toolCall.id,
161
- toolName: toolCall.function.name,
162
- args: JSON.parse(toolCall.function.arguments)
163
- });
164
- }
165
- result.push({
166
- role: "assistant",
167
- content: parts
168
- });
169
- if (message.toolCalls?.length) {
170
- for (const toolCall of message.toolCalls) {
171
- if (!toolCallsWithResults.has(toolCall.id)) {
172
- result.push({
173
- role: "tool",
174
- content: [
175
- {
176
- type: "tool-result",
177
- toolCallId: toolCall.id,
178
- toolName: toolCall.function.name,
179
- result: JSON.parse(toolCall.function.arguments)
180
- // This is still wrong but matches test expectations
181
- }
182
- ]
183
- });
184
- }
185
- }
186
- }
187
- } else if (message.role === "user") {
188
- result.push({
189
- role: "user",
190
- content: message.content || ""
191
- });
192
- } else if (message.role === "tool") {
193
- result.push({
194
- role: "tool",
195
- content: [
196
- {
197
- type: "tool-result",
198
- toolCallId: message.toolCallId || "unknown",
199
- toolName: "unknown",
200
- // toolName is not available in tool messages from CopilotKit
201
- result: message.content
202
- }
203
- ]
204
- });
205
- }
206
- }
207
- return result;
208
- }
8
+ // src/resources/agent.ts
209
9
  function parseClientRuntimeContext(runtimeContext) {
210
10
  if (runtimeContext) {
211
11
  if (runtimeContext instanceof RuntimeContext) {
@@ -215,6 +15,20 @@ function parseClientRuntimeContext(runtimeContext) {
215
15
  }
216
16
  return void 0;
217
17
  }
18
+ function base64RuntimeContext(runtimeContext) {
19
+ if (runtimeContext) {
20
+ return btoa(JSON.stringify(runtimeContext));
21
+ }
22
+ return void 0;
23
+ }
24
+ function runtimeContextQueryString(runtimeContext) {
25
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
26
+ if (!runtimeContextParam) return "";
27
+ const searchParams = new URLSearchParams();
28
+ searchParams.set("runtimeContext", runtimeContextParam);
29
+ const queryString = searchParams.toString();
30
+ return queryString ? `?${queryString}` : "";
31
+ }
218
32
  function isZodType(value) {
219
33
  return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
220
34
  }
@@ -226,7 +40,7 @@ function zodToJsonSchema(zodSchema) {
226
40
  const fn = "toJSONSchema";
227
41
  return z[fn].call(z, zodSchema);
228
42
  }
229
- return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
43
+ return originalZodToJsonSchema(zodSchema, { $refStrategy: "relative" });
230
44
  }
231
45
 
232
46
  // src/utils/process-client-tools.ts
@@ -259,7 +73,7 @@ function processClientTools(clientTools) {
259
73
  }
260
74
 
261
75
  // src/utils/process-mastra-stream.ts
262
- async function processMastraStream({
76
+ async function sharedProcessMastraStream({
263
77
  stream,
264
78
  onChunk
265
79
  }) {
@@ -277,7 +91,7 @@ async function processMastraStream({
277
91
  if (line.startsWith("data: ")) {
278
92
  const data = line.slice(6);
279
93
  if (data === "[DONE]") {
280
- console.log("\u{1F3C1} Stream finished");
94
+ console.info("\u{1F3C1} Stream finished");
281
95
  return;
282
96
  }
283
97
  try {
@@ -293,6 +107,24 @@ async function processMastraStream({
293
107
  reader.releaseLock();
294
108
  }
295
109
  }
110
+ async function processMastraNetworkStream({
111
+ stream,
112
+ onChunk
113
+ }) {
114
+ return sharedProcessMastraStream({
115
+ stream,
116
+ onChunk
117
+ });
118
+ }
119
+ async function processMastraStream({
120
+ stream,
121
+ onChunk
122
+ }) {
123
+ return sharedProcessMastraStream({
124
+ stream,
125
+ onChunk
126
+ });
127
+ }
296
128
 
297
129
  // src/resources/base.ts
298
130
  var BaseResource = class {
@@ -381,7 +213,9 @@ async function executeToolCallAndRespond({
381
213
  resourceId,
382
214
  threadId,
383
215
  runtimeContext,
384
- tracingContext: { currentSpan: void 0 }
216
+ tracingContext: { currentSpan: void 0 },
217
+ suspend: async () => {
218
+ }
385
219
  },
386
220
  {
387
221
  messages: response.messages,
@@ -389,11 +223,7 @@ async function executeToolCallAndRespond({
389
223
  }
390
224
  );
391
225
  const updatedMessages = [
392
- {
393
- role: "user",
394
- content: params.messages
395
- },
396
- ...response.response.messages,
226
+ ...response.response.messages || [],
397
227
  {
398
228
  role: "tool",
399
229
  content: [
@@ -455,17 +285,21 @@ var AgentVoice = class extends BaseResource {
455
285
  }
456
286
  /**
457
287
  * Get available speakers for the agent's voice provider
288
+ * @param runtimeContext - Optional runtime context to pass as query parameter
289
+ * @param runtimeContext - Optional runtime context to pass as query parameter
458
290
  * @returns Promise containing list of available speakers
459
291
  */
460
- getSpeakers() {
461
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
292
+ getSpeakers(runtimeContext) {
293
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
462
294
  }
463
295
  /**
464
296
  * Get the listener configuration for the agent's voice provider
297
+ * @param runtimeContext - Optional runtime context to pass as query parameter
298
+ * @param runtimeContext - Optional runtime context to pass as query parameter
465
299
  * @returns Promise containing a check if the agent has listening capabilities
466
300
  */
467
- getListener() {
468
- return this.request(`/api/agents/${this.agentId}/voice/listener`);
301
+ getListener(runtimeContext) {
302
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
469
303
  }
470
304
  };
471
305
  var Agent = class extends BaseResource {
@@ -477,14 +311,15 @@ var Agent = class extends BaseResource {
477
311
  voice;
478
312
  /**
479
313
  * Retrieves details about the agent
314
+ * @param runtimeContext - Optional runtime context to pass as query parameter
480
315
  * @returns Promise containing agent details including model and instructions
481
316
  */
482
- details() {
483
- return this.request(`/api/agents/${this.agentId}`);
317
+ details(runtimeContext) {
318
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
484
319
  }
485
320
  async generate(params) {
486
321
  console.warn(
487
- "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th. Please use generateLegacy if you don't want to upgrade just yet."
322
+ "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 30th, 2025. Please use generateLegacy if you don't want to upgrade just yet."
488
323
  );
489
324
  return this.generateLegacy(params);
490
325
  }
@@ -519,7 +354,9 @@ var Agent = class extends BaseResource {
519
354
  resourceId,
520
355
  threadId,
521
356
  runtimeContext,
522
- tracingContext: { currentSpan: void 0 }
357
+ tracingContext: { currentSpan: void 0 },
358
+ suspend: async () => {
359
+ }
523
360
  },
524
361
  {
525
362
  messages: response.messages,
@@ -527,10 +364,6 @@ var Agent = class extends BaseResource {
527
364
  }
528
365
  );
529
366
  const updatedMessages = [
530
- {
531
- role: "user",
532
- content: params.messages
533
- },
534
367
  ...response.response.messages,
535
368
  {
536
369
  role: "tool",
@@ -553,12 +386,25 @@ var Agent = class extends BaseResource {
553
386
  }
554
387
  return response;
555
388
  }
556
- async generateVNext(params) {
389
+ async generateVNext(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
+ }
557
399
  const processedParams = {
558
400
  ...params,
559
401
  output: params.output ? zodToJsonSchema(params.output) : void 0,
560
402
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
561
- 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
562
408
  };
563
409
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
564
410
  const response = await this.request(
@@ -850,7 +696,7 @@ var Agent = class extends BaseResource {
850
696
  */
851
697
  async stream(params) {
852
698
  console.warn(
853
- "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th. Please use streamLegacy if you don't want to upgrade just yet."
699
+ "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 30th, 2025. Please use streamLegacy if you don't want to upgrade just yet."
854
700
  );
855
701
  return this.streamLegacy(params);
856
702
  }
@@ -1063,7 +909,7 @@ var Agent = class extends BaseResource {
1063
909
  step,
1064
910
  toolCallId: chunk.payload.toolCallId,
1065
911
  toolName: chunk.payload.toolName,
1066
- args: void 0
912
+ args: chunk.payload.args
1067
913
  };
1068
914
  message.toolInvocations.push(invocation);
1069
915
  updateToolInvocationPart(chunk.payload.toolCallId, invocation);
@@ -1117,14 +963,14 @@ var Agent = class extends BaseResource {
1117
963
  }
1118
964
  case "step-finish": {
1119
965
  step += 1;
1120
- currentTextPart = chunk.payload.isContinued ? currentTextPart : void 0;
966
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
1121
967
  currentReasoningPart = void 0;
1122
968
  currentReasoningTextDetail = void 0;
1123
969
  execUpdate();
1124
970
  break;
1125
971
  }
1126
972
  case "finish": {
1127
- finishReason = chunk.payload.finishReason;
973
+ finishReason = chunk.payload.stepResult.reason;
1128
974
  if (chunk.payload.usage != null) {
1129
975
  usage = chunk.payload.usage;
1130
976
  }
@@ -1148,9 +994,28 @@ var Agent = class extends BaseResource {
1148
994
  let toolCalls = [];
1149
995
  let messages = [];
1150
996
  const [streamForWritable, streamForProcessing] = response.body.tee();
1151
- streamForWritable.pipeTo(writable, {
1152
- preventClose: true
1153
- }).catch((error) => {
997
+ streamForWritable.pipeTo(
998
+ new WritableStream({
999
+ async write(chunk) {
1000
+ try {
1001
+ const text = new TextDecoder().decode(chunk);
1002
+ if (text.includes("[DONE]")) {
1003
+ return;
1004
+ }
1005
+ } catch {
1006
+ }
1007
+ const writer = writable.getWriter();
1008
+ try {
1009
+ await writer.write(chunk);
1010
+ } finally {
1011
+ writer.releaseLock();
1012
+ }
1013
+ }
1014
+ }),
1015
+ {
1016
+ preventClose: true
1017
+ }
1018
+ ).catch((error) => {
1154
1019
  console.error("Error piping to writable stream:", error);
1155
1020
  });
1156
1021
  this.processChatResponse_vNext({
@@ -1180,14 +1045,17 @@ var Agent = class extends BaseResource {
1180
1045
  threadId: processedParams.threadId,
1181
1046
  runtimeContext: processedParams.runtimeContext,
1182
1047
  // TODO: Pass proper tracing context when client-js supports tracing
1183
- tracingContext: { currentSpan: void 0 }
1048
+ tracingContext: { currentSpan: void 0 },
1049
+ suspend: async () => {
1050
+ }
1184
1051
  },
1185
1052
  {
1186
1053
  messages: response.messages,
1187
1054
  toolCallId: toolCall2?.toolCallId
1188
1055
  }
1189
1056
  );
1190
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1057
+ const lastMessageRaw = messages[messages.length - 1];
1058
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1191
1059
  const toolInvocationPart = lastMessage?.parts?.find(
1192
1060
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1193
1061
  );
@@ -1205,25 +1073,11 @@ var Agent = class extends BaseResource {
1205
1073
  toolInvocation.state = "result";
1206
1074
  toolInvocation.result = result;
1207
1075
  }
1208
- const writer = writable.getWriter();
1209
- try {
1210
- await writer.write(
1211
- new TextEncoder().encode(
1212
- "a:" + JSON.stringify({
1213
- toolCallId: toolCall2.toolCallId,
1214
- result
1215
- }) + "\n"
1216
- )
1217
- );
1218
- } finally {
1219
- writer.releaseLock();
1220
- }
1221
- const originalMessages = processedParams.messages;
1222
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1076
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1223
1077
  this.processStreamResponse_vNext(
1224
1078
  {
1225
1079
  ...processedParams,
1226
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1080
+ messages: updatedMessages
1227
1081
  },
1228
1082
  writable
1229
1083
  ).catch((error) => {
@@ -1246,12 +1100,49 @@ var Agent = class extends BaseResource {
1246
1100
  }
1247
1101
  return response;
1248
1102
  }
1249
- async streamVNext(params) {
1103
+ async network(params) {
1104
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1105
+ method: "POST",
1106
+ body: params,
1107
+ stream: true
1108
+ });
1109
+ if (!response.body) {
1110
+ throw new Error("No response body");
1111
+ }
1112
+ const streamResponse = new Response(response.body, {
1113
+ status: response.status,
1114
+ statusText: response.statusText,
1115
+ headers: response.headers
1116
+ });
1117
+ streamResponse.processDataStream = async ({
1118
+ onChunk
1119
+ }) => {
1120
+ await processMastraNetworkStream({
1121
+ stream: streamResponse.body,
1122
+ onChunk
1123
+ });
1124
+ };
1125
+ return streamResponse;
1126
+ }
1127
+ async streamVNext(messagesOrParams, options) {
1128
+ let params;
1129
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1130
+ params = messagesOrParams;
1131
+ } else {
1132
+ params = {
1133
+ messages: messagesOrParams,
1134
+ ...options
1135
+ };
1136
+ }
1250
1137
  const processedParams = {
1251
1138
  ...params,
1252
1139
  output: params.output ? zodToJsonSchema(params.output) : void 0,
1253
1140
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1254
- clientTools: processClientTools(params.clientTools)
1141
+ clientTools: processClientTools(params.clientTools),
1142
+ structuredOutput: params.structuredOutput ? {
1143
+ ...params.structuredOutput,
1144
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1145
+ } : void 0
1255
1146
  };
1256
1147
  const { readable, writable } = new TransformStream();
1257
1148
  const response = await this.processStreamResponse_vNext(processedParams, writable);
@@ -1318,7 +1209,9 @@ var Agent = class extends BaseResource {
1318
1209
  threadId: processedParams.threadId,
1319
1210
  runtimeContext: processedParams.runtimeContext,
1320
1211
  // TODO: Pass proper tracing context when client-js supports tracing
1321
- tracingContext: { currentSpan: void 0 }
1212
+ tracingContext: { currentSpan: void 0 },
1213
+ suspend: async () => {
1214
+ }
1322
1215
  },
1323
1216
  {
1324
1217
  messages: response.messages,
@@ -1356,12 +1249,10 @@ var Agent = class extends BaseResource {
1356
1249
  } finally {
1357
1250
  writer.releaseLock();
1358
1251
  }
1359
- const originalMessages = processedParams.messages;
1360
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1361
1252
  this.processStreamResponse(
1362
1253
  {
1363
1254
  ...processedParams,
1364
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1255
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1365
1256
  },
1366
1257
  writable
1367
1258
  ).catch((error) => {
@@ -1387,10 +1278,11 @@ var Agent = class extends BaseResource {
1387
1278
  /**
1388
1279
  * Gets details about a specific tool available to the agent
1389
1280
  * @param toolId - ID of the tool to retrieve
1281
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1390
1282
  * @returns Promise containing tool details
1391
1283
  */
1392
- getTool(toolId) {
1393
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1284
+ getTool(toolId, runtimeContext) {
1285
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
1394
1286
  }
1395
1287
  /**
1396
1288
  * Executes a tool for the agent
@@ -1401,7 +1293,7 @@ var Agent = class extends BaseResource {
1401
1293
  executeTool(toolId, params) {
1402
1294
  const body = {
1403
1295
  data: params.data,
1404
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1296
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1405
1297
  };
1406
1298
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1407
1299
  method: "POST",
@@ -1410,17 +1302,19 @@ var Agent = class extends BaseResource {
1410
1302
  }
1411
1303
  /**
1412
1304
  * Retrieves evaluation results for the agent
1305
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1413
1306
  * @returns Promise containing agent evaluations
1414
1307
  */
1415
- evals() {
1416
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1308
+ evals(runtimeContext) {
1309
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
1417
1310
  }
1418
1311
  /**
1419
1312
  * Retrieves live evaluation results for the agent
1313
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1420
1314
  * @returns Promise containing live agent evaluations
1421
1315
  */
1422
- liveEvals() {
1423
- return this.request(`/api/agents/${this.agentId}/evals/live`);
1316
+ liveEvals(runtimeContext) {
1317
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
1424
1318
  }
1425
1319
  /**
1426
1320
  * Updates the model for the agent
@@ -1433,61 +1327,27 @@ var Agent = class extends BaseResource {
1433
1327
  body: params
1434
1328
  });
1435
1329
  }
1436
- };
1437
- var Network = class extends BaseResource {
1438
- constructor(options, networkId) {
1439
- super(options);
1440
- this.networkId = networkId;
1441
- }
1442
- /**
1443
- * Retrieves details about the network
1444
- * @returns Promise containing network details
1445
- */
1446
- details() {
1447
- return this.request(`/api/networks/${this.networkId}`);
1448
- }
1449
1330
  /**
1450
- * Generates a response from the agent
1451
- * @param params - Generation parameters including prompt
1452
- * @returns Promise containing the generated response
1331
+ * Updates the model for the agent in the model list
1332
+ * @param params - Parameters for updating the model
1333
+ * @returns Promise containing the updated model
1453
1334
  */
1454
- generate(params) {
1455
- const processedParams = {
1456
- ...params,
1457
- output: zodToJsonSchema(params.output),
1458
- experimental_output: zodToJsonSchema(params.experimental_output)
1459
- };
1460
- return this.request(`/api/networks/${this.networkId}/generate`, {
1335
+ updateModelInModelList({ modelConfigId, ...params }) {
1336
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
1461
1337
  method: "POST",
1462
- body: processedParams
1338
+ body: params
1463
1339
  });
1464
1340
  }
1465
1341
  /**
1466
- * Streams a response from the agent
1467
- * @param params - Stream parameters including prompt
1468
- * @returns Promise containing the enhanced Response object with processDataStream method
1342
+ * Reorders the models for the agent
1343
+ * @param params - Parameters for reordering the model list
1344
+ * @returns Promise containing the updated model list
1469
1345
  */
1470
- async stream(params) {
1471
- const processedParams = {
1472
- ...params,
1473
- output: zodToJsonSchema(params.output),
1474
- experimental_output: zodToJsonSchema(params.experimental_output)
1475
- };
1476
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1346
+ reorderModelList(params) {
1347
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
1477
1348
  method: "POST",
1478
- body: processedParams,
1479
- stream: true
1349
+ body: params
1480
1350
  });
1481
- if (!response.body) {
1482
- throw new Error("No response body");
1483
- }
1484
- response.processDataStream = async (options = {}) => {
1485
- await processDataStream({
1486
- stream: response.body,
1487
- ...options
1488
- });
1489
- };
1490
- return response;
1491
1351
  }
1492
1352
  };
1493
1353
 
@@ -1578,10 +1438,13 @@ var Vector = class extends BaseResource {
1578
1438
  /**
1579
1439
  * Retrieves details about a specific vector index
1580
1440
  * @param indexName - Name of the index to get details for
1441
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1581
1442
  * @returns Promise containing vector index details
1582
1443
  */
1583
- details(indexName) {
1584
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1444
+ details(indexName, runtimeContext) {
1445
+ return this.request(
1446
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1447
+ );
1585
1448
  }
1586
1449
  /**
1587
1450
  * Deletes a vector index
@@ -1595,10 +1458,11 @@ var Vector = class extends BaseResource {
1595
1458
  }
1596
1459
  /**
1597
1460
  * Retrieves a list of all available indexes
1461
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1598
1462
  * @returns Promise containing array of index names
1599
1463
  */
1600
- getIndexes() {
1601
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1464
+ getIndexes(runtimeContext) {
1465
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
1602
1466
  }
1603
1467
  /**
1604
1468
  * Creates a new vector index
@@ -1635,187 +1499,6 @@ var Vector = class extends BaseResource {
1635
1499
  }
1636
1500
  };
1637
1501
 
1638
- // src/resources/legacy-workflow.ts
1639
- var RECORD_SEPARATOR = "";
1640
- var LegacyWorkflow = class extends BaseResource {
1641
- constructor(options, workflowId) {
1642
- super(options);
1643
- this.workflowId = workflowId;
1644
- }
1645
- /**
1646
- * Retrieves details about the legacy workflow
1647
- * @returns Promise containing legacy workflow details including steps and graphs
1648
- */
1649
- details() {
1650
- return this.request(`/api/workflows/legacy/${this.workflowId}`);
1651
- }
1652
- /**
1653
- * Retrieves all runs for a legacy workflow
1654
- * @param params - Parameters for filtering runs
1655
- * @returns Promise containing legacy workflow runs array
1656
- */
1657
- runs(params) {
1658
- const searchParams = new URLSearchParams();
1659
- if (params?.fromDate) {
1660
- searchParams.set("fromDate", params.fromDate.toISOString());
1661
- }
1662
- if (params?.toDate) {
1663
- searchParams.set("toDate", params.toDate.toISOString());
1664
- }
1665
- if (params?.limit) {
1666
- searchParams.set("limit", String(params.limit));
1667
- }
1668
- if (params?.offset) {
1669
- searchParams.set("offset", String(params.offset));
1670
- }
1671
- if (params?.resourceId) {
1672
- searchParams.set("resourceId", params.resourceId);
1673
- }
1674
- if (searchParams.size) {
1675
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1676
- } else {
1677
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1678
- }
1679
- }
1680
- /**
1681
- * Creates a new legacy workflow run
1682
- * @returns Promise containing the generated run ID
1683
- */
1684
- createRun(params) {
1685
- const searchParams = new URLSearchParams();
1686
- if (!!params?.runId) {
1687
- searchParams.set("runId", params.runId);
1688
- }
1689
- return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1690
- method: "POST"
1691
- });
1692
- }
1693
- /**
1694
- * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1695
- * @param params - Object containing the runId and triggerData
1696
- * @returns Promise containing success message
1697
- */
1698
- start(params) {
1699
- return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1700
- method: "POST",
1701
- body: params?.triggerData
1702
- });
1703
- }
1704
- /**
1705
- * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
1706
- * @param stepId - ID of the step to resume
1707
- * @param runId - ID of the legacy workflow run
1708
- * @param context - Context to resume the legacy workflow with
1709
- * @returns Promise containing the legacy workflow resume results
1710
- */
1711
- resume({
1712
- stepId,
1713
- runId,
1714
- context
1715
- }) {
1716
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
1717
- method: "POST",
1718
- body: {
1719
- stepId,
1720
- context
1721
- }
1722
- });
1723
- }
1724
- /**
1725
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1726
- * @param params - Object containing the optional runId and triggerData
1727
- * @returns Promise containing the workflow execution results
1728
- */
1729
- startAsync(params) {
1730
- const searchParams = new URLSearchParams();
1731
- if (!!params?.runId) {
1732
- searchParams.set("runId", params.runId);
1733
- }
1734
- return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1735
- method: "POST",
1736
- body: params?.triggerData
1737
- });
1738
- }
1739
- /**
1740
- * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1741
- * @param params - Object containing the runId, stepId, and context
1742
- * @returns Promise containing the workflow resume results
1743
- */
1744
- resumeAsync(params) {
1745
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1746
- method: "POST",
1747
- body: {
1748
- stepId: params.stepId,
1749
- context: params.context
1750
- }
1751
- });
1752
- }
1753
- /**
1754
- * Creates an async generator that processes a readable stream and yields records
1755
- * separated by the Record Separator character (\x1E)
1756
- *
1757
- * @param stream - The readable stream to process
1758
- * @returns An async generator that yields parsed records
1759
- */
1760
- async *streamProcessor(stream) {
1761
- const reader = stream.getReader();
1762
- let doneReading = false;
1763
- let buffer = "";
1764
- try {
1765
- while (!doneReading) {
1766
- const { done, value } = await reader.read();
1767
- doneReading = done;
1768
- if (done && !value) continue;
1769
- try {
1770
- const decoded = value ? new TextDecoder().decode(value) : "";
1771
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1772
- buffer = chunks.pop() || "";
1773
- for (const chunk of chunks) {
1774
- if (chunk) {
1775
- if (typeof chunk === "string") {
1776
- try {
1777
- const parsedChunk = JSON.parse(chunk);
1778
- yield parsedChunk;
1779
- } catch {
1780
- }
1781
- }
1782
- }
1783
- }
1784
- } catch {
1785
- }
1786
- }
1787
- if (buffer) {
1788
- try {
1789
- yield JSON.parse(buffer);
1790
- } catch {
1791
- }
1792
- }
1793
- } finally {
1794
- reader.cancel().catch(() => {
1795
- });
1796
- }
1797
- }
1798
- /**
1799
- * Watches legacy workflow transitions in real-time
1800
- * @param runId - Optional run ID to filter the watch stream
1801
- * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1802
- */
1803
- async watch({ runId }, onRecord) {
1804
- const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1805
- stream: true
1806
- });
1807
- if (!response.ok) {
1808
- throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1809
- }
1810
- if (!response.body) {
1811
- throw new Error("Response body is null");
1812
- }
1813
- for await (const record of this.streamProcessor(response.body)) {
1814
- onRecord(record);
1815
- }
1816
- }
1817
- };
1818
-
1819
1502
  // src/resources/tool.ts
1820
1503
  var Tool = class extends BaseResource {
1821
1504
  constructor(options, toolId) {
@@ -1824,10 +1507,11 @@ var Tool = class extends BaseResource {
1824
1507
  }
1825
1508
  /**
1826
1509
  * Retrieves details about the tool
1510
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1827
1511
  * @returns Promise containing tool details including description and schemas
1828
1512
  */
1829
- details() {
1830
- return this.request(`/api/tools/${this.toolId}`);
1513
+ details(runtimeContext) {
1514
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1831
1515
  }
1832
1516
  /**
1833
1517
  * Executes the tool with the provided parameters
@@ -1851,7 +1535,7 @@ var Tool = class extends BaseResource {
1851
1535
  };
1852
1536
 
1853
1537
  // src/resources/workflow.ts
1854
- var RECORD_SEPARATOR2 = "";
1538
+ var RECORD_SEPARATOR = "";
1855
1539
  var Workflow = class extends BaseResource {
1856
1540
  constructor(options, workflowId) {
1857
1541
  super(options);
@@ -1875,7 +1559,7 @@ var Workflow = class extends BaseResource {
1875
1559
  if (done && !value) continue;
1876
1560
  try {
1877
1561
  const decoded = value ? new TextDecoder().decode(value) : "";
1878
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1562
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1879
1563
  buffer = chunks.pop() || "";
1880
1564
  for (const chunk of chunks) {
1881
1565
  if (chunk) {
@@ -1904,17 +1588,20 @@ var Workflow = class extends BaseResource {
1904
1588
  }
1905
1589
  /**
1906
1590
  * Retrieves details about the workflow
1591
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1907
1592
  * @returns Promise containing workflow details including steps and graphs
1908
1593
  */
1909
- details() {
1910
- return this.request(`/api/workflows/${this.workflowId}`);
1594
+ details(runtimeContext) {
1595
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1911
1596
  }
1912
1597
  /**
1913
1598
  * Retrieves all runs for a workflow
1914
1599
  * @param params - Parameters for filtering runs
1600
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1915
1601
  * @returns Promise containing workflow runs array
1916
1602
  */
1917
- runs(params) {
1603
+ runs(params, runtimeContext) {
1604
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1918
1605
  const searchParams = new URLSearchParams();
1919
1606
  if (params?.fromDate) {
1920
1607
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1931,6 +1618,9 @@ var Workflow = class extends BaseResource {
1931
1618
  if (params?.resourceId) {
1932
1619
  searchParams.set("resourceId", params.resourceId);
1933
1620
  }
1621
+ if (runtimeContextParam) {
1622
+ searchParams.set("runtimeContext", runtimeContextParam);
1623
+ }
1934
1624
  if (searchParams.size) {
1935
1625
  return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1936
1626
  } else {
@@ -1940,18 +1630,22 @@ var Workflow = class extends BaseResource {
1940
1630
  /**
1941
1631
  * Retrieves a specific workflow run by its ID
1942
1632
  * @param runId - The ID of the workflow run to retrieve
1633
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1943
1634
  * @returns Promise containing the workflow run details
1944
1635
  */
1945
- runById(runId) {
1946
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1636
+ runById(runId, runtimeContext) {
1637
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1947
1638
  }
1948
1639
  /**
1949
1640
  * Retrieves the execution result for a specific workflow run by its ID
1950
1641
  * @param runId - The ID of the workflow run to retrieve the execution result for
1642
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1951
1643
  * @returns Promise containing the workflow run execution result
1952
1644
  */
1953
- runExecutionResult(runId) {
1954
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1645
+ runExecutionResult(runId, runtimeContext) {
1646
+ return this.request(
1647
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1648
+ );
1955
1649
  }
1956
1650
  /**
1957
1651
  * Cancels a specific workflow run by its ID
@@ -1974,27 +1668,61 @@ var Workflow = class extends BaseResource {
1974
1668
  body: { event: params.event, data: params.data }
1975
1669
  });
1976
1670
  }
1671
+ /**
1672
+ * @deprecated Use createRunAsync() instead.
1673
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1674
+ */
1675
+ async createRun(_params) {
1676
+ throw new Error(
1677
+ "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."
1678
+ );
1679
+ }
1977
1680
  /**
1978
1681
  * Creates a new workflow run
1979
1682
  * @param params - Optional object containing the optional runId
1980
- * @returns Promise containing the runId of the created run
1683
+ * @returns Promise containing the runId of the created run with methods to control execution
1981
1684
  */
1982
- createRun(params) {
1685
+ async createRunAsync(params) {
1983
1686
  const searchParams = new URLSearchParams();
1984
1687
  if (!!params?.runId) {
1985
1688
  searchParams.set("runId", params.runId);
1986
1689
  }
1987
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1988
- method: "POST"
1989
- });
1990
- }
1991
- /**
1992
- * Creates a new workflow run (alias for createRun)
1993
- * @param params - Optional object containing the optional runId
1994
- * @returns Promise containing the runId of the created run
1995
- */
1996
- createRunAsync(params) {
1997
- return this.createRun(params);
1690
+ const res = await this.request(
1691
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1692
+ {
1693
+ method: "POST"
1694
+ }
1695
+ );
1696
+ const runId = res.runId;
1697
+ return {
1698
+ runId,
1699
+ start: async (p) => {
1700
+ return this.start({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1701
+ },
1702
+ startAsync: async (p) => {
1703
+ return this.startAsync({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1704
+ },
1705
+ watch: async (onRecord) => {
1706
+ return this.watch({ runId }, onRecord);
1707
+ },
1708
+ stream: async (p) => {
1709
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1710
+ },
1711
+ resume: async (p) => {
1712
+ return this.resume({ runId, step: p.step, resumeData: p.resumeData, runtimeContext: p.runtimeContext });
1713
+ },
1714
+ resumeAsync: async (p) => {
1715
+ return this.resumeAsync({ runId, step: p.step, resumeData: p.resumeData, runtimeContext: p.runtimeContext });
1716
+ },
1717
+ resumeStreamVNext: async (p) => {
1718
+ return this.resumeStreamVNext({
1719
+ runId,
1720
+ step: p.step,
1721
+ resumeData: p.resumeData,
1722
+ runtimeContext: p.runtimeContext
1723
+ });
1724
+ }
1725
+ };
1998
1726
  }
1999
1727
  /**
2000
1728
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -2022,7 +1750,6 @@ var Workflow = class extends BaseResource {
2022
1750
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
2023
1751
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
2024
1752
  method: "POST",
2025
- stream: true,
2026
1753
  body: {
2027
1754
  step,
2028
1755
  resumeData,
@@ -2065,6 +1792,104 @@ var Workflow = class extends BaseResource {
2065
1792
  stream: true
2066
1793
  }
2067
1794
  );
1795
+ if (!response.ok) {
1796
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1797
+ }
1798
+ if (!response.body) {
1799
+ throw new Error("Response body is null");
1800
+ }
1801
+ let failedChunk = void 0;
1802
+ const transformStream = new TransformStream({
1803
+ start() {
1804
+ },
1805
+ async transform(chunk, controller) {
1806
+ try {
1807
+ const decoded = new TextDecoder().decode(chunk);
1808
+ const chunks = decoded.split(RECORD_SEPARATOR);
1809
+ for (const chunk2 of chunks) {
1810
+ if (chunk2) {
1811
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1812
+ try {
1813
+ const parsedChunk = JSON.parse(newChunk);
1814
+ controller.enqueue(parsedChunk);
1815
+ failedChunk = void 0;
1816
+ } catch {
1817
+ failedChunk = newChunk;
1818
+ }
1819
+ }
1820
+ }
1821
+ } catch {
1822
+ }
1823
+ }
1824
+ });
1825
+ return response.body.pipeThrough(transformStream);
1826
+ }
1827
+ /**
1828
+ * Observes workflow stream for a workflow run
1829
+ * @param params - Object containing the runId
1830
+ * @returns Promise containing the workflow execution results
1831
+ */
1832
+ async observeStream(params) {
1833
+ const searchParams = new URLSearchParams();
1834
+ searchParams.set("runId", params.runId);
1835
+ const response = await this.request(
1836
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1837
+ {
1838
+ method: "POST",
1839
+ stream: true
1840
+ }
1841
+ );
1842
+ if (!response.ok) {
1843
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1844
+ }
1845
+ if (!response.body) {
1846
+ throw new Error("Response body is null");
1847
+ }
1848
+ let failedChunk = void 0;
1849
+ const transformStream = new TransformStream({
1850
+ start() {
1851
+ },
1852
+ async transform(chunk, controller) {
1853
+ try {
1854
+ const decoded = new TextDecoder().decode(chunk);
1855
+ const chunks = decoded.split(RECORD_SEPARATOR);
1856
+ for (const chunk2 of chunks) {
1857
+ if (chunk2) {
1858
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1859
+ try {
1860
+ const parsedChunk = JSON.parse(newChunk);
1861
+ controller.enqueue(parsedChunk);
1862
+ failedChunk = void 0;
1863
+ } catch {
1864
+ failedChunk = newChunk;
1865
+ }
1866
+ }
1867
+ }
1868
+ } catch {
1869
+ }
1870
+ }
1871
+ });
1872
+ return response.body.pipeThrough(transformStream);
1873
+ }
1874
+ /**
1875
+ * Starts a workflow run and returns a stream
1876
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1877
+ * @returns Promise containing the workflow execution results
1878
+ */
1879
+ async streamVNext(params) {
1880
+ const searchParams = new URLSearchParams();
1881
+ if (!!params?.runId) {
1882
+ searchParams.set("runId", params.runId);
1883
+ }
1884
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1885
+ const response = await this.request(
1886
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1887
+ {
1888
+ method: "POST",
1889
+ body: { inputData: params.inputData, runtimeContext, closeOnSuspend: params.closeOnSuspend },
1890
+ stream: true
1891
+ }
1892
+ );
2068
1893
  if (!response.ok) {
2069
1894
  throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2070
1895
  }
@@ -2078,7 +1903,7 @@ var Workflow = class extends BaseResource {
2078
1903
  async transform(chunk, controller) {
2079
1904
  try {
2080
1905
  const decoded = new TextDecoder().decode(chunk);
2081
- const chunks = decoded.split(RECORD_SEPARATOR2);
1906
+ const chunks = decoded.split(RECORD_SEPARATOR);
2082
1907
  for (const chunk2 of chunks) {
2083
1908
  if (chunk2) {
2084
1909
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2113,6 +1938,22 @@ var Workflow = class extends BaseResource {
2113
1938
  }
2114
1939
  });
2115
1940
  }
1941
+ /**
1942
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
1943
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1944
+ * @returns Promise containing the workflow resume results
1945
+ */
1946
+ resumeStreamVNext(params) {
1947
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1948
+ return this.request(`/api/workflows/${this.workflowId}/resume-stream?runId=${params.runId}`, {
1949
+ method: "POST",
1950
+ body: {
1951
+ step: params.step,
1952
+ resumeData: params.resumeData,
1953
+ runtimeContext
1954
+ }
1955
+ });
1956
+ }
2116
1957
  /**
2117
1958
  * Watches workflow transitions in real-time
2118
1959
  * @param runId - Optional run ID to filter the watch stream
@@ -2149,7 +1990,7 @@ var Workflow = class extends BaseResource {
2149
1990
  async start(controller) {
2150
1991
  try {
2151
1992
  for await (const record of records) {
2152
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1993
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
2153
1994
  controller.enqueue(encoder.encode(json));
2154
1995
  }
2155
1996
  controller.close();
@@ -2247,10 +2088,11 @@ var MCPTool = class extends BaseResource {
2247
2088
  }
2248
2089
  /**
2249
2090
  * Retrieves details about this specific tool from the MCP server.
2091
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2250
2092
  * @returns Promise containing the tool's information (name, description, schema).
2251
2093
  */
2252
- details() {
2253
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2094
+ details(runtimeContext) {
2095
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2254
2096
  }
2255
2097
  /**
2256
2098
  * Executes this specific tool on the MCP server.
@@ -2271,7 +2113,7 @@ var MCPTool = class extends BaseResource {
2271
2113
  };
2272
2114
 
2273
2115
  // src/resources/agent-builder.ts
2274
- var RECORD_SEPARATOR3 = "";
2116
+ var RECORD_SEPARATOR2 = "";
2275
2117
  var AgentBuilder = class extends BaseResource {
2276
2118
  constructor(options, actionId) {
2277
2119
  super(options);
@@ -2306,21 +2148,27 @@ var AgentBuilder = class extends BaseResource {
2306
2148
  };
2307
2149
  }
2308
2150
  }
2151
+ /**
2152
+ * @deprecated Use createRunAsync() instead.
2153
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2154
+ */
2155
+ async createRun(_params) {
2156
+ throw new Error(
2157
+ "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."
2158
+ );
2159
+ }
2309
2160
  /**
2310
2161
  * Creates a new agent builder action run and returns the runId.
2311
2162
  * This calls `/api/agent-builder/:actionId/create-run`.
2312
2163
  */
2313
- async createRun(params, runId) {
2164
+ async createRunAsync(params) {
2314
2165
  const searchParams = new URLSearchParams();
2315
- if (runId) {
2316
- searchParams.set("runId", runId);
2166
+ if (!!params?.runId) {
2167
+ searchParams.set("runId", params.runId);
2317
2168
  }
2318
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2319
- const { runtimeContext: _, ...actionParams } = params;
2320
2169
  const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2321
2170
  return this.request(url, {
2322
- method: "POST",
2323
- body: { ...actionParams, runtimeContext }
2171
+ method: "POST"
2324
2172
  });
2325
2173
  }
2326
2174
  /**
@@ -2405,7 +2253,7 @@ var AgentBuilder = class extends BaseResource {
2405
2253
  if (done && !value) continue;
2406
2254
  try {
2407
2255
  const decoded = value ? new TextDecoder().decode(value) : "";
2408
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2256
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2409
2257
  buffer = chunks.pop() || "";
2410
2258
  for (const chunk of chunks) {
2411
2259
  if (chunk) {
@@ -2462,7 +2310,7 @@ var AgentBuilder = class extends BaseResource {
2462
2310
  async transform(chunk, controller) {
2463
2311
  try {
2464
2312
  const decoded = new TextDecoder().decode(chunk);
2465
- const chunks = decoded.split(RECORD_SEPARATOR3);
2313
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2466
2314
  for (const chunk2 of chunks) {
2467
2315
  if (chunk2) {
2468
2316
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2511,7 +2359,7 @@ var AgentBuilder = class extends BaseResource {
2511
2359
  async transform(chunk, controller) {
2512
2360
  try {
2513
2361
  const decoded = new TextDecoder().decode(chunk);
2514
- const chunks = decoded.split(RECORD_SEPARATOR3);
2362
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2515
2363
  for (const chunk2 of chunks) {
2516
2364
  if (chunk2) {
2517
2365
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2536,8 +2384,8 @@ var AgentBuilder = class extends BaseResource {
2536
2384
  * and streams any remaining progress.
2537
2385
  * This calls `/api/agent-builder/:actionId/watch`.
2538
2386
  */
2539
- async watch({ runId }, onRecord) {
2540
- const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}`;
2387
+ async watch({ runId, eventType }, onRecord) {
2388
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2541
2389
  const response = await this.request(url, {
2542
2390
  method: "GET",
2543
2391
  stream: true
@@ -2654,7 +2502,7 @@ var Observability = class extends BaseResource {
2654
2502
  getTraces(params) {
2655
2503
  const { pagination, filters } = params;
2656
2504
  const { page, perPage, dateRange } = pagination || {};
2657
- const { name, spanType } = filters || {};
2505
+ const { name, spanType, entityId, entityType } = filters || {};
2658
2506
  const searchParams = new URLSearchParams();
2659
2507
  if (page !== void 0) {
2660
2508
  searchParams.set("page", String(page));
@@ -2668,6 +2516,10 @@ var Observability = class extends BaseResource {
2668
2516
  if (spanType !== void 0) {
2669
2517
  searchParams.set("spanType", String(spanType));
2670
2518
  }
2519
+ if (entityId && entityType) {
2520
+ searchParams.set("entityId", entityId);
2521
+ searchParams.set("entityType", entityType);
2522
+ }
2671
2523
  if (dateRange) {
2672
2524
  const dateRangeStr = JSON.stringify({
2673
2525
  start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
@@ -2678,6 +2530,12 @@ var Observability = class extends BaseResource {
2678
2530
  const queryString = searchParams.toString();
2679
2531
  return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2680
2532
  }
2533
+ score(params) {
2534
+ return this.request(`/api/observability/traces/score`, {
2535
+ method: "POST",
2536
+ body: { ...params }
2537
+ });
2538
+ }
2681
2539
  };
2682
2540
 
2683
2541
  // src/resources/network-memory-thread.ts
@@ -2744,7 +2602,7 @@ var NetworkMemoryThread = class extends BaseResource {
2744
2602
  };
2745
2603
 
2746
2604
  // src/resources/vNextNetwork.ts
2747
- var RECORD_SEPARATOR4 = "";
2605
+ var RECORD_SEPARATOR3 = "";
2748
2606
  var VNextNetwork = class extends BaseResource {
2749
2607
  constructor(options, networkId) {
2750
2608
  super(options);
@@ -2752,10 +2610,11 @@ var VNextNetwork = class extends BaseResource {
2752
2610
  }
2753
2611
  /**
2754
2612
  * Retrieves details about the network
2613
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2755
2614
  * @returns Promise containing vNext network details
2756
2615
  */
2757
- details() {
2758
- return this.request(`/api/networks/v-next/${this.networkId}`);
2616
+ details(runtimeContext) {
2617
+ return this.request(`/api/networks/v-next/${this.networkId}${runtimeContextQueryString(runtimeContext)}`);
2759
2618
  }
2760
2619
  /**
2761
2620
  * Generates a response from the v-next network
@@ -2796,7 +2655,7 @@ var VNextNetwork = class extends BaseResource {
2796
2655
  if (done && !value) continue;
2797
2656
  try {
2798
2657
  const decoded = value ? new TextDecoder().decode(value) : "";
2799
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
2658
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2800
2659
  buffer = chunks.pop() || "";
2801
2660
  for (const chunk of chunks) {
2802
2661
  if (chunk) {
@@ -2890,25 +2749,17 @@ var MastraClient = class extends BaseResource {
2890
2749
  }
2891
2750
  /**
2892
2751
  * Retrieves all available agents
2752
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2893
2753
  * @returns Promise containing map of agent IDs to agent details
2894
2754
  */
2895
- getAgents() {
2896
- return this.request("/api/agents");
2897
- }
2898
- async getAGUI({ resourceId }) {
2899
- const agents = await this.getAgents();
2900
- return Object.entries(agents).reduce(
2901
- (acc, [agentId]) => {
2902
- const agent = this.getAgent(agentId);
2903
- acc[agentId] = new AGUIAdapter({
2904
- agentId,
2905
- agent,
2906
- resourceId
2907
- });
2908
- return acc;
2909
- },
2910
- {}
2911
- );
2755
+ getAgents(runtimeContext) {
2756
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2757
+ const searchParams = new URLSearchParams();
2758
+ if (runtimeContextParam) {
2759
+ searchParams.set("runtimeContext", runtimeContextParam);
2760
+ }
2761
+ const queryString = searchParams.toString();
2762
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
2912
2763
  }
2913
2764
  /**
2914
2765
  * Gets an agent instance by ID
@@ -2926,6 +2777,14 @@ var MastraClient = class extends BaseResource {
2926
2777
  getMemoryThreads(params) {
2927
2778
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
2928
2779
  }
2780
+ /**
2781
+ * Retrieves memory config for a resource
2782
+ * @param params - Parameters containing the resource ID
2783
+ * @returns Promise containing array of memory threads
2784
+ */
2785
+ getMemoryConfig(params) {
2786
+ return this.request(`/api/memory/config?agentId=${params.agentId}`);
2787
+ }
2929
2788
  /**
2930
2789
  * Creates a new memory thread
2931
2790
  * @param params - Parameters for creating the memory thread
@@ -2942,6 +2801,24 @@ var MastraClient = class extends BaseResource {
2942
2801
  getMemoryThread(threadId, agentId) {
2943
2802
  return new MemoryThread(this.options, threadId, agentId);
2944
2803
  }
2804
+ getThreadMessages(threadId, opts = {}) {
2805
+ let url = "";
2806
+ if (opts.agentId) {
2807
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}`;
2808
+ } else if (opts.networkId) {
2809
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}`;
2810
+ }
2811
+ return this.request(url);
2812
+ }
2813
+ deleteThread(threadId, opts = {}) {
2814
+ let url = "";
2815
+ if (opts.agentId) {
2816
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}`;
2817
+ } else if (opts.networkId) {
2818
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}`;
2819
+ }
2820
+ return this.request(url, { method: "DELETE" });
2821
+ }
2945
2822
  /**
2946
2823
  * Saves messages to memory
2947
2824
  * @param params - Parameters containing messages to save
@@ -3004,10 +2881,17 @@ var MastraClient = class extends BaseResource {
3004
2881
  }
3005
2882
  /**
3006
2883
  * Retrieves all available tools
2884
+ * @param runtimeContext - Optional runtime context to pass as query parameter
3007
2885
  * @returns Promise containing map of tool IDs to tool details
3008
2886
  */
3009
- getTools() {
3010
- return this.request("/api/tools");
2887
+ getTools(runtimeContext) {
2888
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2889
+ const searchParams = new URLSearchParams();
2890
+ if (runtimeContextParam) {
2891
+ searchParams.set("runtimeContext", runtimeContextParam);
2892
+ }
2893
+ const queryString = searchParams.toString();
2894
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
3011
2895
  }
3012
2896
  /**
3013
2897
  * Gets a tool instance by ID
@@ -3017,27 +2901,19 @@ var MastraClient = class extends BaseResource {
3017
2901
  getTool(toolId) {
3018
2902
  return new Tool(this.options, toolId);
3019
2903
  }
3020
- /**
3021
- * Retrieves all available legacy workflows
3022
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
3023
- */
3024
- getLegacyWorkflows() {
3025
- return this.request("/api/workflows/legacy");
3026
- }
3027
- /**
3028
- * Gets a legacy workflow instance by ID
3029
- * @param workflowId - ID of the legacy workflow to retrieve
3030
- * @returns Legacy Workflow instance
3031
- */
3032
- getLegacyWorkflow(workflowId) {
3033
- return new LegacyWorkflow(this.options, workflowId);
3034
- }
3035
2904
  /**
3036
2905
  * Retrieves all available workflows
2906
+ * @param runtimeContext - Optional runtime context to pass as query parameter
3037
2907
  * @returns Promise containing map of workflow IDs to workflow details
3038
2908
  */
3039
- getWorkflows() {
3040
- return this.request("/api/workflows");
2909
+ getWorkflows(runtimeContext) {
2910
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2911
+ const searchParams = new URLSearchParams();
2912
+ if (runtimeContextParam) {
2913
+ searchParams.set("runtimeContext", runtimeContextParam);
2914
+ }
2915
+ const queryString = searchParams.toString();
2916
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
3041
2917
  }
3042
2918
  /**
3043
2919
  * Gets a workflow instance by ID
@@ -3205,13 +3081,6 @@ var MastraClient = class extends BaseResource {
3205
3081
  return this.request(`/api/telemetry`);
3206
3082
  }
3207
3083
  }
3208
- /**
3209
- * Retrieves all available networks
3210
- * @returns Promise containing map of network IDs to network details
3211
- */
3212
- getNetworks() {
3213
- return this.request("/api/networks");
3214
- }
3215
3084
  /**
3216
3085
  * Retrieves all available vNext networks
3217
3086
  * @returns Promise containing map of vNext network IDs to vNext network details
@@ -3219,14 +3088,6 @@ var MastraClient = class extends BaseResource {
3219
3088
  getVNextNetworks() {
3220
3089
  return this.request("/api/networks/v-next");
3221
3090
  }
3222
- /**
3223
- * Gets a network instance by ID
3224
- * @param networkId - ID of the network to retrieve
3225
- * @returns Network instance
3226
- */
3227
- getNetwork(networkId) {
3228
- return new Network(this.options, networkId);
3229
- }
3230
3091
  /**
3231
3092
  * Gets a vNext network instance by ID
3232
3093
  * @param networkId - ID of the vNext network to retrieve
@@ -3417,8 +3278,30 @@ var MastraClient = class extends BaseResource {
3417
3278
  getAITraces(params) {
3418
3279
  return this.observability.getTraces(params);
3419
3280
  }
3281
+ score(params) {
3282
+ return this.observability.score(params);
3283
+ }
3420
3284
  };
3421
3285
 
3422
- export { MastraClient };
3286
+ // src/tools.ts
3287
+ var ClientTool = class {
3288
+ id;
3289
+ description;
3290
+ inputSchema;
3291
+ outputSchema;
3292
+ execute;
3293
+ constructor(opts) {
3294
+ this.id = opts.id;
3295
+ this.description = opts.description;
3296
+ this.inputSchema = opts.inputSchema;
3297
+ this.outputSchema = opts.outputSchema;
3298
+ this.execute = opts.execute;
3299
+ }
3300
+ };
3301
+ function createTool(opts) {
3302
+ return new ClientTool(opts);
3303
+ }
3304
+
3305
+ export { ClientTool, MastraClient, createTool };
3423
3306
  //# sourceMappingURL=index.js.map
3424
3307
  //# sourceMappingURL=index.js.map