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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +511 -35
  2. package/README.md +6 -10
  3. package/dist/client.d.ts +37 -43
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/index.cjs +670 -797
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +669 -798
  10. package/dist/index.js.map +1 -1
  11. package/dist/resources/agent-builder.d.ts +14 -2
  12. package/dist/resources/agent-builder.d.ts.map +1 -1
  13. package/dist/resources/agent.d.ts +66 -37
  14. package/dist/resources/agent.d.ts.map +1 -1
  15. package/dist/resources/index.d.ts +0 -2
  16. package/dist/resources/index.d.ts.map +1 -1
  17. package/dist/resources/mcp-tool.d.ts +2 -1
  18. package/dist/resources/mcp-tool.d.ts.map +1 -1
  19. package/dist/resources/observability.d.ts +17 -1
  20. package/dist/resources/observability.d.ts.map +1 -1
  21. package/dist/resources/tool.d.ts +2 -1
  22. package/dist/resources/tool.d.ts.map +1 -1
  23. package/dist/resources/vector.d.ts +5 -2
  24. package/dist/resources/vector.d.ts.map +1 -1
  25. package/dist/resources/workflow.d.ts +128 -13
  26. package/dist/resources/workflow.d.ts.map +1 -1
  27. package/dist/tools.d.ts +22 -0
  28. package/dist/tools.d.ts.map +1 -0
  29. package/dist/types.d.ts +66 -64
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/utils/index.d.ts +2 -0
  32. package/dist/utils/index.d.ts.map +1 -1
  33. package/dist/utils/process-mastra-stream.d.ts +5 -1
  34. package/dist/utils/process-mastra-stream.d.ts.map +1 -1
  35. package/package.json +8 -11
  36. package/dist/adapters/agui.d.ts +0 -23
  37. package/dist/adapters/agui.d.ts.map +0 -1
  38. package/dist/resources/legacy-workflow.d.ts +0 -87
  39. package/dist/resources/legacy-workflow.d.ts.map +0 -1
  40. package/dist/resources/network.d.ts +0 -30
  41. package/dist/resources/network.d.ts.map +0 -1
  42. package/dist/resources/vNextNetwork.d.ts +0 -42
  43. package/dist/resources/vNextNetwork.d.ts.map +0 -1
package/dist/index.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,16 +311,11 @@ 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}`);
484
- }
485
- async generate(params) {
486
- 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."
488
- );
489
- return this.generateLegacy(params);
317
+ details(runtimeContext) {
318
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
490
319
  }
491
320
  async generateLegacy(params) {
492
321
  const processedParams = {
@@ -519,7 +348,9 @@ var Agent = class extends BaseResource {
519
348
  resourceId,
520
349
  threadId,
521
350
  runtimeContext,
522
- tracingContext: { currentSpan: void 0 }
351
+ tracingContext: { currentSpan: void 0 },
352
+ suspend: async () => {
353
+ }
523
354
  },
524
355
  {
525
356
  messages: response.messages,
@@ -527,10 +358,6 @@ var Agent = class extends BaseResource {
527
358
  }
528
359
  );
529
360
  const updatedMessages = [
530
- {
531
- role: "user",
532
- content: params.messages
533
- },
534
361
  ...response.response.messages,
535
362
  {
536
363
  role: "tool",
@@ -553,16 +380,29 @@ var Agent = class extends BaseResource {
553
380
  }
554
381
  return response;
555
382
  }
556
- async generateVNext(params) {
383
+ async generate(messagesOrParams, options) {
384
+ let params;
385
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
386
+ params = messagesOrParams;
387
+ } else {
388
+ params = {
389
+ messages: messagesOrParams,
390
+ ...options
391
+ };
392
+ }
557
393
  const processedParams = {
558
394
  ...params,
559
395
  output: params.output ? zodToJsonSchema(params.output) : void 0,
560
396
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
561
- clientTools: processClientTools(params.clientTools)
397
+ clientTools: processClientTools(params.clientTools),
398
+ structuredOutput: params.structuredOutput ? {
399
+ ...params.structuredOutput,
400
+ schema: zodToJsonSchema(params.structuredOutput.schema)
401
+ } : void 0
562
402
  };
563
403
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
564
404
  const response = await this.request(
565
- `/api/agents/${this.agentId}/generate/vnext`,
405
+ `/api/agents/${this.agentId}/generate`,
566
406
  {
567
407
  method: "POST",
568
408
  body: processedParams
@@ -576,7 +416,7 @@ var Agent = class extends BaseResource {
576
416
  resourceId,
577
417
  threadId,
578
418
  runtimeContext,
579
- respondFn: this.generateVNext.bind(this)
419
+ respondFn: this.generate.bind(this)
580
420
  });
581
421
  }
582
422
  return response;
@@ -843,17 +683,6 @@ var Agent = class extends BaseResource {
843
683
  });
844
684
  onFinish?.({ message, finishReason, usage });
845
685
  }
846
- /**
847
- * Streams a response from the agent
848
- * @param params - Stream parameters including prompt
849
- * @returns Promise containing the enhanced Response object with processDataStream method
850
- */
851
- async stream(params) {
852
- 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."
854
- );
855
- return this.streamLegacy(params);
856
- }
857
686
  /**
858
687
  * Streams a response from the agent
859
688
  * @param params - Stream parameters including prompt
@@ -955,6 +784,14 @@ var Agent = class extends BaseResource {
955
784
  // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
956
785
  onChunk: async (chunk) => {
957
786
  switch (chunk.type) {
787
+ case "tripwire": {
788
+ message.parts.push({
789
+ type: "text",
790
+ text: chunk.payload.tripwireReason
791
+ });
792
+ execUpdate();
793
+ break;
794
+ }
958
795
  case "step-start": {
959
796
  if (!replaceLastMessage) {
960
797
  message.id = chunk.payload.messageId;
@@ -1063,7 +900,7 @@ var Agent = class extends BaseResource {
1063
900
  step,
1064
901
  toolCallId: chunk.payload.toolCallId,
1065
902
  toolName: chunk.payload.toolName,
1066
- args: void 0
903
+ args: chunk.payload.args
1067
904
  };
1068
905
  message.toolInvocations.push(invocation);
1069
906
  updateToolInvocationPart(chunk.payload.toolCallId, invocation);
@@ -1117,14 +954,14 @@ var Agent = class extends BaseResource {
1117
954
  }
1118
955
  case "step-finish": {
1119
956
  step += 1;
1120
- currentTextPart = chunk.payload.isContinued ? currentTextPart : void 0;
957
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
1121
958
  currentReasoningPart = void 0;
1122
959
  currentReasoningTextDetail = void 0;
1123
960
  execUpdate();
1124
961
  break;
1125
962
  }
1126
963
  case "finish": {
1127
- finishReason = chunk.payload.finishReason;
964
+ finishReason = chunk.payload.stepResult.reason;
1128
965
  if (chunk.payload.usage != null) {
1129
966
  usage = chunk.payload.usage;
1130
967
  }
@@ -1136,7 +973,7 @@ var Agent = class extends BaseResource {
1136
973
  onFinish?.({ message, finishReason, usage });
1137
974
  }
1138
975
  async processStreamResponse_vNext(processedParams, writable) {
1139
- const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
976
+ const response = await this.request(`/api/agents/${this.agentId}/stream`, {
1140
977
  method: "POST",
1141
978
  body: processedParams,
1142
979
  stream: true
@@ -1148,9 +985,27 @@ var Agent = class extends BaseResource {
1148
985
  let toolCalls = [];
1149
986
  let messages = [];
1150
987
  const [streamForWritable, streamForProcessing] = response.body.tee();
1151
- streamForWritable.pipeTo(writable, {
1152
- preventClose: true
1153
- }).catch((error) => {
988
+ streamForWritable.pipeTo(
989
+ new WritableStream({
990
+ async write(chunk) {
991
+ let writer;
992
+ try {
993
+ writer = writable.getWriter();
994
+ const text = new TextDecoder().decode(chunk);
995
+ const lines = text.split("\n\n");
996
+ const readableLines = lines.filter((line) => line !== "[DONE]").join("\n\n");
997
+ await writer.write(new TextEncoder().encode(readableLines));
998
+ } catch {
999
+ await writer?.write(chunk);
1000
+ } finally {
1001
+ writer?.releaseLock();
1002
+ }
1003
+ }
1004
+ }),
1005
+ {
1006
+ preventClose: true
1007
+ }
1008
+ ).catch((error) => {
1154
1009
  console.error("Error piping to writable stream:", error);
1155
1010
  });
1156
1011
  this.processChatResponse_vNext({
@@ -1169,9 +1024,11 @@ var Agent = class extends BaseResource {
1169
1024
  if (toolCall) {
1170
1025
  toolCalls.push(toolCall);
1171
1026
  }
1027
+ let shouldExecuteClientTool = false;
1172
1028
  for (const toolCall2 of toolCalls) {
1173
1029
  const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1174
1030
  if (clientTool && clientTool.execute) {
1031
+ shouldExecuteClientTool = true;
1175
1032
  const result = await clientTool.execute(
1176
1033
  {
1177
1034
  context: toolCall2?.args,
@@ -1180,14 +1037,17 @@ var Agent = class extends BaseResource {
1180
1037
  threadId: processedParams.threadId,
1181
1038
  runtimeContext: processedParams.runtimeContext,
1182
1039
  // TODO: Pass proper tracing context when client-js supports tracing
1183
- tracingContext: { currentSpan: void 0 }
1040
+ tracingContext: { currentSpan: void 0 },
1041
+ suspend: async () => {
1042
+ }
1184
1043
  },
1185
1044
  {
1186
1045
  messages: response.messages,
1187
1046
  toolCallId: toolCall2?.toolCallId
1188
1047
  }
1189
1048
  );
1190
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1049
+ const lastMessageRaw = messages[messages.length - 1];
1050
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1191
1051
  const toolInvocationPart = lastMessage?.parts?.find(
1192
1052
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1193
1053
  );
@@ -1205,25 +1065,11 @@ var Agent = class extends BaseResource {
1205
1065
  toolInvocation.state = "result";
1206
1066
  toolInvocation.result = result;
1207
1067
  }
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];
1068
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1223
1069
  this.processStreamResponse_vNext(
1224
1070
  {
1225
1071
  ...processedParams,
1226
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1072
+ messages: updatedMessages
1227
1073
  },
1228
1074
  writable
1229
1075
  ).catch((error) => {
@@ -1231,6 +1077,11 @@ var Agent = class extends BaseResource {
1231
1077
  });
1232
1078
  }
1233
1079
  }
1080
+ if (!shouldExecuteClientTool) {
1081
+ setTimeout(() => {
1082
+ writable.close();
1083
+ }, 0);
1084
+ }
1234
1085
  } else {
1235
1086
  setTimeout(() => {
1236
1087
  writable.close();
@@ -1246,12 +1097,49 @@ var Agent = class extends BaseResource {
1246
1097
  }
1247
1098
  return response;
1248
1099
  }
1249
- async streamVNext(params) {
1100
+ async network(params) {
1101
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1102
+ method: "POST",
1103
+ body: params,
1104
+ stream: true
1105
+ });
1106
+ if (!response.body) {
1107
+ throw new Error("No response body");
1108
+ }
1109
+ const streamResponse = new Response(response.body, {
1110
+ status: response.status,
1111
+ statusText: response.statusText,
1112
+ headers: response.headers
1113
+ });
1114
+ streamResponse.processDataStream = async ({
1115
+ onChunk
1116
+ }) => {
1117
+ await processMastraNetworkStream({
1118
+ stream: streamResponse.body,
1119
+ onChunk
1120
+ });
1121
+ };
1122
+ return streamResponse;
1123
+ }
1124
+ async stream(messagesOrParams, options) {
1125
+ let params;
1126
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1127
+ params = messagesOrParams;
1128
+ } else {
1129
+ params = {
1130
+ messages: messagesOrParams,
1131
+ ...options
1132
+ };
1133
+ }
1250
1134
  const processedParams = {
1251
1135
  ...params,
1252
1136
  output: params.output ? zodToJsonSchema(params.output) : void 0,
1253
1137
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1254
- clientTools: processClientTools(params.clientTools)
1138
+ clientTools: processClientTools(params.clientTools),
1139
+ structuredOutput: params.structuredOutput ? {
1140
+ ...params.structuredOutput,
1141
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1142
+ } : void 0
1255
1143
  };
1256
1144
  const { readable, writable } = new TransformStream();
1257
1145
  const response = await this.processStreamResponse_vNext(processedParams, writable);
@@ -1318,7 +1206,9 @@ var Agent = class extends BaseResource {
1318
1206
  threadId: processedParams.threadId,
1319
1207
  runtimeContext: processedParams.runtimeContext,
1320
1208
  // TODO: Pass proper tracing context when client-js supports tracing
1321
- tracingContext: { currentSpan: void 0 }
1209
+ tracingContext: { currentSpan: void 0 },
1210
+ suspend: async () => {
1211
+ }
1322
1212
  },
1323
1213
  {
1324
1214
  messages: response.messages,
@@ -1356,12 +1246,10 @@ var Agent = class extends BaseResource {
1356
1246
  } finally {
1357
1247
  writer.releaseLock();
1358
1248
  }
1359
- const originalMessages = processedParams.messages;
1360
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1361
1249
  this.processStreamResponse(
1362
1250
  {
1363
1251
  ...processedParams,
1364
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1252
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1365
1253
  },
1366
1254
  writable
1367
1255
  ).catch((error) => {
@@ -1387,10 +1275,11 @@ var Agent = class extends BaseResource {
1387
1275
  /**
1388
1276
  * Gets details about a specific tool available to the agent
1389
1277
  * @param toolId - ID of the tool to retrieve
1278
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1390
1279
  * @returns Promise containing tool details
1391
1280
  */
1392
- getTool(toolId) {
1393
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1281
+ getTool(toolId, runtimeContext) {
1282
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
1394
1283
  }
1395
1284
  /**
1396
1285
  * Executes a tool for the agent
@@ -1401,7 +1290,7 @@ var Agent = class extends BaseResource {
1401
1290
  executeTool(toolId, params) {
1402
1291
  const body = {
1403
1292
  data: params.data,
1404
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1293
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1405
1294
  };
1406
1295
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1407
1296
  method: "POST",
@@ -1410,17 +1299,19 @@ var Agent = class extends BaseResource {
1410
1299
  }
1411
1300
  /**
1412
1301
  * Retrieves evaluation results for the agent
1302
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1413
1303
  * @returns Promise containing agent evaluations
1414
1304
  */
1415
- evals() {
1416
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1305
+ evals(runtimeContext) {
1306
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
1417
1307
  }
1418
1308
  /**
1419
1309
  * Retrieves live evaluation results for the agent
1310
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1420
1311
  * @returns Promise containing live agent evaluations
1421
1312
  */
1422
- liveEvals() {
1423
- return this.request(`/api/agents/${this.agentId}/evals/live`);
1313
+ liveEvals(runtimeContext) {
1314
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
1424
1315
  }
1425
1316
  /**
1426
1317
  * Updates the model for the agent
@@ -1433,61 +1324,33 @@ var Agent = class extends BaseResource {
1433
1324
  body: params
1434
1325
  });
1435
1326
  }
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
1327
  /**
1450
- * Generates a response from the agent
1451
- * @param params - Generation parameters including prompt
1452
- * @returns Promise containing the generated response
1328
+ * Updates the model for the agent in the model list
1329
+ * @param params - Parameters for updating the model
1330
+ * @returns Promise containing the updated model
1453
1331
  */
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`, {
1332
+ updateModelInModelList({ modelConfigId, ...params }) {
1333
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
1461
1334
  method: "POST",
1462
- body: processedParams
1335
+ body: params
1463
1336
  });
1464
1337
  }
1465
1338
  /**
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
1339
+ * Reorders the models for the agent
1340
+ * @param params - Parameters for reordering the model list
1341
+ * @returns Promise containing the updated model list
1469
1342
  */
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`, {
1343
+ reorderModelList(params) {
1344
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
1477
1345
  method: "POST",
1478
- body: processedParams,
1479
- stream: true
1346
+ body: params
1480
1347
  });
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;
1348
+ }
1349
+ async generateVNext(_messagesOrParams, _options) {
1350
+ throw new Error("generateVNext has been renamed to generate. Please use generate instead.");
1351
+ }
1352
+ async streamVNext(_messagesOrParams, _options) {
1353
+ throw new Error("streamVNext has been renamed to stream. Please use stream instead.");
1491
1354
  }
1492
1355
  };
1493
1356
 
@@ -1578,10 +1441,13 @@ var Vector = class extends BaseResource {
1578
1441
  /**
1579
1442
  * Retrieves details about a specific vector index
1580
1443
  * @param indexName - Name of the index to get details for
1444
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1581
1445
  * @returns Promise containing vector index details
1582
1446
  */
1583
- details(indexName) {
1584
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1447
+ details(indexName, runtimeContext) {
1448
+ return this.request(
1449
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1450
+ );
1585
1451
  }
1586
1452
  /**
1587
1453
  * Deletes a vector index
@@ -1595,10 +1461,11 @@ var Vector = class extends BaseResource {
1595
1461
  }
1596
1462
  /**
1597
1463
  * Retrieves a list of all available indexes
1464
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1598
1465
  * @returns Promise containing array of index names
1599
1466
  */
1600
- getIndexes() {
1601
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1467
+ getIndexes(runtimeContext) {
1468
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
1602
1469
  }
1603
1470
  /**
1604
1471
  * Creates a new vector index
@@ -1635,127 +1502,54 @@ var Vector = class extends BaseResource {
1635
1502
  }
1636
1503
  };
1637
1504
 
1638
- // src/resources/legacy-workflow.ts
1639
- var RECORD_SEPARATOR = "";
1640
- var LegacyWorkflow = class extends BaseResource {
1641
- constructor(options, workflowId) {
1505
+ // src/resources/tool.ts
1506
+ var Tool = class extends BaseResource {
1507
+ constructor(options, toolId) {
1642
1508
  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}`);
1509
+ this.toolId = toolId;
1651
1510
  }
1652
1511
  /**
1653
- * Retrieves all runs for a legacy workflow
1654
- * @param params - Parameters for filtering runs
1655
- * @returns Promise containing legacy workflow runs array
1512
+ * Retrieves details about the tool
1513
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1514
+ * @returns Promise containing tool details including description and schemas
1656
1515
  */
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
- }
1516
+ details(runtimeContext) {
1517
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1679
1518
  }
1680
1519
  /**
1681
- * Creates a new legacy workflow run
1682
- * @returns Promise containing the generated run ID
1520
+ * Executes the tool with the provided parameters
1521
+ * @param params - Parameters required for tool execution
1522
+ * @returns Promise containing the tool execution results
1683
1523
  */
1684
- createRun(params) {
1685
- const searchParams = new URLSearchParams();
1686
- if (!!params?.runId) {
1687
- searchParams.set("runId", params.runId);
1524
+ execute(params) {
1525
+ const url = new URLSearchParams();
1526
+ if (params.runId) {
1527
+ url.set("runId", params.runId);
1688
1528
  }
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}`, {
1529
+ const body = {
1530
+ data: params.data,
1531
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1532
+ };
1533
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1700
1534
  method: "POST",
1701
- body: params?.triggerData
1535
+ body
1702
1536
  });
1703
1537
  }
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
- });
1538
+ };
1539
+
1540
+ // src/resources/workflow.ts
1541
+ var RECORD_SEPARATOR = "";
1542
+ var Workflow = class extends BaseResource {
1543
+ constructor(options, workflowId) {
1544
+ super(options);
1545
+ this.workflowId = workflowId;
1723
1546
  }
1724
1547
  /**
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
1548
+ * Creates an async generator that processes a readable stream and yields workflow records
1549
+ * separated by the Record Separator character (\x1E)
1550
+ *
1551
+ * @param stream - The readable stream to process
1552
+ * @returns An async generator that yields parsed records
1759
1553
  */
1760
1554
  async *streamProcessor(stream) {
1761
1555
  const reader = stream.getReader();
@@ -1795,126 +1589,22 @@ var LegacyWorkflow = class extends BaseResource {
1795
1589
  });
1796
1590
  }
1797
1591
  }
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
- // src/resources/tool.ts
1820
- var Tool = class extends BaseResource {
1821
- constructor(options, toolId) {
1822
- super(options);
1823
- this.toolId = toolId;
1824
- }
1825
- /**
1826
- * Retrieves details about the tool
1827
- * @returns Promise containing tool details including description and schemas
1828
- */
1829
- details() {
1830
- return this.request(`/api/tools/${this.toolId}`);
1831
- }
1832
- /**
1833
- * Executes the tool with the provided parameters
1834
- * @param params - Parameters required for tool execution
1835
- * @returns Promise containing the tool execution results
1836
- */
1837
- execute(params) {
1838
- const url = new URLSearchParams();
1839
- if (params.runId) {
1840
- url.set("runId", params.runId);
1841
- }
1842
- const body = {
1843
- data: params.data,
1844
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1845
- };
1846
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1847
- method: "POST",
1848
- body
1849
- });
1850
- }
1851
- };
1852
-
1853
- // src/resources/workflow.ts
1854
- var RECORD_SEPARATOR2 = "";
1855
- var Workflow = class extends BaseResource {
1856
- constructor(options, workflowId) {
1857
- super(options);
1858
- this.workflowId = workflowId;
1859
- }
1860
- /**
1861
- * Creates an async generator that processes a readable stream and yields workflow records
1862
- * separated by the Record Separator character (\x1E)
1863
- *
1864
- * @param stream - The readable stream to process
1865
- * @returns An async generator that yields parsed records
1866
- */
1867
- async *streamProcessor(stream) {
1868
- const reader = stream.getReader();
1869
- let doneReading = false;
1870
- let buffer = "";
1871
- try {
1872
- while (!doneReading) {
1873
- const { done, value } = await reader.read();
1874
- doneReading = done;
1875
- if (done && !value) continue;
1876
- try {
1877
- const decoded = value ? new TextDecoder().decode(value) : "";
1878
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1879
- buffer = chunks.pop() || "";
1880
- for (const chunk of chunks) {
1881
- if (chunk) {
1882
- if (typeof chunk === "string") {
1883
- try {
1884
- const parsedChunk = JSON.parse(chunk);
1885
- yield parsedChunk;
1886
- } catch {
1887
- }
1888
- }
1889
- }
1890
- }
1891
- } catch {
1892
- }
1893
- }
1894
- if (buffer) {
1895
- try {
1896
- yield JSON.parse(buffer);
1897
- } catch {
1898
- }
1899
- }
1900
- } finally {
1901
- reader.cancel().catch(() => {
1902
- });
1903
- }
1904
- }
1905
1592
  /**
1906
1593
  * Retrieves details about the workflow
1594
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1907
1595
  * @returns Promise containing workflow details including steps and graphs
1908
1596
  */
1909
- details() {
1910
- return this.request(`/api/workflows/${this.workflowId}`);
1597
+ details(runtimeContext) {
1598
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1911
1599
  }
1912
1600
  /**
1913
1601
  * Retrieves all runs for a workflow
1914
1602
  * @param params - Parameters for filtering runs
1603
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1915
1604
  * @returns Promise containing workflow runs array
1916
1605
  */
1917
- runs(params) {
1606
+ runs(params, runtimeContext) {
1607
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1918
1608
  const searchParams = new URLSearchParams();
1919
1609
  if (params?.fromDate) {
1920
1610
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1931,6 +1621,9 @@ var Workflow = class extends BaseResource {
1931
1621
  if (params?.resourceId) {
1932
1622
  searchParams.set("resourceId", params.resourceId);
1933
1623
  }
1624
+ if (runtimeContextParam) {
1625
+ searchParams.set("runtimeContext", runtimeContextParam);
1626
+ }
1934
1627
  if (searchParams.size) {
1935
1628
  return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1936
1629
  } else {
@@ -1940,18 +1633,22 @@ var Workflow = class extends BaseResource {
1940
1633
  /**
1941
1634
  * Retrieves a specific workflow run by its ID
1942
1635
  * @param runId - The ID of the workflow run to retrieve
1636
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1943
1637
  * @returns Promise containing the workflow run details
1944
1638
  */
1945
- runById(runId) {
1946
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1639
+ runById(runId, runtimeContext) {
1640
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1947
1641
  }
1948
1642
  /**
1949
1643
  * Retrieves the execution result for a specific workflow run by its ID
1950
1644
  * @param runId - The ID of the workflow run to retrieve the execution result for
1645
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1951
1646
  * @returns Promise containing the workflow run execution result
1952
1647
  */
1953
- runExecutionResult(runId) {
1954
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1648
+ runExecutionResult(runId, runtimeContext) {
1649
+ return this.request(
1650
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1651
+ );
1955
1652
  }
1956
1653
  /**
1957
1654
  * Cancels a specific workflow run by its ID
@@ -1974,27 +1671,83 @@ var Workflow = class extends BaseResource {
1974
1671
  body: { event: params.event, data: params.data }
1975
1672
  });
1976
1673
  }
1674
+ /**
1675
+ * @deprecated Use createRunAsync() instead.
1676
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1677
+ */
1678
+ async createRun(_params) {
1679
+ throw new Error(
1680
+ "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."
1681
+ );
1682
+ }
1977
1683
  /**
1978
1684
  * Creates a new workflow run
1979
1685
  * @param params - Optional object containing the optional runId
1980
- * @returns Promise containing the runId of the created run
1686
+ * @returns Promise containing the runId of the created run with methods to control execution
1981
1687
  */
1982
- createRun(params) {
1688
+ async createRunAsync(params) {
1983
1689
  const searchParams = new URLSearchParams();
1984
1690
  if (!!params?.runId) {
1985
1691
  searchParams.set("runId", params.runId);
1986
1692
  }
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);
1693
+ const res = await this.request(
1694
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1695
+ {
1696
+ method: "POST"
1697
+ }
1698
+ );
1699
+ const runId = res.runId;
1700
+ return {
1701
+ runId,
1702
+ start: async (p) => {
1703
+ return this.start({
1704
+ runId,
1705
+ inputData: p.inputData,
1706
+ runtimeContext: p.runtimeContext,
1707
+ tracingOptions: p.tracingOptions
1708
+ });
1709
+ },
1710
+ startAsync: async (p) => {
1711
+ return this.startAsync({
1712
+ runId,
1713
+ inputData: p.inputData,
1714
+ runtimeContext: p.runtimeContext,
1715
+ tracingOptions: p.tracingOptions
1716
+ });
1717
+ },
1718
+ watch: async (onRecord) => {
1719
+ return this.watch({ runId }, onRecord);
1720
+ },
1721
+ stream: async (p) => {
1722
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1723
+ },
1724
+ resume: async (p) => {
1725
+ return this.resume({
1726
+ runId,
1727
+ step: p.step,
1728
+ resumeData: p.resumeData,
1729
+ runtimeContext: p.runtimeContext,
1730
+ tracingOptions: p.tracingOptions
1731
+ });
1732
+ },
1733
+ resumeAsync: async (p) => {
1734
+ return this.resumeAsync({
1735
+ runId,
1736
+ step: p.step,
1737
+ resumeData: p.resumeData,
1738
+ runtimeContext: p.runtimeContext,
1739
+ tracingOptions: p.tracingOptions
1740
+ });
1741
+ },
1742
+ resumeStreamVNext: async (p) => {
1743
+ return this.resumeStreamVNext({
1744
+ runId,
1745
+ step: p.step,
1746
+ resumeData: p.resumeData,
1747
+ runtimeContext: p.runtimeContext
1748
+ });
1749
+ }
1750
+ };
1998
1751
  }
1999
1752
  /**
2000
1753
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -2005,7 +1758,7 @@ var Workflow = class extends BaseResource {
2005
1758
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2006
1759
  return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
2007
1760
  method: "POST",
2008
- body: { inputData: params?.inputData, runtimeContext }
1761
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
2009
1762
  });
2010
1763
  }
2011
1764
  /**
@@ -2017,16 +1770,17 @@ var Workflow = class extends BaseResource {
2017
1770
  step,
2018
1771
  runId,
2019
1772
  resumeData,
1773
+ tracingOptions,
2020
1774
  ...rest
2021
1775
  }) {
2022
1776
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
2023
1777
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
2024
1778
  method: "POST",
2025
- stream: true,
2026
1779
  body: {
2027
1780
  step,
2028
1781
  resumeData,
2029
- runtimeContext
1782
+ runtimeContext,
1783
+ tracingOptions
2030
1784
  }
2031
1785
  });
2032
1786
  }
@@ -2043,7 +1797,7 @@ var Workflow = class extends BaseResource {
2043
1797
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2044
1798
  return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
2045
1799
  method: "POST",
2046
- body: { inputData: params.inputData, runtimeContext }
1800
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
2047
1801
  });
2048
1802
  }
2049
1803
  /**
@@ -2061,7 +1815,110 @@ var Workflow = class extends BaseResource {
2061
1815
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
2062
1816
  {
2063
1817
  method: "POST",
2064
- body: { inputData: params.inputData, runtimeContext },
1818
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions },
1819
+ stream: true
1820
+ }
1821
+ );
1822
+ if (!response.ok) {
1823
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1824
+ }
1825
+ if (!response.body) {
1826
+ throw new Error("Response body is null");
1827
+ }
1828
+ let failedChunk = void 0;
1829
+ const transformStream = new TransformStream({
1830
+ start() {
1831
+ },
1832
+ async transform(chunk, controller) {
1833
+ try {
1834
+ const decoded = new TextDecoder().decode(chunk);
1835
+ const chunks = decoded.split(RECORD_SEPARATOR);
1836
+ for (const chunk2 of chunks) {
1837
+ if (chunk2) {
1838
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1839
+ try {
1840
+ const parsedChunk = JSON.parse(newChunk);
1841
+ controller.enqueue(parsedChunk);
1842
+ failedChunk = void 0;
1843
+ } catch {
1844
+ failedChunk = newChunk;
1845
+ }
1846
+ }
1847
+ }
1848
+ } catch {
1849
+ }
1850
+ }
1851
+ });
1852
+ return response.body.pipeThrough(transformStream);
1853
+ }
1854
+ /**
1855
+ * Observes workflow stream for a workflow run
1856
+ * @param params - Object containing the runId
1857
+ * @returns Promise containing the workflow execution results
1858
+ */
1859
+ async observeStream(params) {
1860
+ const searchParams = new URLSearchParams();
1861
+ searchParams.set("runId", params.runId);
1862
+ const response = await this.request(
1863
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1864
+ {
1865
+ method: "POST",
1866
+ stream: true
1867
+ }
1868
+ );
1869
+ if (!response.ok) {
1870
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1871
+ }
1872
+ if (!response.body) {
1873
+ throw new Error("Response body is null");
1874
+ }
1875
+ let failedChunk = void 0;
1876
+ const transformStream = new TransformStream({
1877
+ start() {
1878
+ },
1879
+ async transform(chunk, controller) {
1880
+ try {
1881
+ const decoded = new TextDecoder().decode(chunk);
1882
+ const chunks = decoded.split(RECORD_SEPARATOR);
1883
+ for (const chunk2 of chunks) {
1884
+ if (chunk2) {
1885
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1886
+ try {
1887
+ const parsedChunk = JSON.parse(newChunk);
1888
+ controller.enqueue(parsedChunk);
1889
+ failedChunk = void 0;
1890
+ } catch {
1891
+ failedChunk = newChunk;
1892
+ }
1893
+ }
1894
+ }
1895
+ } catch {
1896
+ }
1897
+ }
1898
+ });
1899
+ return response.body.pipeThrough(transformStream);
1900
+ }
1901
+ /**
1902
+ * Starts a workflow run and returns a stream
1903
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1904
+ * @returns Promise containing the workflow execution results
1905
+ */
1906
+ async streamVNext(params) {
1907
+ const searchParams = new URLSearchParams();
1908
+ if (!!params?.runId) {
1909
+ searchParams.set("runId", params.runId);
1910
+ }
1911
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1912
+ const response = await this.request(
1913
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1914
+ {
1915
+ method: "POST",
1916
+ body: {
1917
+ inputData: params.inputData,
1918
+ runtimeContext,
1919
+ closeOnSuspend: params.closeOnSuspend,
1920
+ tracingOptions: params.tracingOptions
1921
+ },
2065
1922
  stream: true
2066
1923
  }
2067
1924
  );
@@ -2078,7 +1935,54 @@ var Workflow = class extends BaseResource {
2078
1935
  async transform(chunk, controller) {
2079
1936
  try {
2080
1937
  const decoded = new TextDecoder().decode(chunk);
2081
- const chunks = decoded.split(RECORD_SEPARATOR2);
1938
+ const chunks = decoded.split(RECORD_SEPARATOR);
1939
+ for (const chunk2 of chunks) {
1940
+ if (chunk2) {
1941
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1942
+ try {
1943
+ const parsedChunk = JSON.parse(newChunk);
1944
+ controller.enqueue(parsedChunk);
1945
+ failedChunk = void 0;
1946
+ } catch {
1947
+ failedChunk = newChunk;
1948
+ }
1949
+ }
1950
+ }
1951
+ } catch {
1952
+ }
1953
+ }
1954
+ });
1955
+ return response.body.pipeThrough(transformStream);
1956
+ }
1957
+ /**
1958
+ * Observes workflow vNext stream for a workflow run
1959
+ * @param params - Object containing the runId
1960
+ * @returns Promise containing the workflow execution results
1961
+ */
1962
+ async observeStreamVNext(params) {
1963
+ const searchParams = new URLSearchParams();
1964
+ searchParams.set("runId", params.runId);
1965
+ const response = await this.request(
1966
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
1967
+ {
1968
+ method: "POST",
1969
+ stream: true
1970
+ }
1971
+ );
1972
+ if (!response.ok) {
1973
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
1974
+ }
1975
+ if (!response.body) {
1976
+ throw new Error("Response body is null");
1977
+ }
1978
+ let failedChunk = void 0;
1979
+ const transformStream = new TransformStream({
1980
+ start() {
1981
+ },
1982
+ async transform(chunk, controller) {
1983
+ try {
1984
+ const decoded = new TextDecoder().decode(chunk);
1985
+ const chunks = decoded.split(RECORD_SEPARATOR);
2082
1986
  for (const chunk2 of chunks) {
2083
1987
  if (chunk2) {
2084
1988
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2109,10 +2013,65 @@ var Workflow = class extends BaseResource {
2109
2013
  body: {
2110
2014
  step: params.step,
2111
2015
  resumeData: params.resumeData,
2112
- runtimeContext
2016
+ runtimeContext,
2017
+ tracingOptions: params.tracingOptions
2113
2018
  }
2114
2019
  });
2115
2020
  }
2021
+ /**
2022
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2023
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2024
+ * @returns Promise containing the workflow resume results
2025
+ */
2026
+ async resumeStreamVNext(params) {
2027
+ const searchParams = new URLSearchParams();
2028
+ searchParams.set("runId", params.runId);
2029
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2030
+ const response = await this.request(
2031
+ `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
2032
+ {
2033
+ method: "POST",
2034
+ body: {
2035
+ step: params.step,
2036
+ resumeData: params.resumeData,
2037
+ runtimeContext,
2038
+ tracingOptions: params.tracingOptions
2039
+ },
2040
+ stream: true
2041
+ }
2042
+ );
2043
+ if (!response.ok) {
2044
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2045
+ }
2046
+ if (!response.body) {
2047
+ throw new Error("Response body is null");
2048
+ }
2049
+ let failedChunk = void 0;
2050
+ const transformStream = new TransformStream({
2051
+ start() {
2052
+ },
2053
+ async transform(chunk, controller) {
2054
+ try {
2055
+ const decoded = new TextDecoder().decode(chunk);
2056
+ const chunks = decoded.split(RECORD_SEPARATOR);
2057
+ for (const chunk2 of chunks) {
2058
+ if (chunk2) {
2059
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2060
+ try {
2061
+ const parsedChunk = JSON.parse(newChunk);
2062
+ controller.enqueue(parsedChunk);
2063
+ failedChunk = void 0;
2064
+ } catch {
2065
+ failedChunk = newChunk;
2066
+ }
2067
+ }
2068
+ }
2069
+ } catch {
2070
+ }
2071
+ }
2072
+ });
2073
+ return response.body.pipeThrough(transformStream);
2074
+ }
2116
2075
  /**
2117
2076
  * Watches workflow transitions in real-time
2118
2077
  * @param runId - Optional run ID to filter the watch stream
@@ -2149,7 +2108,7 @@ var Workflow = class extends BaseResource {
2149
2108
  async start(controller) {
2150
2109
  try {
2151
2110
  for await (const record of records) {
2152
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2111
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
2153
2112
  controller.enqueue(encoder.encode(json));
2154
2113
  }
2155
2114
  controller.close();
@@ -2247,10 +2206,11 @@ var MCPTool = class extends BaseResource {
2247
2206
  }
2248
2207
  /**
2249
2208
  * Retrieves details about this specific tool from the MCP server.
2209
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2250
2210
  * @returns Promise containing the tool's information (name, description, schema).
2251
2211
  */
2252
- details() {
2253
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2212
+ details(runtimeContext) {
2213
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2254
2214
  }
2255
2215
  /**
2256
2216
  * Executes this specific tool on the MCP server.
@@ -2271,7 +2231,7 @@ var MCPTool = class extends BaseResource {
2271
2231
  };
2272
2232
 
2273
2233
  // src/resources/agent-builder.ts
2274
- var RECORD_SEPARATOR3 = "";
2234
+ var RECORD_SEPARATOR2 = "";
2275
2235
  var AgentBuilder = class extends BaseResource {
2276
2236
  constructor(options, actionId) {
2277
2237
  super(options);
@@ -2306,21 +2266,27 @@ var AgentBuilder = class extends BaseResource {
2306
2266
  };
2307
2267
  }
2308
2268
  }
2269
+ /**
2270
+ * @deprecated Use createRunAsync() instead.
2271
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2272
+ */
2273
+ async createRun(_params) {
2274
+ throw new Error(
2275
+ "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."
2276
+ );
2277
+ }
2309
2278
  /**
2310
2279
  * Creates a new agent builder action run and returns the runId.
2311
2280
  * This calls `/api/agent-builder/:actionId/create-run`.
2312
2281
  */
2313
- async createRun(params, runId) {
2282
+ async createRunAsync(params) {
2314
2283
  const searchParams = new URLSearchParams();
2315
- if (runId) {
2316
- searchParams.set("runId", runId);
2284
+ if (!!params?.runId) {
2285
+ searchParams.set("runId", params.runId);
2317
2286
  }
2318
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2319
- const { runtimeContext: _, ...actionParams } = params;
2320
2287
  const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2321
2288
  return this.request(url, {
2322
- method: "POST",
2323
- body: { ...actionParams, runtimeContext }
2289
+ method: "POST"
2324
2290
  });
2325
2291
  }
2326
2292
  /**
@@ -2405,7 +2371,7 @@ var AgentBuilder = class extends BaseResource {
2405
2371
  if (done && !value) continue;
2406
2372
  try {
2407
2373
  const decoded = value ? new TextDecoder().decode(value) : "";
2408
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2374
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2409
2375
  buffer = chunks.pop() || "";
2410
2376
  for (const chunk of chunks) {
2411
2377
  if (chunk) {
@@ -2462,7 +2428,7 @@ var AgentBuilder = class extends BaseResource {
2462
2428
  async transform(chunk, controller) {
2463
2429
  try {
2464
2430
  const decoded = new TextDecoder().decode(chunk);
2465
- const chunks = decoded.split(RECORD_SEPARATOR3);
2431
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2466
2432
  for (const chunk2 of chunks) {
2467
2433
  if (chunk2) {
2468
2434
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2511,7 +2477,7 @@ var AgentBuilder = class extends BaseResource {
2511
2477
  async transform(chunk, controller) {
2512
2478
  try {
2513
2479
  const decoded = new TextDecoder().decode(chunk);
2514
- const chunks = decoded.split(RECORD_SEPARATOR3);
2480
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2515
2481
  for (const chunk2 of chunks) {
2516
2482
  if (chunk2) {
2517
2483
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -2536,8 +2502,8 @@ var AgentBuilder = class extends BaseResource {
2536
2502
  * and streams any remaining progress.
2537
2503
  * This calls `/api/agent-builder/:actionId/watch`.
2538
2504
  */
2539
- async watch({ runId }, onRecord) {
2540
- const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}`;
2505
+ async watch({ runId, eventType }, onRecord) {
2506
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2541
2507
  const response = await this.request(url, {
2542
2508
  method: "GET",
2543
2509
  stream: true
@@ -2654,7 +2620,7 @@ var Observability = class extends BaseResource {
2654
2620
  getTraces(params) {
2655
2621
  const { pagination, filters } = params;
2656
2622
  const { page, perPage, dateRange } = pagination || {};
2657
- const { name, spanType } = filters || {};
2623
+ const { name, spanType, entityId, entityType } = filters || {};
2658
2624
  const searchParams = new URLSearchParams();
2659
2625
  if (page !== void 0) {
2660
2626
  searchParams.set("page", String(page));
@@ -2668,6 +2634,10 @@ var Observability = class extends BaseResource {
2668
2634
  if (spanType !== void 0) {
2669
2635
  searchParams.set("spanType", String(spanType));
2670
2636
  }
2637
+ if (entityId && entityType) {
2638
+ searchParams.set("entityId", entityId);
2639
+ searchParams.set("entityType", entityType);
2640
+ }
2671
2641
  if (dateRange) {
2672
2642
  const dateRangeStr = JSON.stringify({
2673
2643
  start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
@@ -2678,6 +2648,31 @@ var Observability = class extends BaseResource {
2678
2648
  const queryString = searchParams.toString();
2679
2649
  return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2680
2650
  }
2651
+ /**
2652
+ * Retrieves scores by trace ID and span ID
2653
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2654
+ * @returns Promise containing scores and pagination info
2655
+ */
2656
+ getScoresBySpan(params) {
2657
+ const { traceId, spanId, page, perPage } = params;
2658
+ const searchParams = new URLSearchParams();
2659
+ if (page !== void 0) {
2660
+ searchParams.set("page", String(page));
2661
+ }
2662
+ if (perPage !== void 0) {
2663
+ searchParams.set("perPage", String(perPage));
2664
+ }
2665
+ const queryString = searchParams.toString();
2666
+ return this.request(
2667
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2668
+ );
2669
+ }
2670
+ score(params) {
2671
+ return this.request(`/api/observability/traces/score`, {
2672
+ method: "POST",
2673
+ body: { ...params }
2674
+ });
2675
+ }
2681
2676
  };
2682
2677
 
2683
2678
  // src/resources/network-memory-thread.ts
@@ -2743,144 +2738,6 @@ var NetworkMemoryThread = class extends BaseResource {
2743
2738
  }
2744
2739
  };
2745
2740
 
2746
- // src/resources/vNextNetwork.ts
2747
- var RECORD_SEPARATOR4 = "";
2748
- var VNextNetwork = class extends BaseResource {
2749
- constructor(options, networkId) {
2750
- super(options);
2751
- this.networkId = networkId;
2752
- }
2753
- /**
2754
- * Retrieves details about the network
2755
- * @returns Promise containing vNext network details
2756
- */
2757
- details() {
2758
- return this.request(`/api/networks/v-next/${this.networkId}`);
2759
- }
2760
- /**
2761
- * Generates a response from the v-next network
2762
- * @param params - Generation parameters including message
2763
- * @returns Promise containing the generated response
2764
- */
2765
- generate(params) {
2766
- return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
2767
- method: "POST",
2768
- body: {
2769
- ...params,
2770
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2771
- }
2772
- });
2773
- }
2774
- /**
2775
- * Generates a response from the v-next network using multiple primitives
2776
- * @param params - Generation parameters including message
2777
- * @returns Promise containing the generated response
2778
- */
2779
- loop(params) {
2780
- return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
2781
- method: "POST",
2782
- body: {
2783
- ...params,
2784
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2785
- }
2786
- });
2787
- }
2788
- async *streamProcessor(stream) {
2789
- const reader = stream.getReader();
2790
- let doneReading = false;
2791
- let buffer = "";
2792
- try {
2793
- while (!doneReading) {
2794
- const { done, value } = await reader.read();
2795
- doneReading = done;
2796
- if (done && !value) continue;
2797
- try {
2798
- const decoded = value ? new TextDecoder().decode(value) : "";
2799
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
2800
- buffer = chunks.pop() || "";
2801
- for (const chunk of chunks) {
2802
- if (chunk) {
2803
- if (typeof chunk === "string") {
2804
- try {
2805
- const parsedChunk = JSON.parse(chunk);
2806
- yield parsedChunk;
2807
- } catch {
2808
- }
2809
- }
2810
- }
2811
- }
2812
- } catch {
2813
- }
2814
- }
2815
- if (buffer) {
2816
- try {
2817
- yield JSON.parse(buffer);
2818
- } catch {
2819
- }
2820
- }
2821
- } finally {
2822
- reader.cancel().catch(() => {
2823
- });
2824
- }
2825
- }
2826
- /**
2827
- * Streams a response from the v-next network
2828
- * @param params - Stream parameters including message
2829
- * @returns Promise containing the results
2830
- */
2831
- async stream(params, onRecord) {
2832
- const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
2833
- method: "POST",
2834
- body: {
2835
- ...params,
2836
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2837
- },
2838
- stream: true
2839
- });
2840
- if (!response.ok) {
2841
- throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2842
- }
2843
- if (!response.body) {
2844
- throw new Error("Response body is null");
2845
- }
2846
- for await (const record of this.streamProcessor(response.body)) {
2847
- if (typeof record === "string") {
2848
- onRecord(JSON.parse(record));
2849
- } else {
2850
- onRecord(record);
2851
- }
2852
- }
2853
- }
2854
- /**
2855
- * Streams a response from the v-next network loop
2856
- * @param params - Stream parameters including message
2857
- * @returns Promise containing the results
2858
- */
2859
- async loopStream(params, onRecord) {
2860
- const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
2861
- method: "POST",
2862
- body: {
2863
- ...params,
2864
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2865
- },
2866
- stream: true
2867
- });
2868
- if (!response.ok) {
2869
- throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2870
- }
2871
- if (!response.body) {
2872
- throw new Error("Response body is null");
2873
- }
2874
- for await (const record of this.streamProcessor(response.body)) {
2875
- if (typeof record === "string") {
2876
- onRecord(JSON.parse(record));
2877
- } else {
2878
- onRecord(record);
2879
- }
2880
- }
2881
- }
2882
- };
2883
-
2884
2741
  // src/client.ts
2885
2742
  var MastraClient = class extends BaseResource {
2886
2743
  observability;
@@ -2890,25 +2747,17 @@ var MastraClient = class extends BaseResource {
2890
2747
  }
2891
2748
  /**
2892
2749
  * Retrieves all available agents
2750
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2893
2751
  * @returns Promise containing map of agent IDs to agent details
2894
2752
  */
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
- );
2753
+ getAgents(runtimeContext) {
2754
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2755
+ const searchParams = new URLSearchParams();
2756
+ if (runtimeContextParam) {
2757
+ searchParams.set("runtimeContext", runtimeContextParam);
2758
+ }
2759
+ const queryString = searchParams.toString();
2760
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
2912
2761
  }
2913
2762
  /**
2914
2763
  * Gets an agent instance by ID
@@ -2926,6 +2775,14 @@ var MastraClient = class extends BaseResource {
2926
2775
  getMemoryThreads(params) {
2927
2776
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
2928
2777
  }
2778
+ /**
2779
+ * Retrieves memory config for a resource
2780
+ * @param params - Parameters containing the resource ID
2781
+ * @returns Promise containing array of memory threads
2782
+ */
2783
+ getMemoryConfig(params) {
2784
+ return this.request(`/api/memory/config?agentId=${params.agentId}`);
2785
+ }
2929
2786
  /**
2930
2787
  * Creates a new memory thread
2931
2788
  * @param params - Parameters for creating the memory thread
@@ -2942,6 +2799,24 @@ var MastraClient = class extends BaseResource {
2942
2799
  getMemoryThread(threadId, agentId) {
2943
2800
  return new MemoryThread(this.options, threadId, agentId);
2944
2801
  }
2802
+ getThreadMessages(threadId, opts = {}) {
2803
+ let url = "";
2804
+ if (opts.agentId) {
2805
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}`;
2806
+ } else if (opts.networkId) {
2807
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}`;
2808
+ }
2809
+ return this.request(url);
2810
+ }
2811
+ deleteThread(threadId, opts = {}) {
2812
+ let url = "";
2813
+ if (opts.agentId) {
2814
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}`;
2815
+ } else if (opts.networkId) {
2816
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}`;
2817
+ }
2818
+ return this.request(url, { method: "DELETE" });
2819
+ }
2945
2820
  /**
2946
2821
  * Saves messages to memory
2947
2822
  * @param params - Parameters containing messages to save
@@ -3004,10 +2879,17 @@ var MastraClient = class extends BaseResource {
3004
2879
  }
3005
2880
  /**
3006
2881
  * Retrieves all available tools
2882
+ * @param runtimeContext - Optional runtime context to pass as query parameter
3007
2883
  * @returns Promise containing map of tool IDs to tool details
3008
2884
  */
3009
- getTools() {
3010
- return this.request("/api/tools");
2885
+ getTools(runtimeContext) {
2886
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2887
+ const searchParams = new URLSearchParams();
2888
+ if (runtimeContextParam) {
2889
+ searchParams.set("runtimeContext", runtimeContextParam);
2890
+ }
2891
+ const queryString = searchParams.toString();
2892
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
3011
2893
  }
3012
2894
  /**
3013
2895
  * Gets a tool instance by ID
@@ -3017,27 +2899,19 @@ var MastraClient = class extends BaseResource {
3017
2899
  getTool(toolId) {
3018
2900
  return new Tool(this.options, toolId);
3019
2901
  }
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
2902
  /**
3036
2903
  * Retrieves all available workflows
2904
+ * @param runtimeContext - Optional runtime context to pass as query parameter
3037
2905
  * @returns Promise containing map of workflow IDs to workflow details
3038
2906
  */
3039
- getWorkflows() {
3040
- return this.request("/api/workflows");
2907
+ getWorkflows(runtimeContext) {
2908
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2909
+ const searchParams = new URLSearchParams();
2910
+ if (runtimeContextParam) {
2911
+ searchParams.set("runtimeContext", runtimeContextParam);
2912
+ }
2913
+ const queryString = searchParams.toString();
2914
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
3041
2915
  }
3042
2916
  /**
3043
2917
  * Gets a workflow instance by ID
@@ -3205,36 +3079,6 @@ var MastraClient = class extends BaseResource {
3205
3079
  return this.request(`/api/telemetry`);
3206
3080
  }
3207
3081
  }
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
- /**
3216
- * Retrieves all available vNext networks
3217
- * @returns Promise containing map of vNext network IDs to vNext network details
3218
- */
3219
- getVNextNetworks() {
3220
- return this.request("/api/networks/v-next");
3221
- }
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
- /**
3231
- * Gets a vNext network instance by ID
3232
- * @param networkId - ID of the vNext network to retrieve
3233
- * @returns vNext Network instance
3234
- */
3235
- getVNextNetwork(networkId) {
3236
- return new VNextNetwork(this.options, networkId);
3237
- }
3238
3082
  /**
3239
3083
  * Retrieves a list of available MCP servers.
3240
3084
  * @param params - Optional parameters for pagination (limit, offset).
@@ -3339,7 +3183,7 @@ var MastraClient = class extends BaseResource {
3339
3183
  * @returns Promise containing the scorer
3340
3184
  */
3341
3185
  getScorer(scorerId) {
3342
- return this.request(`/api/scores/scorers/${scorerId}`);
3186
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3343
3187
  }
3344
3188
  getScoresByScorerId(params) {
3345
3189
  const { page, perPage, scorerId, entityId, entityType } = params;
@@ -3357,7 +3201,7 @@ var MastraClient = class extends BaseResource {
3357
3201
  searchParams.set("perPage", String(perPage));
3358
3202
  }
3359
3203
  const queryString = searchParams.toString();
3360
- return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3204
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3361
3205
  }
3362
3206
  /**
3363
3207
  * Retrieves scores by run ID
@@ -3374,7 +3218,7 @@ var MastraClient = class extends BaseResource {
3374
3218
  searchParams.set("perPage", String(perPage));
3375
3219
  }
3376
3220
  const queryString = searchParams.toString();
3377
- return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3221
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
3378
3222
  }
3379
3223
  /**
3380
3224
  * Retrieves scores by entity ID and type
@@ -3391,7 +3235,9 @@ var MastraClient = class extends BaseResource {
3391
3235
  searchParams.set("perPage", String(perPage));
3392
3236
  }
3393
3237
  const queryString = searchParams.toString();
3394
- return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3238
+ return this.request(
3239
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3240
+ );
3395
3241
  }
3396
3242
  /**
3397
3243
  * Saves a score
@@ -3417,8 +3263,33 @@ var MastraClient = class extends BaseResource {
3417
3263
  getAITraces(params) {
3418
3264
  return this.observability.getTraces(params);
3419
3265
  }
3266
+ getScoresBySpan(params) {
3267
+ return this.observability.getScoresBySpan(params);
3268
+ }
3269
+ score(params) {
3270
+ return this.observability.score(params);
3271
+ }
3420
3272
  };
3421
3273
 
3422
- export { MastraClient };
3274
+ // src/tools.ts
3275
+ var ClientTool = class {
3276
+ id;
3277
+ description;
3278
+ inputSchema;
3279
+ outputSchema;
3280
+ execute;
3281
+ constructor(opts) {
3282
+ this.id = opts.id;
3283
+ this.description = opts.description;
3284
+ this.inputSchema = opts.inputSchema;
3285
+ this.outputSchema = opts.outputSchema;
3286
+ this.execute = opts.execute;
3287
+ }
3288
+ };
3289
+ function createTool(opts) {
3290
+ return new ClientTool(opts);
3291
+ }
3292
+
3293
+ export { ClientTool, MastraClient, createTool };
3423
3294
  //# sourceMappingURL=index.js.map
3424
3295
  //# sourceMappingURL=index.js.map