@mastra/client-js 0.0.0-llamaindex-switch-core-20250424001624 → 0.0.0-main-test-05-11-2025-2-20251105214713

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