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