@mastra/client-js 0.0.0-storage-20250225005900 → 0.0.0-stream-vnext-usage-20250908171242

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 (73) hide show
  1. package/CHANGELOG.md +2639 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +12 -6
  4. package/dist/client.d.ts +280 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/example.d.ts +2 -0
  7. package/dist/example.d.ts.map +1 -0
  8. package/dist/index.cjs +3279 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +4 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +3273 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources/a2a.d.ts +41 -0
  15. package/dist/resources/a2a.d.ts.map +1 -0
  16. package/dist/resources/agent-builder.d.ts +161 -0
  17. package/dist/resources/agent-builder.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +155 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +13 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/legacy-workflow.d.ts +87 -0
  25. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  26. package/dist/resources/mcp-tool.d.ts +27 -0
  27. package/dist/resources/mcp-tool.d.ts.map +1 -0
  28. package/dist/resources/memory-thread.d.ts +53 -0
  29. package/dist/resources/memory-thread.d.ts.map +1 -0
  30. package/dist/resources/network-memory-thread.d.ts +47 -0
  31. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  32. package/dist/resources/network.d.ts +30 -0
  33. package/dist/resources/network.d.ts.map +1 -0
  34. package/dist/resources/observability.d.ts +19 -0
  35. package/dist/resources/observability.d.ts.map +1 -0
  36. package/dist/resources/tool.d.ts +23 -0
  37. package/dist/resources/tool.d.ts.map +1 -0
  38. package/dist/resources/vNextNetwork.d.ts +42 -0
  39. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  40. package/dist/resources/vector.d.ts +48 -0
  41. package/dist/resources/vector.d.ts.map +1 -0
  42. package/dist/resources/workflow.d.ts +169 -0
  43. package/dist/resources/workflow.d.ts.map +1 -0
  44. package/dist/types.d.ts +461 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/utils/index.d.ts +3 -0
  47. package/dist/utils/index.d.ts.map +1 -0
  48. package/dist/utils/process-client-tools.d.ts +3 -0
  49. package/dist/utils/process-client-tools.d.ts.map +1 -0
  50. package/dist/utils/process-mastra-stream.d.ts +7 -0
  51. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  52. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  53. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  54. package/package.json +50 -21
  55. package/.turbo/turbo-build.log +0 -16
  56. package/LICENSE +0 -44
  57. package/dist/index.d.mts +0 -405
  58. package/dist/index.mjs +0 -487
  59. package/eslint.config.js +0 -6
  60. package/src/client.ts +0 -205
  61. package/src/example.ts +0 -43
  62. package/src/index.test.ts +0 -597
  63. package/src/index.ts +0 -2
  64. package/src/resources/agent.ts +0 -116
  65. package/src/resources/base.ts +0 -68
  66. package/src/resources/index.ts +0 -6
  67. package/src/resources/memory-thread.ts +0 -60
  68. package/src/resources/tool.ts +0 -32
  69. package/src/resources/vector.ts +0 -83
  70. package/src/resources/workflow.ts +0 -68
  71. package/src/types.ts +0 -163
  72. package/tsconfig.json +0 -5
  73. package/vitest.config.js +0 -8
package/dist/index.cjs ADDED
@@ -0,0 +1,3279 @@
1
+ 'use strict';
2
+
3
+ var uiUtils = require('@ai-sdk/ui-utils');
4
+ var uuid = require('@lukeed/uuid');
5
+ var runtimeContext = require('@mastra/core/runtime-context');
6
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
7
+ var zod = require('zod');
8
+ var originalZodToJsonSchema = require('zod-to-json-schema');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
13
+
14
+ // src/resources/agent.ts
15
+ function parseClientRuntimeContext(runtimeContext$1) {
16
+ if (runtimeContext$1) {
17
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
18
+ return Object.fromEntries(runtimeContext$1.entries());
19
+ }
20
+ return runtimeContext$1;
21
+ }
22
+ return void 0;
23
+ }
24
+ function isZodType(value) {
25
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
26
+ }
27
+ function zodToJsonSchema(zodSchema) {
28
+ if (!isZodType(zodSchema)) {
29
+ return zodSchema;
30
+ }
31
+ if ("toJSONSchema" in zod.z) {
32
+ const fn = "toJSONSchema";
33
+ return zod.z[fn].call(zod.z, zodSchema);
34
+ }
35
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
36
+ }
37
+
38
+ // src/utils/process-client-tools.ts
39
+ function processClientTools(clientTools) {
40
+ if (!clientTools) {
41
+ return void 0;
42
+ }
43
+ return Object.fromEntries(
44
+ Object.entries(clientTools).map(([key, value]) => {
45
+ if (isVercelTool.isVercelTool(value)) {
46
+ return [
47
+ key,
48
+ {
49
+ ...value,
50
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
51
+ }
52
+ ];
53
+ } else {
54
+ return [
55
+ key,
56
+ {
57
+ ...value,
58
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
59
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
60
+ }
61
+ ];
62
+ }
63
+ })
64
+ );
65
+ }
66
+
67
+ // src/utils/process-mastra-stream.ts
68
+ async function processMastraStream({
69
+ stream,
70
+ onChunk
71
+ }) {
72
+ const reader = stream.getReader();
73
+ const decoder = new TextDecoder();
74
+ let buffer = "";
75
+ try {
76
+ while (true) {
77
+ const { done, value } = await reader.read();
78
+ if (done) break;
79
+ buffer += decoder.decode(value, { stream: true });
80
+ const lines = buffer.split("\n\n");
81
+ buffer = lines.pop() || "";
82
+ for (const line of lines) {
83
+ if (line.startsWith("data: ")) {
84
+ const data = line.slice(6);
85
+ if (data === "[DONE]") {
86
+ console.log("\u{1F3C1} Stream finished");
87
+ return;
88
+ }
89
+ try {
90
+ const json = JSON.parse(data);
91
+ await onChunk(json);
92
+ } catch (error) {
93
+ console.error("\u274C JSON parse error:", error, "Data:", data);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ } finally {
99
+ reader.releaseLock();
100
+ }
101
+ }
102
+
103
+ // src/resources/base.ts
104
+ var BaseResource = class {
105
+ options;
106
+ constructor(options) {
107
+ this.options = options;
108
+ }
109
+ /**
110
+ * Makes an HTTP request to the API with retries and exponential backoff
111
+ * @param path - The API endpoint path
112
+ * @param options - Optional request configuration
113
+ * @returns Promise containing the response data
114
+ */
115
+ async request(path, options = {}) {
116
+ let lastError = null;
117
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
118
+ let delay = backoffMs;
119
+ for (let attempt = 0; attempt <= retries; attempt++) {
120
+ try {
121
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
122
+ ...options,
123
+ headers: {
124
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
125
+ ...headers,
126
+ ...options.headers
127
+ // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
128
+ // 'x-mastra-client-type': 'js',
129
+ },
130
+ signal: this.options.abortSignal,
131
+ credentials: options.credentials ?? credentials,
132
+ body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
133
+ });
134
+ if (!response.ok) {
135
+ const errorBody = await response.text();
136
+ let errorMessage = `HTTP error! status: ${response.status}`;
137
+ try {
138
+ const errorJson = JSON.parse(errorBody);
139
+ errorMessage += ` - ${JSON.stringify(errorJson)}`;
140
+ } catch {
141
+ if (errorBody) {
142
+ errorMessage += ` - ${errorBody}`;
143
+ }
144
+ }
145
+ throw new Error(errorMessage);
146
+ }
147
+ if (options.stream) {
148
+ return response;
149
+ }
150
+ const data = await response.json();
151
+ return data;
152
+ } catch (error) {
153
+ lastError = error;
154
+ if (attempt === retries) {
155
+ break;
156
+ }
157
+ await new Promise((resolve) => setTimeout(resolve, delay));
158
+ delay = Math.min(delay * 2, maxBackoffMs);
159
+ }
160
+ }
161
+ throw lastError || new Error("Request failed");
162
+ }
163
+ };
164
+
165
+ // src/resources/agent.ts
166
+ async function executeToolCallAndRespond({
167
+ response,
168
+ params,
169
+ runId,
170
+ resourceId,
171
+ threadId,
172
+ runtimeContext,
173
+ respondFn
174
+ }) {
175
+ if (response.finishReason === "tool-calls") {
176
+ const toolCalls = response.toolCalls;
177
+ if (!toolCalls || !Array.isArray(toolCalls)) {
178
+ return response;
179
+ }
180
+ for (const toolCall of toolCalls) {
181
+ const clientTool = params.clientTools?.[toolCall.toolName];
182
+ if (clientTool && clientTool.execute) {
183
+ const result = await clientTool.execute(
184
+ {
185
+ context: toolCall?.args,
186
+ runId,
187
+ resourceId,
188
+ threadId,
189
+ runtimeContext,
190
+ tracingContext: { currentSpan: void 0 }
191
+ },
192
+ {
193
+ messages: response.messages,
194
+ toolCallId: toolCall?.toolCallId
195
+ }
196
+ );
197
+ const updatedMessages = [
198
+ {
199
+ role: "user",
200
+ content: params.messages
201
+ },
202
+ ...response.response.messages,
203
+ {
204
+ role: "tool",
205
+ content: [
206
+ {
207
+ type: "tool-result",
208
+ toolCallId: toolCall.toolCallId,
209
+ toolName: toolCall.toolName,
210
+ result
211
+ }
212
+ ]
213
+ }
214
+ ];
215
+ return respondFn({
216
+ ...params,
217
+ messages: updatedMessages
218
+ });
219
+ }
220
+ }
221
+ }
222
+ }
223
+ var AgentVoice = class extends BaseResource {
224
+ constructor(options, agentId) {
225
+ super(options);
226
+ this.agentId = agentId;
227
+ this.agentId = agentId;
228
+ }
229
+ /**
230
+ * Convert text to speech using the agent's voice provider
231
+ * @param text - Text to convert to speech
232
+ * @param options - Optional provider-specific options for speech generation
233
+ * @returns Promise containing the audio data
234
+ */
235
+ async speak(text, options) {
236
+ return this.request(`/api/agents/${this.agentId}/voice/speak`, {
237
+ method: "POST",
238
+ headers: {
239
+ "Content-Type": "application/json"
240
+ },
241
+ body: { input: text, options },
242
+ stream: true
243
+ });
244
+ }
245
+ /**
246
+ * Convert speech to text using the agent's voice provider
247
+ * @param audio - Audio data to transcribe
248
+ * @param options - Optional provider-specific options
249
+ * @returns Promise containing the transcribed text
250
+ */
251
+ listen(audio, options) {
252
+ const formData = new FormData();
253
+ formData.append("audio", audio);
254
+ if (options) {
255
+ formData.append("options", JSON.stringify(options));
256
+ }
257
+ return this.request(`/api/agents/${this.agentId}/voice/listen`, {
258
+ method: "POST",
259
+ body: formData
260
+ });
261
+ }
262
+ /**
263
+ * Get available speakers for the agent's voice provider
264
+ * @returns Promise containing list of available speakers
265
+ */
266
+ getSpeakers() {
267
+ return this.request(`/api/agents/${this.agentId}/voice/speakers`);
268
+ }
269
+ /**
270
+ * Get the listener configuration for the agent's voice provider
271
+ * @returns Promise containing a check if the agent has listening capabilities
272
+ */
273
+ getListener() {
274
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
275
+ }
276
+ };
277
+ var Agent = class extends BaseResource {
278
+ constructor(options, agentId) {
279
+ super(options);
280
+ this.agentId = agentId;
281
+ this.voice = new AgentVoice(options, this.agentId);
282
+ }
283
+ voice;
284
+ /**
285
+ * Retrieves details about the agent
286
+ * @returns Promise containing agent details including model and instructions
287
+ */
288
+ details() {
289
+ return this.request(`/api/agents/${this.agentId}`);
290
+ }
291
+ async generate(params) {
292
+ console.warn(
293
+ "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th. Please use generateLegacy if you don't want to upgrade just yet."
294
+ );
295
+ return this.generateLegacy(params);
296
+ }
297
+ async generateLegacy(params) {
298
+ const processedParams = {
299
+ ...params,
300
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
301
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
302
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
303
+ clientTools: processClientTools(params.clientTools)
304
+ };
305
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
306
+ const response = await this.request(
307
+ `/api/agents/${this.agentId}/generate-legacy`,
308
+ {
309
+ method: "POST",
310
+ body: processedParams
311
+ }
312
+ );
313
+ if (response.finishReason === "tool-calls") {
314
+ const toolCalls = response.toolCalls;
315
+ if (!toolCalls || !Array.isArray(toolCalls)) {
316
+ return response;
317
+ }
318
+ for (const toolCall of toolCalls) {
319
+ const clientTool = params.clientTools?.[toolCall.toolName];
320
+ if (clientTool && clientTool.execute) {
321
+ const result = await clientTool.execute(
322
+ {
323
+ context: toolCall?.args,
324
+ runId,
325
+ resourceId,
326
+ threadId,
327
+ runtimeContext,
328
+ tracingContext: { currentSpan: void 0 }
329
+ },
330
+ {
331
+ messages: response.messages,
332
+ toolCallId: toolCall?.toolCallId
333
+ }
334
+ );
335
+ const updatedMessages = [
336
+ {
337
+ role: "user",
338
+ content: params.messages
339
+ },
340
+ ...response.response.messages,
341
+ {
342
+ role: "tool",
343
+ content: [
344
+ {
345
+ type: "tool-result",
346
+ toolCallId: toolCall.toolCallId,
347
+ toolName: toolCall.toolName,
348
+ result
349
+ }
350
+ ]
351
+ }
352
+ ];
353
+ return this.generate({
354
+ ...params,
355
+ messages: updatedMessages
356
+ });
357
+ }
358
+ }
359
+ }
360
+ return response;
361
+ }
362
+ async generateVNext(params) {
363
+ const processedParams = {
364
+ ...params,
365
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
366
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
367
+ clientTools: processClientTools(params.clientTools)
368
+ };
369
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
370
+ const response = await this.request(
371
+ `/api/agents/${this.agentId}/generate/vnext`,
372
+ {
373
+ method: "POST",
374
+ body: processedParams
375
+ }
376
+ );
377
+ if (response.finishReason === "tool-calls") {
378
+ return executeToolCallAndRespond({
379
+ response,
380
+ params,
381
+ runId,
382
+ resourceId,
383
+ threadId,
384
+ runtimeContext,
385
+ respondFn: this.generateVNext.bind(this)
386
+ });
387
+ }
388
+ return response;
389
+ }
390
+ async processChatResponse({
391
+ stream,
392
+ update,
393
+ onToolCall,
394
+ onFinish,
395
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
396
+ lastMessage
397
+ }) {
398
+ const replaceLastMessage = lastMessage?.role === "assistant";
399
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
400
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
401
+ return Math.max(max, toolInvocation.step ?? 0);
402
+ }, 0) ?? 0) : 0;
403
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
404
+ id: uuid.v4(),
405
+ createdAt: getCurrentDate(),
406
+ role: "assistant",
407
+ content: "",
408
+ parts: []
409
+ };
410
+ let currentTextPart = void 0;
411
+ let currentReasoningPart = void 0;
412
+ let currentReasoningTextDetail = void 0;
413
+ function updateToolInvocationPart(toolCallId, invocation) {
414
+ const part = message.parts.find(
415
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
416
+ );
417
+ if (part != null) {
418
+ part.toolInvocation = invocation;
419
+ } else {
420
+ message.parts.push({
421
+ type: "tool-invocation",
422
+ toolInvocation: invocation
423
+ });
424
+ }
425
+ }
426
+ const data = [];
427
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
428
+ const partialToolCalls = {};
429
+ let usage = {
430
+ completionTokens: NaN,
431
+ promptTokens: NaN,
432
+ totalTokens: NaN
433
+ };
434
+ let finishReason = "unknown";
435
+ function execUpdate() {
436
+ const copiedData = [...data];
437
+ if (messageAnnotations?.length) {
438
+ message.annotations = messageAnnotations;
439
+ }
440
+ const copiedMessage = {
441
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
442
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
443
+ ...structuredClone(message),
444
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
445
+ // hashing approach by default to detect changes, but it only works for shallow
446
+ // changes. This is why we need to add a revision id to ensure that the message
447
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
448
+ // forwarded to rendering):
449
+ revisionId: uuid.v4()
450
+ };
451
+ update({
452
+ message: copiedMessage,
453
+ data: copiedData,
454
+ replaceLastMessage
455
+ });
456
+ }
457
+ await uiUtils.processDataStream({
458
+ stream,
459
+ onTextPart(value) {
460
+ if (currentTextPart == null) {
461
+ currentTextPart = {
462
+ type: "text",
463
+ text: value
464
+ };
465
+ message.parts.push(currentTextPart);
466
+ } else {
467
+ currentTextPart.text += value;
468
+ }
469
+ message.content += value;
470
+ execUpdate();
471
+ },
472
+ onReasoningPart(value) {
473
+ if (currentReasoningTextDetail == null) {
474
+ currentReasoningTextDetail = { type: "text", text: value };
475
+ if (currentReasoningPart != null) {
476
+ currentReasoningPart.details.push(currentReasoningTextDetail);
477
+ }
478
+ } else {
479
+ currentReasoningTextDetail.text += value;
480
+ }
481
+ if (currentReasoningPart == null) {
482
+ currentReasoningPart = {
483
+ type: "reasoning",
484
+ reasoning: value,
485
+ details: [currentReasoningTextDetail]
486
+ };
487
+ message.parts.push(currentReasoningPart);
488
+ } else {
489
+ currentReasoningPart.reasoning += value;
490
+ }
491
+ message.reasoning = (message.reasoning ?? "") + value;
492
+ execUpdate();
493
+ },
494
+ onReasoningSignaturePart(value) {
495
+ if (currentReasoningTextDetail != null) {
496
+ currentReasoningTextDetail.signature = value.signature;
497
+ }
498
+ },
499
+ onRedactedReasoningPart(value) {
500
+ if (currentReasoningPart == null) {
501
+ currentReasoningPart = {
502
+ type: "reasoning",
503
+ reasoning: "",
504
+ details: []
505
+ };
506
+ message.parts.push(currentReasoningPart);
507
+ }
508
+ currentReasoningPart.details.push({
509
+ type: "redacted",
510
+ data: value.data
511
+ });
512
+ currentReasoningTextDetail = void 0;
513
+ execUpdate();
514
+ },
515
+ onFilePart(value) {
516
+ message.parts.push({
517
+ type: "file",
518
+ mimeType: value.mimeType,
519
+ data: value.data
520
+ });
521
+ execUpdate();
522
+ },
523
+ onSourcePart(value) {
524
+ message.parts.push({
525
+ type: "source",
526
+ source: value
527
+ });
528
+ execUpdate();
529
+ },
530
+ onToolCallStreamingStartPart(value) {
531
+ if (message.toolInvocations == null) {
532
+ message.toolInvocations = [];
533
+ }
534
+ partialToolCalls[value.toolCallId] = {
535
+ text: "",
536
+ step,
537
+ toolName: value.toolName,
538
+ index: message.toolInvocations.length
539
+ };
540
+ const invocation = {
541
+ state: "partial-call",
542
+ step,
543
+ toolCallId: value.toolCallId,
544
+ toolName: value.toolName,
545
+ args: void 0
546
+ };
547
+ message.toolInvocations.push(invocation);
548
+ updateToolInvocationPart(value.toolCallId, invocation);
549
+ execUpdate();
550
+ },
551
+ onToolCallDeltaPart(value) {
552
+ const partialToolCall = partialToolCalls[value.toolCallId];
553
+ partialToolCall.text += value.argsTextDelta;
554
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
555
+ const invocation = {
556
+ state: "partial-call",
557
+ step: partialToolCall.step,
558
+ toolCallId: value.toolCallId,
559
+ toolName: partialToolCall.toolName,
560
+ args: partialArgs
561
+ };
562
+ message.toolInvocations[partialToolCall.index] = invocation;
563
+ updateToolInvocationPart(value.toolCallId, invocation);
564
+ execUpdate();
565
+ },
566
+ async onToolCallPart(value) {
567
+ const invocation = {
568
+ state: "call",
569
+ step,
570
+ ...value
571
+ };
572
+ if (partialToolCalls[value.toolCallId] != null) {
573
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
574
+ } else {
575
+ if (message.toolInvocations == null) {
576
+ message.toolInvocations = [];
577
+ }
578
+ message.toolInvocations.push(invocation);
579
+ }
580
+ updateToolInvocationPart(value.toolCallId, invocation);
581
+ execUpdate();
582
+ if (onToolCall) {
583
+ const result = await onToolCall({ toolCall: value });
584
+ if (result != null) {
585
+ const invocation2 = {
586
+ state: "result",
587
+ step,
588
+ ...value,
589
+ result
590
+ };
591
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
592
+ updateToolInvocationPart(value.toolCallId, invocation2);
593
+ execUpdate();
594
+ }
595
+ }
596
+ },
597
+ onToolResultPart(value) {
598
+ const toolInvocations = message.toolInvocations;
599
+ if (toolInvocations == null) {
600
+ throw new Error("tool_result must be preceded by a tool_call");
601
+ }
602
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
603
+ if (toolInvocationIndex === -1) {
604
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
605
+ }
606
+ const invocation = {
607
+ ...toolInvocations[toolInvocationIndex],
608
+ state: "result",
609
+ ...value
610
+ };
611
+ toolInvocations[toolInvocationIndex] = invocation;
612
+ updateToolInvocationPart(value.toolCallId, invocation);
613
+ execUpdate();
614
+ },
615
+ onDataPart(value) {
616
+ data.push(...value);
617
+ execUpdate();
618
+ },
619
+ onMessageAnnotationsPart(value) {
620
+ if (messageAnnotations == null) {
621
+ messageAnnotations = [...value];
622
+ } else {
623
+ messageAnnotations.push(...value);
624
+ }
625
+ execUpdate();
626
+ },
627
+ onFinishStepPart(value) {
628
+ step += 1;
629
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
630
+ currentReasoningPart = void 0;
631
+ currentReasoningTextDetail = void 0;
632
+ },
633
+ onStartStepPart(value) {
634
+ if (!replaceLastMessage) {
635
+ message.id = value.messageId;
636
+ }
637
+ message.parts.push({ type: "step-start" });
638
+ execUpdate();
639
+ },
640
+ onFinishMessagePart(value) {
641
+ finishReason = value.finishReason;
642
+ if (value.usage != null) {
643
+ usage = value.usage;
644
+ }
645
+ },
646
+ onErrorPart(error) {
647
+ throw new Error(error);
648
+ }
649
+ });
650
+ onFinish?.({ message, finishReason, usage });
651
+ }
652
+ /**
653
+ * Streams a response from the agent
654
+ * @param params - Stream parameters including prompt
655
+ * @returns Promise containing the enhanced Response object with processDataStream method
656
+ */
657
+ async stream(params) {
658
+ console.warn(
659
+ "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th. Please use streamLegacy if you don't want to upgrade just yet."
660
+ );
661
+ return this.streamLegacy(params);
662
+ }
663
+ /**
664
+ * Streams a response from the agent
665
+ * @param params - Stream parameters including prompt
666
+ * @returns Promise containing the enhanced Response object with processDataStream method
667
+ */
668
+ async streamLegacy(params) {
669
+ const processedParams = {
670
+ ...params,
671
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
672
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
673
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
674
+ clientTools: processClientTools(params.clientTools)
675
+ };
676
+ const { readable, writable } = new TransformStream();
677
+ const response = await this.processStreamResponse(processedParams, writable);
678
+ const streamResponse = new Response(readable, {
679
+ status: response.status,
680
+ statusText: response.statusText,
681
+ headers: response.headers
682
+ });
683
+ streamResponse.processDataStream = async (options = {}) => {
684
+ await uiUtils.processDataStream({
685
+ stream: streamResponse.body,
686
+ ...options
687
+ });
688
+ };
689
+ return streamResponse;
690
+ }
691
+ async processChatResponse_vNext({
692
+ stream,
693
+ update,
694
+ onToolCall,
695
+ onFinish,
696
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
697
+ lastMessage
698
+ }) {
699
+ const replaceLastMessage = lastMessage?.role === "assistant";
700
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
701
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
702
+ return Math.max(max, toolInvocation.step ?? 0);
703
+ }, 0) ?? 0) : 0;
704
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
705
+ id: uuid.v4(),
706
+ createdAt: getCurrentDate(),
707
+ role: "assistant",
708
+ content: "",
709
+ parts: []
710
+ };
711
+ let currentTextPart = void 0;
712
+ let currentReasoningPart = void 0;
713
+ let currentReasoningTextDetail = void 0;
714
+ function updateToolInvocationPart(toolCallId, invocation) {
715
+ const part = message.parts.find(
716
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
717
+ );
718
+ if (part != null) {
719
+ part.toolInvocation = invocation;
720
+ } else {
721
+ message.parts.push({
722
+ type: "tool-invocation",
723
+ toolInvocation: invocation
724
+ });
725
+ }
726
+ }
727
+ const data = [];
728
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
729
+ const partialToolCalls = {};
730
+ let usage = {
731
+ completionTokens: NaN,
732
+ promptTokens: NaN,
733
+ totalTokens: NaN
734
+ };
735
+ let finishReason = "unknown";
736
+ function execUpdate() {
737
+ const copiedData = [...data];
738
+ if (messageAnnotations?.length) {
739
+ message.annotations = messageAnnotations;
740
+ }
741
+ const copiedMessage = {
742
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
743
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
744
+ ...structuredClone(message),
745
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
746
+ // hashing approach by default to detect changes, but it only works for shallow
747
+ // changes. This is why we need to add a revision id to ensure that the message
748
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
749
+ // forwarded to rendering):
750
+ revisionId: uuid.v4()
751
+ };
752
+ update({
753
+ message: copiedMessage,
754
+ data: copiedData,
755
+ replaceLastMessage
756
+ });
757
+ }
758
+ await processMastraStream({
759
+ stream,
760
+ // TODO: casting as any here because the stream types were all typed as any before in core.
761
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
762
+ onChunk: async (chunk) => {
763
+ switch (chunk.type) {
764
+ case "step-start": {
765
+ if (!replaceLastMessage) {
766
+ message.id = chunk.payload.messageId;
767
+ }
768
+ message.parts.push({ type: "step-start" });
769
+ execUpdate();
770
+ break;
771
+ }
772
+ case "text-delta": {
773
+ if (currentTextPart == null) {
774
+ currentTextPart = {
775
+ type: "text",
776
+ text: chunk.payload.text
777
+ };
778
+ message.parts.push(currentTextPart);
779
+ } else {
780
+ currentTextPart.text += chunk.payload.text;
781
+ }
782
+ message.content += chunk.payload.text;
783
+ execUpdate();
784
+ break;
785
+ }
786
+ case "reasoning-delta": {
787
+ if (currentReasoningTextDetail == null) {
788
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
789
+ if (currentReasoningPart != null) {
790
+ currentReasoningPart.details.push(currentReasoningTextDetail);
791
+ }
792
+ } else {
793
+ currentReasoningTextDetail.text += chunk.payload.text;
794
+ }
795
+ if (currentReasoningPart == null) {
796
+ currentReasoningPart = {
797
+ type: "reasoning",
798
+ reasoning: chunk.payload.text,
799
+ details: [currentReasoningTextDetail]
800
+ };
801
+ message.parts.push(currentReasoningPart);
802
+ } else {
803
+ currentReasoningPart.reasoning += chunk.payload.text;
804
+ }
805
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
806
+ execUpdate();
807
+ break;
808
+ }
809
+ case "file": {
810
+ message.parts.push({
811
+ type: "file",
812
+ mimeType: chunk.payload.mimeType,
813
+ data: chunk.payload.data
814
+ });
815
+ execUpdate();
816
+ break;
817
+ }
818
+ case "source": {
819
+ message.parts.push({
820
+ type: "source",
821
+ source: chunk.payload.source
822
+ });
823
+ execUpdate();
824
+ break;
825
+ }
826
+ case "tool-call": {
827
+ const invocation = {
828
+ state: "call",
829
+ step,
830
+ ...chunk.payload
831
+ };
832
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
833
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
834
+ } else {
835
+ if (message.toolInvocations == null) {
836
+ message.toolInvocations = [];
837
+ }
838
+ message.toolInvocations.push(invocation);
839
+ }
840
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
841
+ execUpdate();
842
+ if (onToolCall) {
843
+ const result = await onToolCall({ toolCall: chunk.payload });
844
+ if (result != null) {
845
+ const invocation2 = {
846
+ state: "result",
847
+ step,
848
+ ...chunk.payload,
849
+ result
850
+ };
851
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
852
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
853
+ execUpdate();
854
+ }
855
+ }
856
+ }
857
+ case "tool-call-input-streaming-start": {
858
+ if (message.toolInvocations == null) {
859
+ message.toolInvocations = [];
860
+ }
861
+ partialToolCalls[chunk.payload.toolCallId] = {
862
+ text: "",
863
+ step,
864
+ toolName: chunk.payload.toolName,
865
+ index: message.toolInvocations.length
866
+ };
867
+ const invocation = {
868
+ state: "partial-call",
869
+ step,
870
+ toolCallId: chunk.payload.toolCallId,
871
+ toolName: chunk.payload.toolName,
872
+ args: chunk.payload.args
873
+ };
874
+ message.toolInvocations.push(invocation);
875
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
876
+ execUpdate();
877
+ break;
878
+ }
879
+ case "tool-call-delta": {
880
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
881
+ partialToolCall.text += chunk.payload.argsTextDelta;
882
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
883
+ const invocation = {
884
+ state: "partial-call",
885
+ step: partialToolCall.step,
886
+ toolCallId: chunk.payload.toolCallId,
887
+ toolName: partialToolCall.toolName,
888
+ args: partialArgs
889
+ };
890
+ message.toolInvocations[partialToolCall.index] = invocation;
891
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
892
+ execUpdate();
893
+ break;
894
+ }
895
+ case "tool-result": {
896
+ const toolInvocations = message.toolInvocations;
897
+ if (toolInvocations == null) {
898
+ throw new Error("tool_result must be preceded by a tool_call");
899
+ }
900
+ const toolInvocationIndex = toolInvocations.findIndex(
901
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
902
+ );
903
+ if (toolInvocationIndex === -1) {
904
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
905
+ }
906
+ const invocation = {
907
+ ...toolInvocations[toolInvocationIndex],
908
+ state: "result",
909
+ ...chunk.payload
910
+ };
911
+ toolInvocations[toolInvocationIndex] = invocation;
912
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
913
+ execUpdate();
914
+ break;
915
+ }
916
+ case "error": {
917
+ throw new Error(chunk.payload.error);
918
+ }
919
+ case "data": {
920
+ data.push(...chunk.payload.data);
921
+ execUpdate();
922
+ break;
923
+ }
924
+ case "step-finish": {
925
+ step += 1;
926
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
927
+ currentReasoningPart = void 0;
928
+ currentReasoningTextDetail = void 0;
929
+ execUpdate();
930
+ break;
931
+ }
932
+ case "finish": {
933
+ finishReason = chunk.payload.stepResult.reason;
934
+ if (chunk.payload.usage != null) {
935
+ usage = chunk.payload.usage;
936
+ }
937
+ break;
938
+ }
939
+ }
940
+ }
941
+ });
942
+ onFinish?.({ message, finishReason, usage });
943
+ }
944
+ async processStreamResponse_vNext(processedParams, writable) {
945
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
946
+ method: "POST",
947
+ body: processedParams,
948
+ stream: true
949
+ });
950
+ if (!response.body) {
951
+ throw new Error("No response body");
952
+ }
953
+ try {
954
+ let toolCalls = [];
955
+ let messages = [];
956
+ const [streamForWritable, streamForProcessing] = response.body.tee();
957
+ streamForWritable.pipeTo(
958
+ new WritableStream({
959
+ async write(chunk) {
960
+ try {
961
+ const text = new TextDecoder().decode(chunk);
962
+ if (text.includes("[DONE]")) {
963
+ return;
964
+ }
965
+ } catch {
966
+ }
967
+ const writer = writable.getWriter();
968
+ try {
969
+ await writer.write(chunk);
970
+ } finally {
971
+ writer.releaseLock();
972
+ }
973
+ }
974
+ }),
975
+ {
976
+ preventClose: true
977
+ }
978
+ ).catch((error) => {
979
+ console.error("Error piping to writable stream:", error);
980
+ });
981
+ this.processChatResponse_vNext({
982
+ stream: streamForProcessing,
983
+ update: ({ message }) => {
984
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
985
+ if (existingIndex !== -1) {
986
+ messages[existingIndex] = message;
987
+ } else {
988
+ messages.push(message);
989
+ }
990
+ },
991
+ onFinish: async ({ finishReason, message }) => {
992
+ if (finishReason === "tool-calls") {
993
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
994
+ if (toolCall) {
995
+ toolCalls.push(toolCall);
996
+ }
997
+ for (const toolCall2 of toolCalls) {
998
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
999
+ if (clientTool && clientTool.execute) {
1000
+ const result = await clientTool.execute(
1001
+ {
1002
+ context: toolCall2?.args,
1003
+ runId: processedParams.runId,
1004
+ resourceId: processedParams.resourceId,
1005
+ threadId: processedParams.threadId,
1006
+ runtimeContext: processedParams.runtimeContext,
1007
+ // TODO: Pass proper tracing context when client-js supports tracing
1008
+ tracingContext: { currentSpan: void 0 }
1009
+ },
1010
+ {
1011
+ messages: response.messages,
1012
+ toolCallId: toolCall2?.toolCallId
1013
+ }
1014
+ );
1015
+ const lastMessageRaw = messages[messages.length - 1];
1016
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1017
+ const toolInvocationPart = lastMessage?.parts?.find(
1018
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1019
+ );
1020
+ if (toolInvocationPart) {
1021
+ toolInvocationPart.toolInvocation = {
1022
+ ...toolInvocationPart.toolInvocation,
1023
+ state: "result",
1024
+ result
1025
+ };
1026
+ }
1027
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1028
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1029
+ );
1030
+ if (toolInvocation) {
1031
+ toolInvocation.state = "result";
1032
+ toolInvocation.result = result;
1033
+ }
1034
+ const originalMessages = processedParams.messages;
1035
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1036
+ const updatedMessages = lastMessage != null ? [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messageArray, ...messages];
1037
+ this.processStreamResponse_vNext(
1038
+ {
1039
+ ...processedParams,
1040
+ messages: updatedMessages
1041
+ },
1042
+ writable
1043
+ ).catch((error) => {
1044
+ console.error("Error processing stream response:", error);
1045
+ });
1046
+ }
1047
+ }
1048
+ } else {
1049
+ setTimeout(() => {
1050
+ writable.close();
1051
+ }, 0);
1052
+ }
1053
+ },
1054
+ lastMessage: void 0
1055
+ }).catch((error) => {
1056
+ console.error("Error processing stream response:", error);
1057
+ });
1058
+ } catch (error) {
1059
+ console.error("Error processing stream response:", error);
1060
+ }
1061
+ return response;
1062
+ }
1063
+ async streamVNext(params) {
1064
+ const processedParams = {
1065
+ ...params,
1066
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1067
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1068
+ clientTools: processClientTools(params.clientTools)
1069
+ };
1070
+ const { readable, writable } = new TransformStream();
1071
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1072
+ const streamResponse = new Response(readable, {
1073
+ status: response.status,
1074
+ statusText: response.statusText,
1075
+ headers: response.headers
1076
+ });
1077
+ streamResponse.processDataStream = async ({
1078
+ onChunk
1079
+ }) => {
1080
+ await processMastraStream({
1081
+ stream: streamResponse.body,
1082
+ onChunk
1083
+ });
1084
+ };
1085
+ return streamResponse;
1086
+ }
1087
+ /**
1088
+ * Processes the stream response and handles tool calls
1089
+ */
1090
+ async processStreamResponse(processedParams, writable) {
1091
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1092
+ method: "POST",
1093
+ body: processedParams,
1094
+ stream: true
1095
+ });
1096
+ if (!response.body) {
1097
+ throw new Error("No response body");
1098
+ }
1099
+ try {
1100
+ let toolCalls = [];
1101
+ let messages = [];
1102
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1103
+ streamForWritable.pipeTo(writable, {
1104
+ preventClose: true
1105
+ }).catch((error) => {
1106
+ console.error("Error piping to writable stream:", error);
1107
+ });
1108
+ this.processChatResponse({
1109
+ stream: streamForProcessing,
1110
+ update: ({ message }) => {
1111
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1112
+ if (existingIndex !== -1) {
1113
+ messages[existingIndex] = message;
1114
+ } else {
1115
+ messages.push(message);
1116
+ }
1117
+ },
1118
+ onFinish: async ({ finishReason, message }) => {
1119
+ if (finishReason === "tool-calls") {
1120
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1121
+ if (toolCall) {
1122
+ toolCalls.push(toolCall);
1123
+ }
1124
+ for (const toolCall2 of toolCalls) {
1125
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1126
+ if (clientTool && clientTool.execute) {
1127
+ const result = await clientTool.execute(
1128
+ {
1129
+ context: toolCall2?.args,
1130
+ runId: processedParams.runId,
1131
+ resourceId: processedParams.resourceId,
1132
+ threadId: processedParams.threadId,
1133
+ runtimeContext: processedParams.runtimeContext,
1134
+ // TODO: Pass proper tracing context when client-js supports tracing
1135
+ tracingContext: { currentSpan: void 0 }
1136
+ },
1137
+ {
1138
+ messages: response.messages,
1139
+ toolCallId: toolCall2?.toolCallId
1140
+ }
1141
+ );
1142
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1143
+ const toolInvocationPart = lastMessage?.parts?.find(
1144
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1145
+ );
1146
+ if (toolInvocationPart) {
1147
+ toolInvocationPart.toolInvocation = {
1148
+ ...toolInvocationPart.toolInvocation,
1149
+ state: "result",
1150
+ result
1151
+ };
1152
+ }
1153
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1154
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1155
+ );
1156
+ if (toolInvocation) {
1157
+ toolInvocation.state = "result";
1158
+ toolInvocation.result = result;
1159
+ }
1160
+ const writer = writable.getWriter();
1161
+ try {
1162
+ await writer.write(
1163
+ new TextEncoder().encode(
1164
+ "a:" + JSON.stringify({
1165
+ toolCallId: toolCall2.toolCallId,
1166
+ result
1167
+ }) + "\n"
1168
+ )
1169
+ );
1170
+ } finally {
1171
+ writer.releaseLock();
1172
+ }
1173
+ const originalMessages = processedParams.messages;
1174
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1175
+ this.processStreamResponse(
1176
+ {
1177
+ ...processedParams,
1178
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1179
+ },
1180
+ writable
1181
+ ).catch((error) => {
1182
+ console.error("Error processing stream response:", error);
1183
+ });
1184
+ }
1185
+ }
1186
+ } else {
1187
+ setTimeout(() => {
1188
+ writable.close();
1189
+ }, 0);
1190
+ }
1191
+ },
1192
+ lastMessage: void 0
1193
+ }).catch((error) => {
1194
+ console.error("Error processing stream response:", error);
1195
+ });
1196
+ } catch (error) {
1197
+ console.error("Error processing stream response:", error);
1198
+ }
1199
+ return response;
1200
+ }
1201
+ /**
1202
+ * Gets details about a specific tool available to the agent
1203
+ * @param toolId - ID of the tool to retrieve
1204
+ * @returns Promise containing tool details
1205
+ */
1206
+ getTool(toolId) {
1207
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1208
+ }
1209
+ /**
1210
+ * Executes a tool for the agent
1211
+ * @param toolId - ID of the tool to execute
1212
+ * @param params - Parameters required for tool execution
1213
+ * @returns Promise containing the tool execution results
1214
+ */
1215
+ executeTool(toolId, params) {
1216
+ const body = {
1217
+ data: params.data,
1218
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1219
+ };
1220
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1221
+ method: "POST",
1222
+ body
1223
+ });
1224
+ }
1225
+ /**
1226
+ * Retrieves evaluation results for the agent
1227
+ * @returns Promise containing agent evaluations
1228
+ */
1229
+ evals() {
1230
+ return this.request(`/api/agents/${this.agentId}/evals/ci`);
1231
+ }
1232
+ /**
1233
+ * Retrieves live evaluation results for the agent
1234
+ * @returns Promise containing live agent evaluations
1235
+ */
1236
+ liveEvals() {
1237
+ return this.request(`/api/agents/${this.agentId}/evals/live`);
1238
+ }
1239
+ /**
1240
+ * Updates the model for the agent
1241
+ * @param params - Parameters for updating the model
1242
+ * @returns Promise containing the updated model
1243
+ */
1244
+ updateModel(params) {
1245
+ return this.request(`/api/agents/${this.agentId}/model`, {
1246
+ method: "POST",
1247
+ body: params
1248
+ });
1249
+ }
1250
+ };
1251
+ var Network = class extends BaseResource {
1252
+ constructor(options, networkId) {
1253
+ super(options);
1254
+ this.networkId = networkId;
1255
+ }
1256
+ /**
1257
+ * Retrieves details about the network
1258
+ * @returns Promise containing network details
1259
+ */
1260
+ details() {
1261
+ return this.request(`/api/networks/${this.networkId}`);
1262
+ }
1263
+ /**
1264
+ * Generates a response from the agent
1265
+ * @param params - Generation parameters including prompt
1266
+ * @returns Promise containing the generated response
1267
+ */
1268
+ generate(params) {
1269
+ const processedParams = {
1270
+ ...params,
1271
+ output: zodToJsonSchema(params.output),
1272
+ experimental_output: zodToJsonSchema(params.experimental_output)
1273
+ };
1274
+ return this.request(`/api/networks/${this.networkId}/generate`, {
1275
+ method: "POST",
1276
+ body: processedParams
1277
+ });
1278
+ }
1279
+ /**
1280
+ * Streams a response from the agent
1281
+ * @param params - Stream parameters including prompt
1282
+ * @returns Promise containing the enhanced Response object with processDataStream method
1283
+ */
1284
+ async stream(params) {
1285
+ const processedParams = {
1286
+ ...params,
1287
+ output: zodToJsonSchema(params.output),
1288
+ experimental_output: zodToJsonSchema(params.experimental_output)
1289
+ };
1290
+ const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1291
+ method: "POST",
1292
+ body: processedParams,
1293
+ stream: true
1294
+ });
1295
+ if (!response.body) {
1296
+ throw new Error("No response body");
1297
+ }
1298
+ response.processDataStream = async (options = {}) => {
1299
+ await uiUtils.processDataStream({
1300
+ stream: response.body,
1301
+ ...options
1302
+ });
1303
+ };
1304
+ return response;
1305
+ }
1306
+ };
1307
+
1308
+ // src/resources/memory-thread.ts
1309
+ var MemoryThread = class extends BaseResource {
1310
+ constructor(options, threadId, agentId) {
1311
+ super(options);
1312
+ this.threadId = threadId;
1313
+ this.agentId = agentId;
1314
+ }
1315
+ /**
1316
+ * Retrieves the memory thread details
1317
+ * @returns Promise containing thread details including title and metadata
1318
+ */
1319
+ get() {
1320
+ return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`);
1321
+ }
1322
+ /**
1323
+ * Updates the memory thread properties
1324
+ * @param params - Update parameters including title and metadata
1325
+ * @returns Promise containing updated thread details
1326
+ */
1327
+ update(params) {
1328
+ return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
1329
+ method: "PATCH",
1330
+ body: params
1331
+ });
1332
+ }
1333
+ /**
1334
+ * Deletes the memory thread
1335
+ * @returns Promise containing deletion result
1336
+ */
1337
+ delete() {
1338
+ return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
1339
+ method: "DELETE"
1340
+ });
1341
+ }
1342
+ /**
1343
+ * Retrieves messages associated with the thread
1344
+ * @param params - Optional parameters including limit for number of messages to retrieve
1345
+ * @returns Promise containing thread messages and UI messages
1346
+ */
1347
+ getMessages(params) {
1348
+ const query = new URLSearchParams({
1349
+ agentId: this.agentId,
1350
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1351
+ });
1352
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
1353
+ }
1354
+ /**
1355
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1356
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1357
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1358
+ */
1359
+ getMessagesPaginated({
1360
+ selectBy,
1361
+ ...rest
1362
+ }) {
1363
+ const query = new URLSearchParams({
1364
+ ...rest,
1365
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1366
+ });
1367
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1368
+ }
1369
+ /**
1370
+ * Deletes one or more messages from the thread
1371
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1372
+ * message object with id property, or array of message objects
1373
+ * @returns Promise containing deletion result
1374
+ */
1375
+ deleteMessages(messageIds) {
1376
+ const query = new URLSearchParams({
1377
+ agentId: this.agentId
1378
+ });
1379
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1380
+ method: "POST",
1381
+ body: { messageIds }
1382
+ });
1383
+ }
1384
+ };
1385
+
1386
+ // src/resources/vector.ts
1387
+ var Vector = class extends BaseResource {
1388
+ constructor(options, vectorName) {
1389
+ super(options);
1390
+ this.vectorName = vectorName;
1391
+ }
1392
+ /**
1393
+ * Retrieves details about a specific vector index
1394
+ * @param indexName - Name of the index to get details for
1395
+ * @returns Promise containing vector index details
1396
+ */
1397
+ details(indexName) {
1398
+ return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1399
+ }
1400
+ /**
1401
+ * Deletes a vector index
1402
+ * @param indexName - Name of the index to delete
1403
+ * @returns Promise indicating deletion success
1404
+ */
1405
+ delete(indexName) {
1406
+ return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`, {
1407
+ method: "DELETE"
1408
+ });
1409
+ }
1410
+ /**
1411
+ * Retrieves a list of all available indexes
1412
+ * @returns Promise containing array of index names
1413
+ */
1414
+ getIndexes() {
1415
+ return this.request(`/api/vector/${this.vectorName}/indexes`);
1416
+ }
1417
+ /**
1418
+ * Creates a new vector index
1419
+ * @param params - Parameters for index creation including dimension and metric
1420
+ * @returns Promise indicating creation success
1421
+ */
1422
+ createIndex(params) {
1423
+ return this.request(`/api/vector/${this.vectorName}/create-index`, {
1424
+ method: "POST",
1425
+ body: params
1426
+ });
1427
+ }
1428
+ /**
1429
+ * Upserts vectors into an index
1430
+ * @param params - Parameters containing vectors, metadata, and optional IDs
1431
+ * @returns Promise containing array of vector IDs
1432
+ */
1433
+ upsert(params) {
1434
+ return this.request(`/api/vector/${this.vectorName}/upsert`, {
1435
+ method: "POST",
1436
+ body: params
1437
+ });
1438
+ }
1439
+ /**
1440
+ * Queries vectors in an index
1441
+ * @param params - Query parameters including query vector and search options
1442
+ * @returns Promise containing query results
1443
+ */
1444
+ query(params) {
1445
+ return this.request(`/api/vector/${this.vectorName}/query`, {
1446
+ method: "POST",
1447
+ body: params
1448
+ });
1449
+ }
1450
+ };
1451
+
1452
+ // src/resources/legacy-workflow.ts
1453
+ var RECORD_SEPARATOR = "";
1454
+ var LegacyWorkflow = class extends BaseResource {
1455
+ constructor(options, workflowId) {
1456
+ super(options);
1457
+ this.workflowId = workflowId;
1458
+ }
1459
+ /**
1460
+ * Retrieves details about the legacy workflow
1461
+ * @returns Promise containing legacy workflow details including steps and graphs
1462
+ */
1463
+ details() {
1464
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
1465
+ }
1466
+ /**
1467
+ * Retrieves all runs for a legacy workflow
1468
+ * @param params - Parameters for filtering runs
1469
+ * @returns Promise containing legacy workflow runs array
1470
+ */
1471
+ runs(params) {
1472
+ const searchParams = new URLSearchParams();
1473
+ if (params?.fromDate) {
1474
+ searchParams.set("fromDate", params.fromDate.toISOString());
1475
+ }
1476
+ if (params?.toDate) {
1477
+ searchParams.set("toDate", params.toDate.toISOString());
1478
+ }
1479
+ if (params?.limit) {
1480
+ searchParams.set("limit", String(params.limit));
1481
+ }
1482
+ if (params?.offset) {
1483
+ searchParams.set("offset", String(params.offset));
1484
+ }
1485
+ if (params?.resourceId) {
1486
+ searchParams.set("resourceId", params.resourceId);
1487
+ }
1488
+ if (searchParams.size) {
1489
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1490
+ } else {
1491
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1492
+ }
1493
+ }
1494
+ /**
1495
+ * Creates a new legacy workflow run
1496
+ * @returns Promise containing the generated run ID
1497
+ */
1498
+ createRun(params) {
1499
+ const searchParams = new URLSearchParams();
1500
+ if (!!params?.runId) {
1501
+ searchParams.set("runId", params.runId);
1502
+ }
1503
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1504
+ method: "POST"
1505
+ });
1506
+ }
1507
+ /**
1508
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1509
+ * @param params - Object containing the runId and triggerData
1510
+ * @returns Promise containing success message
1511
+ */
1512
+ start(params) {
1513
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1514
+ method: "POST",
1515
+ body: params?.triggerData
1516
+ });
1517
+ }
1518
+ /**
1519
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
1520
+ * @param stepId - ID of the step to resume
1521
+ * @param runId - ID of the legacy workflow run
1522
+ * @param context - Context to resume the legacy workflow with
1523
+ * @returns Promise containing the legacy workflow resume results
1524
+ */
1525
+ resume({
1526
+ stepId,
1527
+ runId,
1528
+ context
1529
+ }) {
1530
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
1531
+ method: "POST",
1532
+ body: {
1533
+ stepId,
1534
+ context
1535
+ }
1536
+ });
1537
+ }
1538
+ /**
1539
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1540
+ * @param params - Object containing the optional runId and triggerData
1541
+ * @returns Promise containing the workflow execution results
1542
+ */
1543
+ startAsync(params) {
1544
+ const searchParams = new URLSearchParams();
1545
+ if (!!params?.runId) {
1546
+ searchParams.set("runId", params.runId);
1547
+ }
1548
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1549
+ method: "POST",
1550
+ body: params?.triggerData
1551
+ });
1552
+ }
1553
+ /**
1554
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1555
+ * @param params - Object containing the runId, stepId, and context
1556
+ * @returns Promise containing the workflow resume results
1557
+ */
1558
+ resumeAsync(params) {
1559
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1560
+ method: "POST",
1561
+ body: {
1562
+ stepId: params.stepId,
1563
+ context: params.context
1564
+ }
1565
+ });
1566
+ }
1567
+ /**
1568
+ * Creates an async generator that processes a readable stream and yields records
1569
+ * separated by the Record Separator character (\x1E)
1570
+ *
1571
+ * @param stream - The readable stream to process
1572
+ * @returns An async generator that yields parsed records
1573
+ */
1574
+ async *streamProcessor(stream) {
1575
+ const reader = stream.getReader();
1576
+ let doneReading = false;
1577
+ let buffer = "";
1578
+ try {
1579
+ while (!doneReading) {
1580
+ const { done, value } = await reader.read();
1581
+ doneReading = done;
1582
+ if (done && !value) continue;
1583
+ try {
1584
+ const decoded = value ? new TextDecoder().decode(value) : "";
1585
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1586
+ buffer = chunks.pop() || "";
1587
+ for (const chunk of chunks) {
1588
+ if (chunk) {
1589
+ if (typeof chunk === "string") {
1590
+ try {
1591
+ const parsedChunk = JSON.parse(chunk);
1592
+ yield parsedChunk;
1593
+ } catch {
1594
+ }
1595
+ }
1596
+ }
1597
+ }
1598
+ } catch {
1599
+ }
1600
+ }
1601
+ if (buffer) {
1602
+ try {
1603
+ yield JSON.parse(buffer);
1604
+ } catch {
1605
+ }
1606
+ }
1607
+ } finally {
1608
+ reader.cancel().catch(() => {
1609
+ });
1610
+ }
1611
+ }
1612
+ /**
1613
+ * Watches legacy workflow transitions in real-time
1614
+ * @param runId - Optional run ID to filter the watch stream
1615
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1616
+ */
1617
+ async watch({ runId }, onRecord) {
1618
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1619
+ stream: true
1620
+ });
1621
+ if (!response.ok) {
1622
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1623
+ }
1624
+ if (!response.body) {
1625
+ throw new Error("Response body is null");
1626
+ }
1627
+ for await (const record of this.streamProcessor(response.body)) {
1628
+ onRecord(record);
1629
+ }
1630
+ }
1631
+ };
1632
+
1633
+ // src/resources/tool.ts
1634
+ var Tool = class extends BaseResource {
1635
+ constructor(options, toolId) {
1636
+ super(options);
1637
+ this.toolId = toolId;
1638
+ }
1639
+ /**
1640
+ * Retrieves details about the tool
1641
+ * @returns Promise containing tool details including description and schemas
1642
+ */
1643
+ details() {
1644
+ return this.request(`/api/tools/${this.toolId}`);
1645
+ }
1646
+ /**
1647
+ * Executes the tool with the provided parameters
1648
+ * @param params - Parameters required for tool execution
1649
+ * @returns Promise containing the tool execution results
1650
+ */
1651
+ execute(params) {
1652
+ const url = new URLSearchParams();
1653
+ if (params.runId) {
1654
+ url.set("runId", params.runId);
1655
+ }
1656
+ const body = {
1657
+ data: params.data,
1658
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1659
+ };
1660
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1661
+ method: "POST",
1662
+ body
1663
+ });
1664
+ }
1665
+ };
1666
+
1667
+ // src/resources/workflow.ts
1668
+ var RECORD_SEPARATOR2 = "";
1669
+ var Workflow = class extends BaseResource {
1670
+ constructor(options, workflowId) {
1671
+ super(options);
1672
+ this.workflowId = workflowId;
1673
+ }
1674
+ /**
1675
+ * Creates an async generator that processes a readable stream and yields workflow records
1676
+ * separated by the Record Separator character (\x1E)
1677
+ *
1678
+ * @param stream - The readable stream to process
1679
+ * @returns An async generator that yields parsed records
1680
+ */
1681
+ async *streamProcessor(stream) {
1682
+ const reader = stream.getReader();
1683
+ let doneReading = false;
1684
+ let buffer = "";
1685
+ try {
1686
+ while (!doneReading) {
1687
+ const { done, value } = await reader.read();
1688
+ doneReading = done;
1689
+ if (done && !value) continue;
1690
+ try {
1691
+ const decoded = value ? new TextDecoder().decode(value) : "";
1692
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1693
+ buffer = chunks.pop() || "";
1694
+ for (const chunk of chunks) {
1695
+ if (chunk) {
1696
+ if (typeof chunk === "string") {
1697
+ try {
1698
+ const parsedChunk = JSON.parse(chunk);
1699
+ yield parsedChunk;
1700
+ } catch {
1701
+ }
1702
+ }
1703
+ }
1704
+ }
1705
+ } catch {
1706
+ }
1707
+ }
1708
+ if (buffer) {
1709
+ try {
1710
+ yield JSON.parse(buffer);
1711
+ } catch {
1712
+ }
1713
+ }
1714
+ } finally {
1715
+ reader.cancel().catch(() => {
1716
+ });
1717
+ }
1718
+ }
1719
+ /**
1720
+ * Retrieves details about the workflow
1721
+ * @returns Promise containing workflow details including steps and graphs
1722
+ */
1723
+ details() {
1724
+ return this.request(`/api/workflows/${this.workflowId}`);
1725
+ }
1726
+ /**
1727
+ * Retrieves all runs for a workflow
1728
+ * @param params - Parameters for filtering runs
1729
+ * @returns Promise containing workflow runs array
1730
+ */
1731
+ runs(params) {
1732
+ const searchParams = new URLSearchParams();
1733
+ if (params?.fromDate) {
1734
+ searchParams.set("fromDate", params.fromDate.toISOString());
1735
+ }
1736
+ if (params?.toDate) {
1737
+ searchParams.set("toDate", params.toDate.toISOString());
1738
+ }
1739
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1740
+ searchParams.set("limit", String(params.limit));
1741
+ }
1742
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1743
+ searchParams.set("offset", String(params.offset));
1744
+ }
1745
+ if (params?.resourceId) {
1746
+ searchParams.set("resourceId", params.resourceId);
1747
+ }
1748
+ if (searchParams.size) {
1749
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1750
+ } else {
1751
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1752
+ }
1753
+ }
1754
+ /**
1755
+ * Retrieves a specific workflow run by its ID
1756
+ * @param runId - The ID of the workflow run to retrieve
1757
+ * @returns Promise containing the workflow run details
1758
+ */
1759
+ runById(runId) {
1760
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1761
+ }
1762
+ /**
1763
+ * Retrieves the execution result for a specific workflow run by its ID
1764
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1765
+ * @returns Promise containing the workflow run execution result
1766
+ */
1767
+ runExecutionResult(runId) {
1768
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1769
+ }
1770
+ /**
1771
+ * Cancels a specific workflow run by its ID
1772
+ * @param runId - The ID of the workflow run to cancel
1773
+ * @returns Promise containing a success message
1774
+ */
1775
+ cancelRun(runId) {
1776
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1777
+ method: "POST"
1778
+ });
1779
+ }
1780
+ /**
1781
+ * Sends an event to a specific workflow run by its ID
1782
+ * @param params - Object containing the runId, event and data
1783
+ * @returns Promise containing a success message
1784
+ */
1785
+ sendRunEvent(params) {
1786
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1787
+ method: "POST",
1788
+ body: { event: params.event, data: params.data }
1789
+ });
1790
+ }
1791
+ /**
1792
+ * Creates a new workflow run
1793
+ * @param params - Optional object containing the optional runId
1794
+ * @returns Promise containing the runId of the created run
1795
+ */
1796
+ createRun(params) {
1797
+ const searchParams = new URLSearchParams();
1798
+ if (!!params?.runId) {
1799
+ searchParams.set("runId", params.runId);
1800
+ }
1801
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1802
+ method: "POST"
1803
+ });
1804
+ }
1805
+ /**
1806
+ * Creates a new workflow run (alias for createRun)
1807
+ * @param params - Optional object containing the optional runId
1808
+ * @returns Promise containing the runId of the created run
1809
+ */
1810
+ createRunAsync(params) {
1811
+ return this.createRun(params);
1812
+ }
1813
+ /**
1814
+ * Starts a workflow run synchronously without waiting for the workflow to complete
1815
+ * @param params - Object containing the runId, inputData and runtimeContext
1816
+ * @returns Promise containing success message
1817
+ */
1818
+ start(params) {
1819
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1820
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1821
+ method: "POST",
1822
+ body: { inputData: params?.inputData, runtimeContext }
1823
+ });
1824
+ }
1825
+ /**
1826
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1827
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1828
+ * @returns Promise containing success message
1829
+ */
1830
+ resume({
1831
+ step,
1832
+ runId,
1833
+ resumeData,
1834
+ ...rest
1835
+ }) {
1836
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1837
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1838
+ method: "POST",
1839
+ stream: true,
1840
+ body: {
1841
+ step,
1842
+ resumeData,
1843
+ runtimeContext
1844
+ }
1845
+ });
1846
+ }
1847
+ /**
1848
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1849
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1850
+ * @returns Promise containing the workflow execution results
1851
+ */
1852
+ startAsync(params) {
1853
+ const searchParams = new URLSearchParams();
1854
+ if (!!params?.runId) {
1855
+ searchParams.set("runId", params.runId);
1856
+ }
1857
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1858
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1859
+ method: "POST",
1860
+ body: { inputData: params.inputData, runtimeContext }
1861
+ });
1862
+ }
1863
+ /**
1864
+ * Starts a workflow run and returns a stream
1865
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1866
+ * @returns Promise containing the workflow execution results
1867
+ */
1868
+ async stream(params) {
1869
+ const searchParams = new URLSearchParams();
1870
+ if (!!params?.runId) {
1871
+ searchParams.set("runId", params.runId);
1872
+ }
1873
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1874
+ const response = await this.request(
1875
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1876
+ {
1877
+ method: "POST",
1878
+ body: { inputData: params.inputData, runtimeContext },
1879
+ stream: true
1880
+ }
1881
+ );
1882
+ if (!response.ok) {
1883
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1884
+ }
1885
+ if (!response.body) {
1886
+ throw new Error("Response body is null");
1887
+ }
1888
+ let failedChunk = void 0;
1889
+ const transformStream = new TransformStream({
1890
+ start() {
1891
+ },
1892
+ async transform(chunk, controller) {
1893
+ try {
1894
+ const decoded = new TextDecoder().decode(chunk);
1895
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1896
+ for (const chunk2 of chunks) {
1897
+ if (chunk2) {
1898
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1899
+ try {
1900
+ const parsedChunk = JSON.parse(newChunk);
1901
+ controller.enqueue(parsedChunk);
1902
+ failedChunk = void 0;
1903
+ } catch {
1904
+ failedChunk = newChunk;
1905
+ }
1906
+ }
1907
+ }
1908
+ } catch {
1909
+ }
1910
+ }
1911
+ });
1912
+ return response.body.pipeThrough(transformStream);
1913
+ }
1914
+ /**
1915
+ * Starts a workflow run and returns a stream
1916
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1917
+ * @returns Promise containing the workflow execution results
1918
+ */
1919
+ async streamVNext(params) {
1920
+ const searchParams = new URLSearchParams();
1921
+ if (!!params?.runId) {
1922
+ searchParams.set("runId", params.runId);
1923
+ }
1924
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1925
+ const response = await this.request(
1926
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1927
+ {
1928
+ method: "POST",
1929
+ body: { inputData: params.inputData, runtimeContext },
1930
+ stream: true
1931
+ }
1932
+ );
1933
+ if (!response.ok) {
1934
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1935
+ }
1936
+ if (!response.body) {
1937
+ throw new Error("Response body is null");
1938
+ }
1939
+ let failedChunk = void 0;
1940
+ const transformStream = new TransformStream({
1941
+ start() {
1942
+ },
1943
+ async transform(chunk, controller) {
1944
+ try {
1945
+ const decoded = new TextDecoder().decode(chunk);
1946
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1947
+ for (const chunk2 of chunks) {
1948
+ if (chunk2) {
1949
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1950
+ try {
1951
+ const parsedChunk = JSON.parse(newChunk);
1952
+ controller.enqueue(parsedChunk);
1953
+ failedChunk = void 0;
1954
+ } catch {
1955
+ failedChunk = newChunk;
1956
+ }
1957
+ }
1958
+ }
1959
+ } catch {
1960
+ }
1961
+ }
1962
+ });
1963
+ return response.body.pipeThrough(transformStream);
1964
+ }
1965
+ /**
1966
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1967
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1968
+ * @returns Promise containing the workflow resume results
1969
+ */
1970
+ resumeAsync(params) {
1971
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1972
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1973
+ method: "POST",
1974
+ body: {
1975
+ step: params.step,
1976
+ resumeData: params.resumeData,
1977
+ runtimeContext
1978
+ }
1979
+ });
1980
+ }
1981
+ /**
1982
+ * Watches workflow transitions in real-time
1983
+ * @param runId - Optional run ID to filter the watch stream
1984
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1985
+ */
1986
+ async watch({ runId }, onRecord) {
1987
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1988
+ stream: true
1989
+ });
1990
+ if (!response.ok) {
1991
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1992
+ }
1993
+ if (!response.body) {
1994
+ throw new Error("Response body is null");
1995
+ }
1996
+ for await (const record of this.streamProcessor(response.body)) {
1997
+ if (typeof record === "string") {
1998
+ onRecord(JSON.parse(record));
1999
+ } else {
2000
+ onRecord(record);
2001
+ }
2002
+ }
2003
+ }
2004
+ /**
2005
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2006
+ * serializing each as JSON and separating them with the record separator (\x1E).
2007
+ *
2008
+ * @param records - An iterable or async iterable of objects to stream
2009
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2010
+ */
2011
+ static createRecordStream(records) {
2012
+ const encoder = new TextEncoder();
2013
+ return new ReadableStream({
2014
+ async start(controller) {
2015
+ try {
2016
+ for await (const record of records) {
2017
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2018
+ controller.enqueue(encoder.encode(json));
2019
+ }
2020
+ controller.close();
2021
+ } catch (err) {
2022
+ controller.error(err);
2023
+ }
2024
+ }
2025
+ });
2026
+ }
2027
+ };
2028
+
2029
+ // src/resources/a2a.ts
2030
+ var A2A = class extends BaseResource {
2031
+ constructor(options, agentId) {
2032
+ super(options);
2033
+ this.agentId = agentId;
2034
+ }
2035
+ /**
2036
+ * Get the agent card with metadata about the agent
2037
+ * @returns Promise containing the agent card information
2038
+ */
2039
+ async getCard() {
2040
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2041
+ }
2042
+ /**
2043
+ * Send a message to the agent and gets a message or task response
2044
+ * @param params - Parameters for the task
2045
+ * @returns Promise containing the response
2046
+ */
2047
+ async sendMessage(params) {
2048
+ const response = await this.request(`/a2a/${this.agentId}`, {
2049
+ method: "POST",
2050
+ body: {
2051
+ method: "message/send",
2052
+ params
2053
+ }
2054
+ });
2055
+ return response;
2056
+ }
2057
+ /**
2058
+ * Sends a message to an agent to initiate/continue a task and subscribes
2059
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2060
+ * @param params - Parameters for the task
2061
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2062
+ */
2063
+ async sendStreamingMessage(params) {
2064
+ const response = await this.request(`/a2a/${this.agentId}`, {
2065
+ method: "POST",
2066
+ body: {
2067
+ method: "message/stream",
2068
+ params
2069
+ }
2070
+ });
2071
+ return response;
2072
+ }
2073
+ /**
2074
+ * Get the status and result of a task
2075
+ * @param params - Parameters for querying the task
2076
+ * @returns Promise containing the task response
2077
+ */
2078
+ async getTask(params) {
2079
+ const response = await this.request(`/a2a/${this.agentId}`, {
2080
+ method: "POST",
2081
+ body: {
2082
+ method: "tasks/get",
2083
+ params
2084
+ }
2085
+ });
2086
+ return response;
2087
+ }
2088
+ /**
2089
+ * Cancel a running task
2090
+ * @param params - Parameters identifying the task to cancel
2091
+ * @returns Promise containing the task response
2092
+ */
2093
+ async cancelTask(params) {
2094
+ return this.request(`/a2a/${this.agentId}`, {
2095
+ method: "POST",
2096
+ body: {
2097
+ method: "tasks/cancel",
2098
+ params
2099
+ }
2100
+ });
2101
+ }
2102
+ };
2103
+
2104
+ // src/resources/mcp-tool.ts
2105
+ var MCPTool = class extends BaseResource {
2106
+ serverId;
2107
+ toolId;
2108
+ constructor(options, serverId, toolId) {
2109
+ super(options);
2110
+ this.serverId = serverId;
2111
+ this.toolId = toolId;
2112
+ }
2113
+ /**
2114
+ * Retrieves details about this specific tool from the MCP server.
2115
+ * @returns Promise containing the tool's information (name, description, schema).
2116
+ */
2117
+ details() {
2118
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2119
+ }
2120
+ /**
2121
+ * Executes this specific tool on the MCP server.
2122
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2123
+ * @returns Promise containing the result of the tool execution.
2124
+ */
2125
+ execute(params) {
2126
+ const body = {};
2127
+ if (params.data !== void 0) body.data = params.data;
2128
+ if (params.runtimeContext !== void 0) {
2129
+ body.runtimeContext = params.runtimeContext;
2130
+ }
2131
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2132
+ method: "POST",
2133
+ body: Object.keys(body).length > 0 ? body : void 0
2134
+ });
2135
+ }
2136
+ };
2137
+
2138
+ // src/resources/agent-builder.ts
2139
+ var RECORD_SEPARATOR3 = "";
2140
+ var AgentBuilder = class extends BaseResource {
2141
+ constructor(options, actionId) {
2142
+ super(options);
2143
+ this.actionId = actionId;
2144
+ }
2145
+ // Helper function to transform workflow result to action result
2146
+ transformWorkflowResult(result) {
2147
+ if (result.status === "success") {
2148
+ return {
2149
+ success: result.result.success || false,
2150
+ applied: result.result.applied || false,
2151
+ branchName: result.result.branchName,
2152
+ message: result.result.message || "Agent builder action completed",
2153
+ validationResults: result.result.validationResults,
2154
+ error: result.result.error,
2155
+ errors: result.result.errors,
2156
+ stepResults: result.result.stepResults
2157
+ };
2158
+ } else if (result.status === "failed") {
2159
+ return {
2160
+ success: false,
2161
+ applied: false,
2162
+ message: `Agent builder action failed: ${result.error.message}`,
2163
+ error: result.error.message
2164
+ };
2165
+ } else {
2166
+ return {
2167
+ success: false,
2168
+ applied: false,
2169
+ message: "Agent builder action was suspended",
2170
+ error: "Workflow suspended - manual intervention required"
2171
+ };
2172
+ }
2173
+ }
2174
+ /**
2175
+ * Creates a new agent builder action run and returns the runId.
2176
+ * This calls `/api/agent-builder/:actionId/create-run`.
2177
+ */
2178
+ async createRun(params) {
2179
+ const searchParams = new URLSearchParams();
2180
+ if (!!params?.runId) {
2181
+ searchParams.set("runId", params.runId);
2182
+ }
2183
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2184
+ return this.request(url, {
2185
+ method: "POST"
2186
+ });
2187
+ }
2188
+ /**
2189
+ * Creates a new workflow run (alias for createRun)
2190
+ * @param params - Optional object containing the optional runId
2191
+ * @returns Promise containing the runId of the created run
2192
+ */
2193
+ createRunAsync(params) {
2194
+ return this.createRun(params);
2195
+ }
2196
+ /**
2197
+ * Starts agent builder action asynchronously and waits for completion.
2198
+ * This calls `/api/agent-builder/:actionId/start-async`.
2199
+ */
2200
+ async startAsync(params, runId) {
2201
+ const searchParams = new URLSearchParams();
2202
+ if (runId) {
2203
+ searchParams.set("runId", runId);
2204
+ }
2205
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2206
+ const { runtimeContext: _, ...actionParams } = params;
2207
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2208
+ const result = await this.request(url, {
2209
+ method: "POST",
2210
+ body: { ...actionParams, runtimeContext }
2211
+ });
2212
+ return this.transformWorkflowResult(result);
2213
+ }
2214
+ /**
2215
+ * Starts an existing agent builder action run.
2216
+ * This calls `/api/agent-builder/:actionId/start`.
2217
+ */
2218
+ async startActionRun(params, runId) {
2219
+ const searchParams = new URLSearchParams();
2220
+ searchParams.set("runId", runId);
2221
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2222
+ const { runtimeContext: _, ...actionParams } = params;
2223
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2224
+ return this.request(url, {
2225
+ method: "POST",
2226
+ body: { ...actionParams, runtimeContext }
2227
+ });
2228
+ }
2229
+ /**
2230
+ * Resumes a suspended agent builder action step.
2231
+ * This calls `/api/agent-builder/:actionId/resume`.
2232
+ */
2233
+ async resume(params, runId) {
2234
+ const searchParams = new URLSearchParams();
2235
+ searchParams.set("runId", runId);
2236
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2237
+ const { runtimeContext: _, ...resumeParams } = params;
2238
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2239
+ return this.request(url, {
2240
+ method: "POST",
2241
+ body: { ...resumeParams, runtimeContext }
2242
+ });
2243
+ }
2244
+ /**
2245
+ * Resumes a suspended agent builder action step asynchronously.
2246
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2247
+ */
2248
+ async resumeAsync(params, runId) {
2249
+ const searchParams = new URLSearchParams();
2250
+ searchParams.set("runId", runId);
2251
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2252
+ const { runtimeContext: _, ...resumeParams } = params;
2253
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2254
+ const result = await this.request(url, {
2255
+ method: "POST",
2256
+ body: { ...resumeParams, runtimeContext }
2257
+ });
2258
+ return this.transformWorkflowResult(result);
2259
+ }
2260
+ /**
2261
+ * Creates an async generator that processes a readable stream and yields action records
2262
+ * separated by the Record Separator character (\x1E)
2263
+ *
2264
+ * @param stream - The readable stream to process
2265
+ * @returns An async generator that yields parsed records
2266
+ */
2267
+ async *streamProcessor(stream) {
2268
+ const reader = stream.getReader();
2269
+ let doneReading = false;
2270
+ let buffer = "";
2271
+ try {
2272
+ while (!doneReading) {
2273
+ const { done, value } = await reader.read();
2274
+ doneReading = done;
2275
+ if (done && !value) continue;
2276
+ try {
2277
+ const decoded = value ? new TextDecoder().decode(value) : "";
2278
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2279
+ buffer = chunks.pop() || "";
2280
+ for (const chunk of chunks) {
2281
+ if (chunk) {
2282
+ if (typeof chunk === "string") {
2283
+ try {
2284
+ const parsedChunk = JSON.parse(chunk);
2285
+ yield parsedChunk;
2286
+ } catch {
2287
+ }
2288
+ }
2289
+ }
2290
+ }
2291
+ } catch {
2292
+ }
2293
+ }
2294
+ if (buffer) {
2295
+ try {
2296
+ yield JSON.parse(buffer);
2297
+ } catch {
2298
+ }
2299
+ }
2300
+ } finally {
2301
+ reader.cancel().catch(() => {
2302
+ });
2303
+ }
2304
+ }
2305
+ /**
2306
+ * Streams agent builder action progress in real-time.
2307
+ * This calls `/api/agent-builder/:actionId/stream`.
2308
+ */
2309
+ async stream(params, runId) {
2310
+ const searchParams = new URLSearchParams();
2311
+ if (runId) {
2312
+ searchParams.set("runId", runId);
2313
+ }
2314
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2315
+ const { runtimeContext: _, ...actionParams } = params;
2316
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2317
+ const response = await this.request(url, {
2318
+ method: "POST",
2319
+ body: { ...actionParams, runtimeContext },
2320
+ stream: true
2321
+ });
2322
+ if (!response.ok) {
2323
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2324
+ }
2325
+ if (!response.body) {
2326
+ throw new Error("Response body is null");
2327
+ }
2328
+ let failedChunk = void 0;
2329
+ const transformStream = new TransformStream({
2330
+ start() {
2331
+ },
2332
+ async transform(chunk, controller) {
2333
+ try {
2334
+ const decoded = new TextDecoder().decode(chunk);
2335
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2336
+ for (const chunk2 of chunks) {
2337
+ if (chunk2) {
2338
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2339
+ try {
2340
+ const parsedChunk = JSON.parse(newChunk);
2341
+ controller.enqueue(parsedChunk);
2342
+ failedChunk = void 0;
2343
+ } catch {
2344
+ failedChunk = newChunk;
2345
+ }
2346
+ }
2347
+ }
2348
+ } catch {
2349
+ }
2350
+ }
2351
+ });
2352
+ return response.body.pipeThrough(transformStream);
2353
+ }
2354
+ /**
2355
+ * Streams agent builder action progress in real-time using VNext streaming.
2356
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2357
+ */
2358
+ async streamVNext(params, runId) {
2359
+ const searchParams = new URLSearchParams();
2360
+ if (runId) {
2361
+ searchParams.set("runId", runId);
2362
+ }
2363
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2364
+ const { runtimeContext: _, ...actionParams } = params;
2365
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2366
+ const response = await this.request(url, {
2367
+ method: "POST",
2368
+ body: { ...actionParams, runtimeContext },
2369
+ stream: true
2370
+ });
2371
+ if (!response.ok) {
2372
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2373
+ }
2374
+ if (!response.body) {
2375
+ throw new Error("Response body is null");
2376
+ }
2377
+ let failedChunk = void 0;
2378
+ const transformStream = new TransformStream({
2379
+ start() {
2380
+ },
2381
+ async transform(chunk, controller) {
2382
+ try {
2383
+ const decoded = new TextDecoder().decode(chunk);
2384
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2385
+ for (const chunk2 of chunks) {
2386
+ if (chunk2) {
2387
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2388
+ try {
2389
+ const parsedChunk = JSON.parse(newChunk);
2390
+ controller.enqueue(parsedChunk);
2391
+ failedChunk = void 0;
2392
+ } catch {
2393
+ failedChunk = newChunk;
2394
+ }
2395
+ }
2396
+ }
2397
+ } catch {
2398
+ }
2399
+ }
2400
+ });
2401
+ return response.body.pipeThrough(transformStream);
2402
+ }
2403
+ /**
2404
+ * Watches an existing agent builder action run by runId.
2405
+ * This is used for hot reload recovery - it loads the existing run state
2406
+ * and streams any remaining progress.
2407
+ * This calls `/api/agent-builder/:actionId/watch`.
2408
+ */
2409
+ async watch({ runId, eventType }, onRecord) {
2410
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2411
+ const response = await this.request(url, {
2412
+ method: "GET",
2413
+ stream: true
2414
+ });
2415
+ if (!response.ok) {
2416
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2417
+ }
2418
+ if (!response.body) {
2419
+ throw new Error("Response body is null");
2420
+ }
2421
+ for await (const record of this.streamProcessor(response.body)) {
2422
+ if (typeof record === "string") {
2423
+ onRecord(JSON.parse(record));
2424
+ } else {
2425
+ onRecord(record);
2426
+ }
2427
+ }
2428
+ }
2429
+ /**
2430
+ * Gets a specific action run by its ID.
2431
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2432
+ */
2433
+ async runById(runId) {
2434
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2435
+ return this.request(url, {
2436
+ method: "GET"
2437
+ });
2438
+ }
2439
+ /**
2440
+ * Gets details about this agent builder action.
2441
+ * This calls `/api/agent-builder/:actionId`.
2442
+ */
2443
+ async details() {
2444
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2445
+ return result;
2446
+ }
2447
+ /**
2448
+ * Gets all runs for this agent builder action.
2449
+ * This calls `/api/agent-builder/:actionId/runs`.
2450
+ */
2451
+ async runs(params) {
2452
+ const searchParams = new URLSearchParams();
2453
+ if (params?.fromDate) {
2454
+ searchParams.set("fromDate", params.fromDate.toISOString());
2455
+ }
2456
+ if (params?.toDate) {
2457
+ searchParams.set("toDate", params.toDate.toISOString());
2458
+ }
2459
+ if (params?.limit !== void 0) {
2460
+ searchParams.set("limit", String(params.limit));
2461
+ }
2462
+ if (params?.offset !== void 0) {
2463
+ searchParams.set("offset", String(params.offset));
2464
+ }
2465
+ if (params?.resourceId) {
2466
+ searchParams.set("resourceId", params.resourceId);
2467
+ }
2468
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2469
+ return this.request(url, {
2470
+ method: "GET"
2471
+ });
2472
+ }
2473
+ /**
2474
+ * Gets the execution result of an agent builder action run.
2475
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2476
+ */
2477
+ async runExecutionResult(runId) {
2478
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2479
+ return this.request(url, {
2480
+ method: "GET"
2481
+ });
2482
+ }
2483
+ /**
2484
+ * Cancels an agent builder action run.
2485
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2486
+ */
2487
+ async cancelRun(runId) {
2488
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2489
+ return this.request(url, {
2490
+ method: "POST"
2491
+ });
2492
+ }
2493
+ /**
2494
+ * Sends an event to an agent builder action run.
2495
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2496
+ */
2497
+ async sendRunEvent(params) {
2498
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2499
+ return this.request(url, {
2500
+ method: "POST",
2501
+ body: { event: params.event, data: params.data }
2502
+ });
2503
+ }
2504
+ };
2505
+
2506
+ // src/resources/observability.ts
2507
+ var Observability = class extends BaseResource {
2508
+ constructor(options) {
2509
+ super(options);
2510
+ }
2511
+ /**
2512
+ * Retrieves a specific AI trace by ID
2513
+ * @param traceId - ID of the trace to retrieve
2514
+ * @returns Promise containing the AI trace with all its spans
2515
+ */
2516
+ getTrace(traceId) {
2517
+ return this.request(`/api/observability/traces/${traceId}`);
2518
+ }
2519
+ /**
2520
+ * Retrieves paginated list of AI traces with optional filtering
2521
+ * @param params - Parameters for pagination and filtering
2522
+ * @returns Promise containing paginated traces and pagination info
2523
+ */
2524
+ getTraces(params) {
2525
+ const { pagination, filters } = params;
2526
+ const { page, perPage, dateRange } = pagination || {};
2527
+ const { name, spanType } = filters || {};
2528
+ const searchParams = new URLSearchParams();
2529
+ if (page !== void 0) {
2530
+ searchParams.set("page", String(page));
2531
+ }
2532
+ if (perPage !== void 0) {
2533
+ searchParams.set("perPage", String(perPage));
2534
+ }
2535
+ if (name) {
2536
+ searchParams.set("name", name);
2537
+ }
2538
+ if (spanType !== void 0) {
2539
+ searchParams.set("spanType", String(spanType));
2540
+ }
2541
+ if (dateRange) {
2542
+ const dateRangeStr = JSON.stringify({
2543
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2544
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2545
+ });
2546
+ searchParams.set("dateRange", dateRangeStr);
2547
+ }
2548
+ const queryString = searchParams.toString();
2549
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2550
+ }
2551
+ };
2552
+
2553
+ // src/resources/network-memory-thread.ts
2554
+ var NetworkMemoryThread = class extends BaseResource {
2555
+ constructor(options, threadId, networkId) {
2556
+ super(options);
2557
+ this.threadId = threadId;
2558
+ this.networkId = networkId;
2559
+ }
2560
+ /**
2561
+ * Retrieves the memory thread details
2562
+ * @returns Promise containing thread details including title and metadata
2563
+ */
2564
+ get() {
2565
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
2566
+ }
2567
+ /**
2568
+ * Updates the memory thread properties
2569
+ * @param params - Update parameters including title and metadata
2570
+ * @returns Promise containing updated thread details
2571
+ */
2572
+ update(params) {
2573
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2574
+ method: "PATCH",
2575
+ body: params
2576
+ });
2577
+ }
2578
+ /**
2579
+ * Deletes the memory thread
2580
+ * @returns Promise containing deletion result
2581
+ */
2582
+ delete() {
2583
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2584
+ method: "DELETE"
2585
+ });
2586
+ }
2587
+ /**
2588
+ * Retrieves messages associated with the thread
2589
+ * @param params - Optional parameters including limit for number of messages to retrieve
2590
+ * @returns Promise containing thread messages and UI messages
2591
+ */
2592
+ getMessages(params) {
2593
+ const query = new URLSearchParams({
2594
+ networkId: this.networkId,
2595
+ ...params?.limit ? { limit: params.limit.toString() } : {}
2596
+ });
2597
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
2598
+ }
2599
+ /**
2600
+ * Deletes one or more messages from the thread
2601
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2602
+ * message object with id property, or array of message objects
2603
+ * @returns Promise containing deletion result
2604
+ */
2605
+ deleteMessages(messageIds) {
2606
+ const query = new URLSearchParams({
2607
+ networkId: this.networkId
2608
+ });
2609
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
2610
+ method: "POST",
2611
+ body: { messageIds }
2612
+ });
2613
+ }
2614
+ };
2615
+
2616
+ // src/resources/vNextNetwork.ts
2617
+ var RECORD_SEPARATOR4 = "";
2618
+ var VNextNetwork = class extends BaseResource {
2619
+ constructor(options, networkId) {
2620
+ super(options);
2621
+ this.networkId = networkId;
2622
+ }
2623
+ /**
2624
+ * Retrieves details about the network
2625
+ * @returns Promise containing vNext network details
2626
+ */
2627
+ details() {
2628
+ return this.request(`/api/networks/v-next/${this.networkId}`);
2629
+ }
2630
+ /**
2631
+ * Generates a response from the v-next network
2632
+ * @param params - Generation parameters including message
2633
+ * @returns Promise containing the generated response
2634
+ */
2635
+ generate(params) {
2636
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
2637
+ method: "POST",
2638
+ body: {
2639
+ ...params,
2640
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2641
+ }
2642
+ });
2643
+ }
2644
+ /**
2645
+ * Generates a response from the v-next network using multiple primitives
2646
+ * @param params - Generation parameters including message
2647
+ * @returns Promise containing the generated response
2648
+ */
2649
+ loop(params) {
2650
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
2651
+ method: "POST",
2652
+ body: {
2653
+ ...params,
2654
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2655
+ }
2656
+ });
2657
+ }
2658
+ async *streamProcessor(stream) {
2659
+ const reader = stream.getReader();
2660
+ let doneReading = false;
2661
+ let buffer = "";
2662
+ try {
2663
+ while (!doneReading) {
2664
+ const { done, value } = await reader.read();
2665
+ doneReading = done;
2666
+ if (done && !value) continue;
2667
+ try {
2668
+ const decoded = value ? new TextDecoder().decode(value) : "";
2669
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
2670
+ buffer = chunks.pop() || "";
2671
+ for (const chunk of chunks) {
2672
+ if (chunk) {
2673
+ if (typeof chunk === "string") {
2674
+ try {
2675
+ const parsedChunk = JSON.parse(chunk);
2676
+ yield parsedChunk;
2677
+ } catch {
2678
+ }
2679
+ }
2680
+ }
2681
+ }
2682
+ } catch {
2683
+ }
2684
+ }
2685
+ if (buffer) {
2686
+ try {
2687
+ yield JSON.parse(buffer);
2688
+ } catch {
2689
+ }
2690
+ }
2691
+ } finally {
2692
+ reader.cancel().catch(() => {
2693
+ });
2694
+ }
2695
+ }
2696
+ /**
2697
+ * Streams a response from the v-next network
2698
+ * @param params - Stream parameters including message
2699
+ * @returns Promise containing the results
2700
+ */
2701
+ async stream(params, onRecord) {
2702
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
2703
+ method: "POST",
2704
+ body: {
2705
+ ...params,
2706
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2707
+ },
2708
+ stream: true
2709
+ });
2710
+ if (!response.ok) {
2711
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2712
+ }
2713
+ if (!response.body) {
2714
+ throw new Error("Response body is null");
2715
+ }
2716
+ for await (const record of this.streamProcessor(response.body)) {
2717
+ if (typeof record === "string") {
2718
+ onRecord(JSON.parse(record));
2719
+ } else {
2720
+ onRecord(record);
2721
+ }
2722
+ }
2723
+ }
2724
+ /**
2725
+ * Streams a response from the v-next network loop
2726
+ * @param params - Stream parameters including message
2727
+ * @returns Promise containing the results
2728
+ */
2729
+ async loopStream(params, onRecord) {
2730
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
2731
+ method: "POST",
2732
+ body: {
2733
+ ...params,
2734
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2735
+ },
2736
+ stream: true
2737
+ });
2738
+ if (!response.ok) {
2739
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2740
+ }
2741
+ if (!response.body) {
2742
+ throw new Error("Response body is null");
2743
+ }
2744
+ for await (const record of this.streamProcessor(response.body)) {
2745
+ if (typeof record === "string") {
2746
+ onRecord(JSON.parse(record));
2747
+ } else {
2748
+ onRecord(record);
2749
+ }
2750
+ }
2751
+ }
2752
+ };
2753
+
2754
+ // src/client.ts
2755
+ var MastraClient = class extends BaseResource {
2756
+ observability;
2757
+ constructor(options) {
2758
+ super(options);
2759
+ this.observability = new Observability(options);
2760
+ }
2761
+ /**
2762
+ * Retrieves all available agents
2763
+ * @returns Promise containing map of agent IDs to agent details
2764
+ */
2765
+ getAgents() {
2766
+ return this.request("/api/agents");
2767
+ }
2768
+ /**
2769
+ * Gets an agent instance by ID
2770
+ * @param agentId - ID of the agent to retrieve
2771
+ * @returns Agent instance
2772
+ */
2773
+ getAgent(agentId) {
2774
+ return new Agent(this.options, agentId);
2775
+ }
2776
+ /**
2777
+ * Retrieves memory threads for a resource
2778
+ * @param params - Parameters containing the resource ID
2779
+ * @returns Promise containing array of memory threads
2780
+ */
2781
+ getMemoryThreads(params) {
2782
+ return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
2783
+ }
2784
+ /**
2785
+ * Creates a new memory thread
2786
+ * @param params - Parameters for creating the memory thread
2787
+ * @returns Promise containing the created memory thread
2788
+ */
2789
+ createMemoryThread(params) {
2790
+ return this.request(`/api/memory/threads?agentId=${params.agentId}`, { method: "POST", body: params });
2791
+ }
2792
+ /**
2793
+ * Gets a memory thread instance by ID
2794
+ * @param threadId - ID of the memory thread to retrieve
2795
+ * @returns MemoryThread instance
2796
+ */
2797
+ getMemoryThread(threadId, agentId) {
2798
+ return new MemoryThread(this.options, threadId, agentId);
2799
+ }
2800
+ /**
2801
+ * Saves messages to memory
2802
+ * @param params - Parameters containing messages to save
2803
+ * @returns Promise containing the saved messages
2804
+ */
2805
+ saveMessageToMemory(params) {
2806
+ return this.request(`/api/memory/save-messages?agentId=${params.agentId}`, {
2807
+ method: "POST",
2808
+ body: params
2809
+ });
2810
+ }
2811
+ /**
2812
+ * Gets the status of the memory system
2813
+ * @returns Promise containing memory system status
2814
+ */
2815
+ getMemoryStatus(agentId) {
2816
+ return this.request(`/api/memory/status?agentId=${agentId}`);
2817
+ }
2818
+ /**
2819
+ * Retrieves memory threads for a resource
2820
+ * @param params - Parameters containing the resource ID
2821
+ * @returns Promise containing array of memory threads
2822
+ */
2823
+ getNetworkMemoryThreads(params) {
2824
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
2825
+ }
2826
+ /**
2827
+ * Creates a new memory thread
2828
+ * @param params - Parameters for creating the memory thread
2829
+ * @returns Promise containing the created memory thread
2830
+ */
2831
+ createNetworkMemoryThread(params) {
2832
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
2833
+ }
2834
+ /**
2835
+ * Gets a memory thread instance by ID
2836
+ * @param threadId - ID of the memory thread to retrieve
2837
+ * @returns MemoryThread instance
2838
+ */
2839
+ getNetworkMemoryThread(threadId, networkId) {
2840
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2841
+ }
2842
+ /**
2843
+ * Saves messages to memory
2844
+ * @param params - Parameters containing messages to save
2845
+ * @returns Promise containing the saved messages
2846
+ */
2847
+ saveNetworkMessageToMemory(params) {
2848
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2849
+ method: "POST",
2850
+ body: params
2851
+ });
2852
+ }
2853
+ /**
2854
+ * Gets the status of the memory system
2855
+ * @returns Promise containing memory system status
2856
+ */
2857
+ getNetworkMemoryStatus(networkId) {
2858
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2859
+ }
2860
+ /**
2861
+ * Retrieves all available tools
2862
+ * @returns Promise containing map of tool IDs to tool details
2863
+ */
2864
+ getTools() {
2865
+ return this.request("/api/tools");
2866
+ }
2867
+ /**
2868
+ * Gets a tool instance by ID
2869
+ * @param toolId - ID of the tool to retrieve
2870
+ * @returns Tool instance
2871
+ */
2872
+ getTool(toolId) {
2873
+ return new Tool(this.options, toolId);
2874
+ }
2875
+ /**
2876
+ * Retrieves all available legacy workflows
2877
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2878
+ */
2879
+ getLegacyWorkflows() {
2880
+ return this.request("/api/workflows/legacy");
2881
+ }
2882
+ /**
2883
+ * Gets a legacy workflow instance by ID
2884
+ * @param workflowId - ID of the legacy workflow to retrieve
2885
+ * @returns Legacy Workflow instance
2886
+ */
2887
+ getLegacyWorkflow(workflowId) {
2888
+ return new LegacyWorkflow(this.options, workflowId);
2889
+ }
2890
+ /**
2891
+ * Retrieves all available workflows
2892
+ * @returns Promise containing map of workflow IDs to workflow details
2893
+ */
2894
+ getWorkflows() {
2895
+ return this.request("/api/workflows");
2896
+ }
2897
+ /**
2898
+ * Gets a workflow instance by ID
2899
+ * @param workflowId - ID of the workflow to retrieve
2900
+ * @returns Workflow instance
2901
+ */
2902
+ getWorkflow(workflowId) {
2903
+ return new Workflow(this.options, workflowId);
2904
+ }
2905
+ /**
2906
+ * Gets all available agent builder actions
2907
+ * @returns Promise containing map of action IDs to action details
2908
+ */
2909
+ getAgentBuilderActions() {
2910
+ return this.request("/api/agent-builder/");
2911
+ }
2912
+ /**
2913
+ * Gets an agent builder instance for executing agent-builder workflows
2914
+ * @returns AgentBuilder instance
2915
+ */
2916
+ getAgentBuilderAction(actionId) {
2917
+ return new AgentBuilder(this.options, actionId);
2918
+ }
2919
+ /**
2920
+ * Gets a vector instance by name
2921
+ * @param vectorName - Name of the vector to retrieve
2922
+ * @returns Vector instance
2923
+ */
2924
+ getVector(vectorName) {
2925
+ return new Vector(this.options, vectorName);
2926
+ }
2927
+ /**
2928
+ * Retrieves logs
2929
+ * @param params - Parameters for filtering logs
2930
+ * @returns Promise containing array of log messages
2931
+ */
2932
+ getLogs(params) {
2933
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2934
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2935
+ const searchParams = new URLSearchParams();
2936
+ if (transportId) {
2937
+ searchParams.set("transportId", transportId);
2938
+ }
2939
+ if (fromDate) {
2940
+ searchParams.set("fromDate", fromDate.toISOString());
2941
+ }
2942
+ if (toDate) {
2943
+ searchParams.set("toDate", toDate.toISOString());
2944
+ }
2945
+ if (logLevel) {
2946
+ searchParams.set("logLevel", logLevel);
2947
+ }
2948
+ if (page) {
2949
+ searchParams.set("page", String(page));
2950
+ }
2951
+ if (perPage) {
2952
+ searchParams.set("perPage", String(perPage));
2953
+ }
2954
+ if (_filters) {
2955
+ if (Array.isArray(_filters)) {
2956
+ for (const filter of _filters) {
2957
+ searchParams.append("filters", filter);
2958
+ }
2959
+ } else {
2960
+ searchParams.set("filters", _filters);
2961
+ }
2962
+ }
2963
+ if (searchParams.size) {
2964
+ return this.request(`/api/logs?${searchParams}`);
2965
+ } else {
2966
+ return this.request(`/api/logs`);
2967
+ }
2968
+ }
2969
+ /**
2970
+ * Gets logs for a specific run
2971
+ * @param params - Parameters containing run ID to retrieve
2972
+ * @returns Promise containing array of log messages
2973
+ */
2974
+ getLogForRun(params) {
2975
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2976
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2977
+ const searchParams = new URLSearchParams();
2978
+ if (runId) {
2979
+ searchParams.set("runId", runId);
2980
+ }
2981
+ if (transportId) {
2982
+ searchParams.set("transportId", transportId);
2983
+ }
2984
+ if (fromDate) {
2985
+ searchParams.set("fromDate", fromDate.toISOString());
2986
+ }
2987
+ if (toDate) {
2988
+ searchParams.set("toDate", toDate.toISOString());
2989
+ }
2990
+ if (logLevel) {
2991
+ searchParams.set("logLevel", logLevel);
2992
+ }
2993
+ if (page) {
2994
+ searchParams.set("page", String(page));
2995
+ }
2996
+ if (perPage) {
2997
+ searchParams.set("perPage", String(perPage));
2998
+ }
2999
+ if (_filters) {
3000
+ if (Array.isArray(_filters)) {
3001
+ for (const filter of _filters) {
3002
+ searchParams.append("filters", filter);
3003
+ }
3004
+ } else {
3005
+ searchParams.set("filters", _filters);
3006
+ }
3007
+ }
3008
+ if (searchParams.size) {
3009
+ return this.request(`/api/logs/${runId}?${searchParams}`);
3010
+ } else {
3011
+ return this.request(`/api/logs/${runId}`);
3012
+ }
3013
+ }
3014
+ /**
3015
+ * List of all log transports
3016
+ * @returns Promise containing list of log transports
3017
+ */
3018
+ getLogTransports() {
3019
+ return this.request("/api/logs/transports");
3020
+ }
3021
+ /**
3022
+ * List of all traces (paged)
3023
+ * @param params - Parameters for filtering traces
3024
+ * @returns Promise containing telemetry data
3025
+ */
3026
+ getTelemetry(params) {
3027
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
3028
+ const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
3029
+ const searchParams = new URLSearchParams();
3030
+ if (name) {
3031
+ searchParams.set("name", name);
3032
+ }
3033
+ if (scope) {
3034
+ searchParams.set("scope", scope);
3035
+ }
3036
+ if (page) {
3037
+ searchParams.set("page", String(page));
3038
+ }
3039
+ if (perPage) {
3040
+ searchParams.set("perPage", String(perPage));
3041
+ }
3042
+ if (_attribute) {
3043
+ if (Array.isArray(_attribute)) {
3044
+ for (const attr of _attribute) {
3045
+ searchParams.append("attribute", attr);
3046
+ }
3047
+ } else {
3048
+ searchParams.set("attribute", _attribute);
3049
+ }
3050
+ }
3051
+ if (fromDate) {
3052
+ searchParams.set("fromDate", fromDate.toISOString());
3053
+ }
3054
+ if (toDate) {
3055
+ searchParams.set("toDate", toDate.toISOString());
3056
+ }
3057
+ if (searchParams.size) {
3058
+ return this.request(`/api/telemetry?${searchParams}`);
3059
+ } else {
3060
+ return this.request(`/api/telemetry`);
3061
+ }
3062
+ }
3063
+ /**
3064
+ * Retrieves all available networks
3065
+ * @returns Promise containing map of network IDs to network details
3066
+ */
3067
+ getNetworks() {
3068
+ return this.request("/api/networks");
3069
+ }
3070
+ /**
3071
+ * Retrieves all available vNext networks
3072
+ * @returns Promise containing map of vNext network IDs to vNext network details
3073
+ */
3074
+ getVNextNetworks() {
3075
+ return this.request("/api/networks/v-next");
3076
+ }
3077
+ /**
3078
+ * Gets a network instance by ID
3079
+ * @param networkId - ID of the network to retrieve
3080
+ * @returns Network instance
3081
+ */
3082
+ getNetwork(networkId) {
3083
+ return new Network(this.options, networkId);
3084
+ }
3085
+ /**
3086
+ * Gets a vNext network instance by ID
3087
+ * @param networkId - ID of the vNext network to retrieve
3088
+ * @returns vNext Network instance
3089
+ */
3090
+ getVNextNetwork(networkId) {
3091
+ return new VNextNetwork(this.options, networkId);
3092
+ }
3093
+ /**
3094
+ * Retrieves a list of available MCP servers.
3095
+ * @param params - Optional parameters for pagination (limit, offset).
3096
+ * @returns Promise containing the list of MCP servers and pagination info.
3097
+ */
3098
+ getMcpServers(params) {
3099
+ const searchParams = new URLSearchParams();
3100
+ if (params?.limit !== void 0) {
3101
+ searchParams.set("limit", String(params.limit));
3102
+ }
3103
+ if (params?.offset !== void 0) {
3104
+ searchParams.set("offset", String(params.offset));
3105
+ }
3106
+ const queryString = searchParams.toString();
3107
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
3108
+ }
3109
+ /**
3110
+ * Retrieves detailed information for a specific MCP server.
3111
+ * @param serverId - The ID of the MCP server to retrieve.
3112
+ * @param params - Optional parameters, e.g., specific version.
3113
+ * @returns Promise containing the detailed MCP server information.
3114
+ */
3115
+ getMcpServerDetails(serverId, params) {
3116
+ const searchParams = new URLSearchParams();
3117
+ if (params?.version) {
3118
+ searchParams.set("version", params.version);
3119
+ }
3120
+ const queryString = searchParams.toString();
3121
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
3122
+ }
3123
+ /**
3124
+ * Retrieves a list of tools for a specific MCP server.
3125
+ * @param serverId - The ID of the MCP server.
3126
+ * @returns Promise containing the list of tools.
3127
+ */
3128
+ getMcpServerTools(serverId) {
3129
+ return this.request(`/api/mcp/${serverId}/tools`);
3130
+ }
3131
+ /**
3132
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
3133
+ * This instance can then be used to fetch details or execute the tool.
3134
+ * @param serverId - The ID of the MCP server.
3135
+ * @param toolId - The ID of the tool.
3136
+ * @returns MCPTool instance.
3137
+ */
3138
+ getMcpServerTool(serverId, toolId) {
3139
+ return new MCPTool(this.options, serverId, toolId);
3140
+ }
3141
+ /**
3142
+ * Gets an A2A client for interacting with an agent via the A2A protocol
3143
+ * @param agentId - ID of the agent to interact with
3144
+ * @returns A2A client instance
3145
+ */
3146
+ getA2A(agentId) {
3147
+ return new A2A(this.options, agentId);
3148
+ }
3149
+ /**
3150
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3151
+ * @param agentId - ID of the agent.
3152
+ * @param threadId - ID of the thread.
3153
+ * @param resourceId - Optional ID of the resource.
3154
+ * @returns Working memory for the specified thread or resource.
3155
+ */
3156
+ getWorkingMemory({
3157
+ agentId,
3158
+ threadId,
3159
+ resourceId
3160
+ }) {
3161
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3162
+ }
3163
+ /**
3164
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3165
+ * @param agentId - ID of the agent.
3166
+ * @param threadId - ID of the thread.
3167
+ * @param workingMemory - The new working memory content.
3168
+ * @param resourceId - Optional ID of the resource.
3169
+ */
3170
+ updateWorkingMemory({
3171
+ agentId,
3172
+ threadId,
3173
+ workingMemory,
3174
+ resourceId
3175
+ }) {
3176
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
3177
+ method: "POST",
3178
+ body: {
3179
+ workingMemory,
3180
+ resourceId
3181
+ }
3182
+ });
3183
+ }
3184
+ /**
3185
+ * Retrieves all available scorers
3186
+ * @returns Promise containing list of available scorers
3187
+ */
3188
+ getScorers() {
3189
+ return this.request("/api/scores/scorers");
3190
+ }
3191
+ /**
3192
+ * Retrieves a scorer by ID
3193
+ * @param scorerId - ID of the scorer to retrieve
3194
+ * @returns Promise containing the scorer
3195
+ */
3196
+ getScorer(scorerId) {
3197
+ return this.request(`/api/scores/scorers/${scorerId}`);
3198
+ }
3199
+ getScoresByScorerId(params) {
3200
+ const { page, perPage, scorerId, entityId, entityType } = params;
3201
+ const searchParams = new URLSearchParams();
3202
+ if (entityId) {
3203
+ searchParams.set("entityId", entityId);
3204
+ }
3205
+ if (entityType) {
3206
+ searchParams.set("entityType", entityType);
3207
+ }
3208
+ if (page !== void 0) {
3209
+ searchParams.set("page", String(page));
3210
+ }
3211
+ if (perPage !== void 0) {
3212
+ searchParams.set("perPage", String(perPage));
3213
+ }
3214
+ const queryString = searchParams.toString();
3215
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3216
+ }
3217
+ /**
3218
+ * Retrieves scores by run ID
3219
+ * @param params - Parameters containing run ID and pagination options
3220
+ * @returns Promise containing scores and pagination info
3221
+ */
3222
+ getScoresByRunId(params) {
3223
+ const { runId, page, perPage } = params;
3224
+ const searchParams = new URLSearchParams();
3225
+ if (page !== void 0) {
3226
+ searchParams.set("page", String(page));
3227
+ }
3228
+ if (perPage !== void 0) {
3229
+ searchParams.set("perPage", String(perPage));
3230
+ }
3231
+ const queryString = searchParams.toString();
3232
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3233
+ }
3234
+ /**
3235
+ * Retrieves scores by entity ID and type
3236
+ * @param params - Parameters containing entity ID, type, and pagination options
3237
+ * @returns Promise containing scores and pagination info
3238
+ */
3239
+ getScoresByEntityId(params) {
3240
+ const { entityId, entityType, page, perPage } = params;
3241
+ const searchParams = new URLSearchParams();
3242
+ if (page !== void 0) {
3243
+ searchParams.set("page", String(page));
3244
+ }
3245
+ if (perPage !== void 0) {
3246
+ searchParams.set("perPage", String(perPage));
3247
+ }
3248
+ const queryString = searchParams.toString();
3249
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3250
+ }
3251
+ /**
3252
+ * Saves a score
3253
+ * @param params - Parameters containing the score data to save
3254
+ * @returns Promise containing the saved score
3255
+ */
3256
+ saveScore(params) {
3257
+ return this.request("/api/scores", {
3258
+ method: "POST",
3259
+ body: params
3260
+ });
3261
+ }
3262
+ /**
3263
+ * Retrieves model providers with available keys
3264
+ * @returns Promise containing model providers with available keys
3265
+ */
3266
+ getModelProviders() {
3267
+ return this.request(`/api/model-providers`);
3268
+ }
3269
+ getAITrace(traceId) {
3270
+ return this.observability.getTrace(traceId);
3271
+ }
3272
+ getAITraces(params) {
3273
+ return this.observability.getTraces(params);
3274
+ }
3275
+ };
3276
+
3277
+ exports.MastraClient = MastraClient;
3278
+ //# sourceMappingURL=index.cjs.map
3279
+ //# sourceMappingURL=index.cjs.map