@mastra/client-js 1.47.0-alpha.1 → 1.47.0-alpha.10

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 (60) hide show
  1. package/dist/_types/@ai-sdk_provider/package.json +1 -0
  2. package/dist/_types/@ai-sdk_provider-utils/dist/index.d.ts +1 -1
  3. package/dist/_types/@ai-sdk_provider-utils/package.json +1 -0
  4. package/dist/_types/@ai-sdk_ui-utils/dist/index.d.ts +3 -3
  5. package/dist/_types/@ai-sdk_ui-utils/package.json +1 -0
  6. package/dist/client.d.ts +54 -207
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/docs/SKILL.md +1 -1
  9. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  10. package/dist/docs/references/docs-connections-a2a.md +4 -3
  11. package/dist/docs/references/docs-harness-agent-controller.md +4 -2
  12. package/dist/docs/references/reference-client-js-agent-controller.md +77 -16
  13. package/dist/docs/references/reference-client-js-agents.md +25 -0
  14. package/dist/docs/references/reference-client-js-mastra-client.md +1 -1
  15. package/dist/docs/references/reference-client-js-observability.md +49 -1
  16. package/dist/docs/references/reference-observability-tracing-trace-query.md +110 -9
  17. package/dist/index.cjs +337 -165
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.ts +2 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +338 -166
  22. package/dist/index.js.map +1 -1
  23. package/dist/resources/a2a.d.ts +5 -1
  24. package/dist/resources/a2a.d.ts.map +1 -1
  25. package/dist/resources/agent-builder.d.ts +25 -40
  26. package/dist/resources/agent-builder.d.ts.map +1 -1
  27. package/dist/resources/agent-controller.d.ts +5 -4
  28. package/dist/resources/agent-controller.d.ts.map +1 -1
  29. package/dist/resources/agent.d.ts +46 -74
  30. package/dist/resources/agent.d.ts.map +1 -1
  31. package/dist/resources/base.d.ts.map +1 -1
  32. package/dist/resources/channels.d.ts +13 -31
  33. package/dist/resources/channels.d.ts.map +1 -1
  34. package/dist/resources/conversations.d.ts +6 -3
  35. package/dist/resources/conversations.d.ts.map +1 -1
  36. package/dist/resources/mcp-tool.d.ts +9 -6
  37. package/dist/resources/mcp-tool.d.ts.map +1 -1
  38. package/dist/resources/memory-thread.d.ts +11 -11
  39. package/dist/resources/memory-thread.d.ts.map +1 -1
  40. package/dist/resources/observability-route-types.d.ts +101 -0
  41. package/dist/resources/observability-route-types.d.ts.map +1 -0
  42. package/dist/resources/observability.d.ts +24 -9
  43. package/dist/resources/observability.d.ts.map +1 -1
  44. package/dist/resources/responses.d.ts +5 -2
  45. package/dist/resources/responses.d.ts.map +1 -1
  46. package/dist/resources/run.d.ts +21 -57
  47. package/dist/resources/run.d.ts.map +1 -1
  48. package/dist/resources/tool.d.ts +6 -4
  49. package/dist/resources/tool.d.ts.map +1 -1
  50. package/dist/resources/vector.d.ts +5 -10
  51. package/dist/resources/vector.d.ts.map +1 -1
  52. package/dist/resources/workflow.d.ts +8 -10
  53. package/dist/resources/workflow.d.ts.map +1 -1
  54. package/dist/route-types.generated.d.ts +2870 -2116
  55. package/dist/route-types.generated.d.ts.map +1 -1
  56. package/dist/types.d.ts +252 -1593
  57. package/dist/types.d.ts.map +1 -1
  58. package/dist/utils/index.d.ts +7 -0
  59. package/dist/utils/index.d.ts.map +1 -1
  60. package/package.json +5 -5
package/dist/index.cjs CHANGED
@@ -365,6 +365,33 @@ function buildTenancyQuery(tenancy) {
365
365
  const queryString = searchParams.toString();
366
366
  return queryString ? `?${queryString}` : "";
367
367
  }
368
+ /**
369
+ * Merges multiple optional abort signals into one. Returns `undefined` when no
370
+ * signals are provided, the single signal when only one is provided, and a
371
+ * combined signal otherwise. Uses `AbortSignal.any` when available and falls
372
+ * back to a manual listener merge for runtimes that lack it.
373
+ */
374
+ function mergeAbortSignals(...signals) {
375
+ const defined = signals.filter((signal) => signal !== void 0);
376
+ if (defined.length === 0) return void 0;
377
+ if (defined.length === 1) return defined[0];
378
+ if (typeof AbortSignal.any === "function") return AbortSignal.any(defined);
379
+ const controller = new AbortController();
380
+ const alreadyAborted = defined.find((signal) => signal.aborted);
381
+ if (alreadyAborted) {
382
+ controller.abort(alreadyAborted.reason);
383
+ return controller.signal;
384
+ }
385
+ const cleanup = () => {
386
+ for (const signal of defined) signal.removeEventListener("abort", onAbort);
387
+ };
388
+ function onAbort() {
389
+ cleanup();
390
+ controller.abort(this.reason);
391
+ }
392
+ for (const signal of defined) signal.addEventListener("abort", onAbort);
393
+ return controller.signal;
394
+ }
368
395
  //#endregion
369
396
  //#region src/utils/client-tool-model-output.ts
370
397
  /**
@@ -559,43 +586,61 @@ var BaseResource = class {
559
586
  */
560
587
  async request(path, options = {}) {
561
588
  let lastError = null;
562
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials, fetch: customFetch } = this.options;
589
+ const { baseUrl, retries: defaultRetries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials, fetch: customFetch } = this.options;
590
+ const { retries: requestRetries, ...fetchOptions } = options;
591
+ const retries = requestRetries ?? defaultRetries;
592
+ if (!Number.isSafeInteger(retries) || retries < 0) throw new RangeError("retries must be a non-negative safe integer");
593
+ const signal = mergeAbortSignals(this.options.abortSignal, fetchOptions.signal);
563
594
  const fetchFn = customFetch || fetch;
564
595
  let delay = backoffMs;
565
596
  const fullPath = `${this.apiPrefix}${path}`;
566
- for (let attempt = 0; attempt <= retries; attempt++) try {
567
- const response = await fetchFn(`${baseUrl.replace(/\/$/, "")}${fullPath}`, {
568
- ...options,
569
- headers: {
570
- ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT" || options.method === "PATCH" || options.method === "DELETE") ? { "content-type": "application/json" } : {},
571
- ...headers,
572
- ...options.headers
573
- },
574
- signal: this.options.abortSignal,
575
- credentials: options.credentials ?? credentials,
576
- body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
577
- });
578
- if (!response.ok) {
579
- const errorBody = await response.text();
580
- let parsedBody;
581
- let errorMessage = `HTTP error! status: ${response.status}`;
582
- try {
583
- parsedBody = JSON.parse(errorBody);
584
- errorMessage += ` - ${JSON.stringify(parsedBody)}`;
585
- } catch {
586
- if (errorBody) errorMessage += ` - ${errorBody}`;
597
+ for (let attempt = 0; attempt <= retries; attempt++) {
598
+ if (signal?.aborted) throw signal.reason ?? new DOMException("This operation was aborted", "AbortError");
599
+ try {
600
+ const response = await fetchFn(`${baseUrl.replace(/\/$/, "")}${fullPath}`, {
601
+ ...fetchOptions,
602
+ headers: {
603
+ ...fetchOptions.body && !(fetchOptions.body instanceof FormData) && (fetchOptions.method === "POST" || fetchOptions.method === "PUT" || fetchOptions.method === "PATCH" || fetchOptions.method === "DELETE") ? { "content-type": "application/json" } : {},
604
+ ...headers,
605
+ ...fetchOptions.headers
606
+ },
607
+ signal,
608
+ credentials: fetchOptions.credentials ?? credentials,
609
+ body: fetchOptions.body instanceof FormData ? fetchOptions.body : fetchOptions.body ? JSON.stringify(fetchOptions.body) : void 0
610
+ });
611
+ if (!response.ok) {
612
+ const errorBody = await response.text();
613
+ let parsedBody;
614
+ let errorMessage = `HTTP error! status: ${response.status}`;
615
+ try {
616
+ parsedBody = JSON.parse(errorBody);
617
+ errorMessage += ` - ${JSON.stringify(parsedBody)}`;
618
+ } catch {
619
+ if (errorBody) errorMessage += ` - ${errorBody}`;
620
+ }
621
+ throw new MastraClientError(response.status, response.statusText, errorMessage, parsedBody);
587
622
  }
588
- throw new MastraClientError(response.status, response.statusText, errorMessage, parsedBody);
623
+ if (options.stream) return response;
624
+ return await response.json();
625
+ } catch (error) {
626
+ lastError = error;
627
+ if (signal?.aborted || error?.name === "AbortError") throw error;
628
+ const status = error.status;
629
+ if (status !== void 0 && status >= 400 && status < 500) throw error;
630
+ if (attempt === retries) break;
631
+ await new Promise((resolve, reject) => {
632
+ const timer = setTimeout(() => {
633
+ signal?.removeEventListener("abort", onAbort);
634
+ resolve();
635
+ }, delay);
636
+ const onAbort = () => {
637
+ clearTimeout(timer);
638
+ reject(signal?.reason ?? new DOMException("This operation was aborted", "AbortError"));
639
+ };
640
+ signal?.addEventListener("abort", onAbort, { once: true });
641
+ });
642
+ delay = Math.min(delay * 2, maxBackoffMs);
589
643
  }
590
- if (options.stream) return response;
591
- return await response.json();
592
- } catch (error) {
593
- lastError = error;
594
- const status = error.status;
595
- if (status !== void 0 && status >= 400 && status < 500) throw error;
596
- if (attempt === retries) break;
597
- await new Promise((resolve) => setTimeout(resolve, delay));
598
- delay = Math.min(delay * 2, maxBackoffMs);
599
644
  }
600
645
  throw lastError || /* @__PURE__ */ new Error("Request failed");
601
646
  }
@@ -919,6 +964,11 @@ var Agent = class extends BaseResource {
919
964
  * depending on the toolset's scope).
920
965
  *
921
966
  * @param threadId - Optional thread ID for thread-scoped browser sessions
967
+ *
968
+ * @remarks This is a browser-stream adapter compatibility endpoint, not a
969
+ * `SERVER_ROUTES` route. Its historical deployer implementation returns
970
+ * `{ success: true }`; no generated contract exists while the adapter owns it.
971
+ * The public `boolean` result remains broad for backwards compatibility.
922
972
  */
923
973
  closeBrowser(threadId) {
924
974
  return this.request(`/agents/${this.agentId}/browser/close`, {
@@ -1215,12 +1265,13 @@ var Agent = class extends BaseResource {
1215
1265
  * @experimental Agent signals are experimental and may change in a future release.
1216
1266
  */
1217
1267
  async abortThread(params) {
1218
- const { resourceId, threadId } = params;
1268
+ const { resourceId, threadId, expectedRunId } = params;
1219
1269
  return this.request(`/agents/${this.agentId}/threads/abort`, {
1220
1270
  method: "POST",
1221
1271
  body: {
1222
1272
  resourceId,
1223
- threadId
1273
+ threadId,
1274
+ ...expectedRunId === void 0 ? {} : { expectedRunId }
1224
1275
  }
1225
1276
  });
1226
1277
  }
@@ -1320,8 +1371,10 @@ var Agent = class extends BaseResource {
1320
1371
  return this.request(`/stored/agents/${encodeURIComponent(this.agentId)}/versions/compare?${queryParams.toString()}${contextString ? `&${contextString.slice(1)}` : ""}`);
1321
1372
  }
1322
1373
  async generateLegacy(params) {
1374
+ const { abortSignal: perCallSignal, ...bodyParams } = params;
1375
+ const abortSignal = mergeAbortSignals(this.options.abortSignal, perCallSignal);
1323
1376
  const processedParams = {
1324
- ...params,
1377
+ ...bodyParams,
1325
1378
  output: params.output ? zodToJsonSchema(params.output) : void 0,
1326
1379
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
1327
1380
  requestContext: parseClientRequestContext(params.requestContext),
@@ -1330,9 +1383,11 @@ var Agent = class extends BaseResource {
1330
1383
  const { resourceId, threadId, requestContext } = processedParams;
1331
1384
  const response = await this.request(`/agents/${this.agentId}/generate-legacy`, {
1332
1385
  method: "POST",
1333
- body: processedParams
1386
+ body: processedParams,
1387
+ signal: abortSignal
1334
1388
  });
1335
1389
  if (response.finishReason === "tool-calls") {
1390
+ if (abortSignal?.aborted) throw abortSignal.reason ?? new DOMException("This operation was aborted", "AbortError");
1336
1391
  const toolCalls = response.toolCalls;
1337
1392
  if (!toolCalls || !Array.isArray(toolCalls)) return response;
1338
1393
  for (const toolCall of toolCalls) {
@@ -1381,8 +1436,10 @@ var Agent = class extends BaseResource {
1381
1436
  messages
1382
1437
  };
1383
1438
  const resolvedClientTools = params.clientToolsResolver?.() ?? params.clientTools;
1439
+ const abortSignal = mergeAbortSignals(this.options.abortSignal, params.abortSignal);
1384
1440
  const processedParams = {
1385
1441
  ...params,
1442
+ abortSignal: void 0,
1386
1443
  requestContext: parseClientRequestContext(params.requestContext),
1387
1444
  clientTools: processClientTools(resolvedClientTools),
1388
1445
  structuredOutput: params.structuredOutput ? {
@@ -1396,20 +1453,24 @@ var Agent = class extends BaseResource {
1396
1453
  const threadId = typeof thread === "string" ? thread : thread?.id;
1397
1454
  const response = await this.request(`/agents/${this.agentId}/generate`, {
1398
1455
  method: "POST",
1399
- body: processedParams
1400
- });
1401
- if (response.finishReason === "tool-calls") return executeToolCallAndRespond({
1402
- response,
1403
- params: {
1404
- ...params,
1405
- clientTools: resolvedClientTools
1406
- },
1407
- agentId: this.agentId,
1408
- resourceId,
1409
- threadId,
1410
- requestContext,
1411
- respondFn: this.generate.bind(this)
1456
+ body: processedParams,
1457
+ signal: abortSignal
1412
1458
  });
1459
+ if (response.finishReason === "tool-calls") {
1460
+ if (abortSignal?.aborted) throw abortSignal.reason ?? new DOMException("This operation was aborted", "AbortError");
1461
+ return executeToolCallAndRespond({
1462
+ response,
1463
+ params: {
1464
+ ...params,
1465
+ clientTools: resolvedClientTools
1466
+ },
1467
+ agentId: this.agentId,
1468
+ resourceId,
1469
+ threadId,
1470
+ requestContext,
1471
+ respondFn: this.generate.bind(this)
1472
+ });
1473
+ }
1413
1474
  return response;
1414
1475
  }
1415
1476
  async processChatResponse({ stream, update, onToolCall, onFinish, getCurrentDate = () => /* @__PURE__ */ new Date(), lastMessage }) {
@@ -1645,7 +1706,7 @@ var Agent = class extends BaseResource {
1645
1706
  throw new Error(error);
1646
1707
  }
1647
1708
  });
1648
- onFinish?.({
1709
+ await onFinish?.({
1649
1710
  message,
1650
1711
  finishReason,
1651
1712
  usage
@@ -1664,8 +1725,22 @@ var Agent = class extends BaseResource {
1664
1725
  requestContext: parseClientRequestContext(params.requestContext),
1665
1726
  clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
1666
1727
  };
1667
- const { readable, writable } = new TransformStream();
1668
- const response = await this.processStreamResponseLegacy(processedParams, writable);
1728
+ const { readable: innerReadable, writable } = new TransformStream();
1729
+ const abortController = new AbortController();
1730
+ const signal = mergeAbortSignals(abortController.signal, params.abortSignal, this.options.abortSignal);
1731
+ const innerReader = innerReadable.getReader();
1732
+ const readable = new ReadableStream({
1733
+ async pull(controller) {
1734
+ const { done, value } = await innerReader.read();
1735
+ if (done) controller.close();
1736
+ else controller.enqueue(value);
1737
+ },
1738
+ cancel(reason) {
1739
+ abortController.abort(reason);
1740
+ return innerReader.cancel(reason).catch(() => {});
1741
+ }
1742
+ });
1743
+ const response = await this.processStreamResponseLegacy(processedParams, writable, signal);
1669
1744
  const streamResponse = new Response(readable, {
1670
1745
  status: response.status,
1671
1746
  statusText: response.statusText,
@@ -1906,29 +1981,63 @@ var Agent = class extends BaseResource {
1906
1981
  }
1907
1982
  }
1908
1983
  });
1909
- onFinish?.({
1984
+ await onFinish?.({
1910
1985
  message,
1911
1986
  finishReason,
1912
1987
  usage
1913
1988
  });
1914
1989
  }
1915
- async processStreamResponse(processedParams, controller, route = "stream") {
1990
+ /**
1991
+ * Creates the consumer-facing stream for the streaming methods. Cancelling the
1992
+ * returned stream (or aborting `externalSignal`) aborts the underlying request
1993
+ * and stops any client-tool continuations.
1994
+ */
1995
+ createCancellableStream(externalSignal) {
1996
+ const abortController = new AbortController();
1997
+ let readableController;
1998
+ return {
1999
+ readable: new ReadableStream({
2000
+ start(controller) {
2001
+ readableController = controller;
2002
+ },
2003
+ cancel(reason) {
2004
+ abortController.abort(reason);
2005
+ }
2006
+ }),
2007
+ controller: readableController,
2008
+ signal: mergeAbortSignals(abortController.signal, externalSignal, this.options.abortSignal)
2009
+ };
2010
+ }
2011
+ async processStreamResponse(processedParams, controller, route = "stream", signal) {
1916
2012
  const { memory } = processedParams ?? {};
1917
2013
  const { resource, thread } = memory ?? {};
1918
2014
  const threadId = processedParams.threadId ?? (typeof thread === "string" ? thread : thread?.id);
1919
2015
  const resourceId = processedParams.resourceId ?? resource;
1920
- let requestBody = processedParams;
2016
+ const { abortSignal: _abortSignal, ...serializableParams } = processedParams;
2017
+ let requestBody = serializableParams;
1921
2018
  if (route === "resume-stream") {
1922
- const { messages: _messages, ...resumeStreamBody } = processedParams;
2019
+ const { messages: _messages, ...resumeStreamBody } = serializableParams;
1923
2020
  requestBody = resumeStreamBody;
1924
2021
  }
1925
2022
  const requestPath = route === "stream" && this.routeOverrides?.stream ? this.routeOverrides.stream : `/agents/${this.agentId}/${route}`;
1926
2023
  const response = await this.request(requestPath, {
1927
2024
  method: "POST",
1928
2025
  body: requestBody,
1929
- stream: true
2026
+ stream: true,
2027
+ signal
1930
2028
  });
1931
2029
  if (!response.body) throw new Error("No response body");
2030
+ const isAborted = () => Boolean(signal?.aborted);
2031
+ const isAbortError = (error) => isAborted() || error?.name === "AbortError";
2032
+ const safeClose = () => {
2033
+ try {
2034
+ controller.close();
2035
+ } catch {}
2036
+ };
2037
+ const safeEnqueue = (chunk) => {
2038
+ if (isAborted()) return;
2039
+ controller.enqueue(chunk);
2040
+ };
1932
2041
  try {
1933
2042
  let messages = [];
1934
2043
  let streamRunId = processedParams.runId;
@@ -1940,7 +2049,7 @@ var Agent = class extends BaseResource {
1940
2049
  const lines = pendingText.split("\n\n");
1941
2050
  pendingText = isFinal ? "" : lines.pop() ?? "";
1942
2051
  const readableLines = lines.filter((line) => line.trim() !== "[DONE]" && line.trim() !== "data: [DONE]").join("\n\n");
1943
- if (readableLines) controller.enqueue(new TextEncoder().encode(`${readableLines}\n\n`));
2052
+ if (readableLines) safeEnqueue(new TextEncoder().encode(`${readableLines}\n\n`));
1944
2053
  };
1945
2054
  const pipePromise = streamForController.pipeTo(new WritableStream({
1946
2055
  async write(chunk) {
@@ -1948,26 +2057,32 @@ var Agent = class extends BaseResource {
1948
2057
  enqueueReadableText(decoder.decode(chunk, { stream: true }));
1949
2058
  } catch (error) {
1950
2059
  console.error("Error enqueueing to controller:", error);
1951
- controller.enqueue(chunk);
2060
+ safeEnqueue(chunk);
1952
2061
  }
1953
2062
  },
1954
2063
  close() {
1955
2064
  enqueueReadableText(decoder.decode(), true);
1956
2065
  }
1957
- })).catch((error) => {
1958
- console.error("Error piping to controller:", error);
2066
+ }), { signal }).catch((error) => {
2067
+ if (!isAbortError(error)) console.error("Error piping to controller:", error);
2068
+ safeClose();
2069
+ });
2070
+ const onAbort = () => {
1959
2071
  try {
1960
- controller.close();
2072
+ controller.error(signal?.reason);
1961
2073
  } catch {}
1962
- });
2074
+ };
2075
+ signal?.addEventListener("abort", onAbort, { once: true });
2076
+ const processingStream = signal ? streamForProcessing.pipeThrough(new TransformStream(), { signal }) : streamForProcessing;
1963
2077
  this.processChatResponse_vNext({
1964
- stream: streamForProcessing,
2078
+ stream: processingStream,
1965
2079
  update: ({ message }) => {
1966
2080
  const existingIndex = messages.findIndex((m) => m.id === message.id);
1967
2081
  if (existingIndex !== -1) messages[existingIndex] = message;
1968
2082
  else messages.push(message);
1969
2083
  },
1970
2084
  onFinish: async ({ finishReason, message }) => {
2085
+ if (isAborted()) return;
1971
2086
  if (finishReason === "tool-calls") {
1972
2087
  const toolInvocationsById = /* @__PURE__ */ new Map();
1973
2088
  for (const part of message?.parts ?? []) {
@@ -1994,6 +2109,7 @@ var Agent = class extends BaseResource {
1994
2109
  const syntheticChunks = [];
1995
2110
  const toolResultContents = [];
1996
2111
  for (const toolCall of executableToolCalls) {
2112
+ if (isAborted()) return;
1997
2113
  const clientTool = processedParams.clientTools?.[toolCall.toolName];
1998
2114
  const runId = streamRunId ?? toolCall.toolCallId;
1999
2115
  let result;
@@ -2061,6 +2177,7 @@ var Agent = class extends BaseResource {
2061
2177
  try {
2062
2178
  await pipePromise;
2063
2179
  } catch {}
2180
+ if (isAborted()) return;
2064
2181
  for (const synthetic of syntheticChunks) try {
2065
2182
  const errorForSerialization = synthetic.type === "tool-error" ? synthetic.payload.error : void 0;
2066
2183
  const serializedError = errorForSerialization instanceof Error ? {
@@ -2076,7 +2193,7 @@ var Agent = class extends BaseResource {
2076
2193
  }
2077
2194
  } : synthetic;
2078
2195
  const sseLine = `data: ${JSON.stringify(payloadForWire)}\n\n`;
2079
- controller.enqueue(new TextEncoder().encode(sseLine));
2196
+ safeEnqueue(new TextEncoder().encode(sseLine));
2080
2197
  } catch (enqueueErr) {
2081
2198
  console.error("Failed to enqueue synthetic tool-result chunk:", enqueueErr);
2082
2199
  }
@@ -2090,22 +2207,23 @@ var Agent = class extends BaseResource {
2090
2207
  toolResultMessage
2091
2208
  ];
2092
2209
  const recursionRoute = route === "resume-stream" ? "stream" : route === "resume-stream-until-idle" ? "stream-until-idle" : route;
2210
+ if (isAborted()) return;
2093
2211
  try {
2094
2212
  await this.processStreamResponse({
2095
2213
  ...processedParams,
2096
2214
  messages: updatedMessages,
2097
2215
  clientTools: processClientTools(processedParams.clientToolsResolver?.() ?? processedParams.clientTools)
2098
- }, controller, recursionRoute);
2216
+ }, controller, recursionRoute, signal);
2099
2217
  } catch (error) {
2100
- console.error("Error processing recursive stream response:", error);
2218
+ if (!isAbortError(error)) console.error("Error processing recursive stream response:", error);
2101
2219
  }
2102
2220
  } else {
2103
2221
  await pipePromise;
2104
- controller.close();
2222
+ safeClose();
2105
2223
  }
2106
2224
  } else {
2107
2225
  await pipePromise;
2108
- controller.close();
2226
+ safeClose();
2109
2227
  }
2110
2228
  },
2111
2229
  onStreamChunk: (chunk) => {
@@ -2113,14 +2231,16 @@ var Agent = class extends BaseResource {
2113
2231
  },
2114
2232
  lastMessage: void 0
2115
2233
  }).catch(async (error) => {
2116
- console.error("Error processing stream response:", error);
2234
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2117
2235
  try {
2118
2236
  await pipePromise;
2119
- controller.close();
2120
2237
  } catch {}
2238
+ safeClose();
2239
+ }).finally(() => {
2240
+ signal?.removeEventListener("abort", onAbort);
2121
2241
  });
2122
2242
  } catch (error) {
2123
- console.error("Error processing stream response:", error);
2243
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2124
2244
  }
2125
2245
  return response;
2126
2246
  }
@@ -2217,11 +2337,8 @@ var Agent = class extends BaseResource {
2217
2337
  clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools),
2218
2338
  structuredOutput
2219
2339
  };
2220
- let readableController;
2221
- const readable = new ReadableStream({ start(controller) {
2222
- readableController = controller;
2223
- } });
2224
- const response = await this.processStreamResponse(processedParams, readableController);
2340
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2341
+ const response = await this.processStreamResponse(processedParams, readableController, "stream", signal);
2225
2342
  const streamResponse = new Response(readable, {
2226
2343
  status: response.status,
2227
2344
  statusText: response.statusText,
@@ -2251,11 +2368,8 @@ var Agent = class extends BaseResource {
2251
2368
  clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools),
2252
2369
  structuredOutput
2253
2370
  };
2254
- let readableController;
2255
- const readable = new ReadableStream({ start(controller) {
2256
- readableController = controller;
2257
- } });
2258
- const response = await this.processStreamResponse(processedParams, readableController, "stream-until-idle");
2371
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2372
+ const response = await this.processStreamResponse(processedParams, readableController, "stream-until-idle", signal);
2259
2373
  const streamResponse = new Response(readable, {
2260
2374
  status: response.status,
2261
2375
  statusText: response.statusText,
@@ -2295,11 +2409,8 @@ var Agent = class extends BaseResource {
2295
2409
  ...rest,
2296
2410
  requestContext: parseClientRequestContext(requestContext)
2297
2411
  };
2298
- let readableController;
2299
- const readable = new ReadableStream({ start(controller) {
2300
- readableController = controller;
2301
- } });
2302
- const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call");
2412
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2413
+ const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call", signal);
2303
2414
  const streamResponse = new Response(readable, {
2304
2415
  status: response.status,
2305
2416
  statusText: response.statusText,
@@ -2329,11 +2440,8 @@ var Agent = class extends BaseResource {
2329
2440
  ...rest,
2330
2441
  requestContext: parseClientRequestContext(requestContext)
2331
2442
  };
2332
- let readableController;
2333
- const readable = new ReadableStream({ start(controller) {
2334
- readableController = controller;
2335
- } });
2336
- const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call");
2443
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2444
+ const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call", signal);
2337
2445
  const streamResponse = new Response(readable, {
2338
2446
  status: response.status,
2339
2447
  statusText: response.statusText,
@@ -2403,11 +2511,8 @@ var Agent = class extends BaseResource {
2403
2511
  schema: (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)((0, _mastra_schema_compat_schema.toStandardSchema)(options.structuredOutput.schema))
2404
2512
  } : void 0
2405
2513
  };
2406
- let readableController;
2407
- const readable = new ReadableStream({ start(controller) {
2408
- readableController = controller;
2409
- } });
2410
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream");
2514
+ const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
2515
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream", signal);
2411
2516
  const streamResponse = new Response(readable, {
2412
2517
  status: response.status,
2413
2518
  statusText: response.statusText,
@@ -2466,11 +2571,8 @@ var Agent = class extends BaseResource {
2466
2571
  schema: (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)((0, _mastra_schema_compat_schema.toStandardSchema)(options.structuredOutput.schema))
2467
2572
  } : void 0
2468
2573
  };
2469
- let readableController;
2470
- const readable = new ReadableStream({ start(controller) {
2471
- readableController = controller;
2472
- } });
2473
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle");
2574
+ const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
2575
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle", signal);
2474
2576
  const streamResponse = new Response(readable, {
2475
2577
  status: response.status,
2476
2578
  statusText: response.statusText,
@@ -2515,32 +2617,41 @@ var Agent = class extends BaseResource {
2515
2617
  /**
2516
2618
  * Processes the stream response and handles tool calls
2517
2619
  */
2518
- async processStreamResponseLegacy(processedParams, writable) {
2620
+ async processStreamResponseLegacy(processedParams, writable, signal) {
2519
2621
  const { memory } = processedParams ?? {};
2520
2622
  const { resource, thread } = memory ?? {};
2521
2623
  const threadId = processedParams.threadId ?? (typeof thread === "string" ? thread : thread?.id);
2522
2624
  const resourceId = processedParams.resourceId ?? resource;
2625
+ const { abortSignal: _abortSignal, ...bodyParams } = processedParams ?? {};
2626
+ const isAborted = () => signal?.aborted === true;
2627
+ const isAbortError = (error) => isAborted() || error?.name === "AbortError";
2523
2628
  const response = await this.request(this.routeOverrides?.stream ?? `/agents/${this.agentId}/stream-legacy`, {
2524
2629
  method: "POST",
2525
- body: processedParams,
2526
- stream: true
2630
+ body: bodyParams,
2631
+ stream: true,
2632
+ signal
2527
2633
  });
2528
2634
  if (!response.body) throw new Error("No response body");
2529
2635
  try {
2530
2636
  let toolCalls = [];
2531
2637
  let messages = [];
2532
2638
  const [streamForWritable, streamForProcessing] = response.body.tee();
2533
- streamForWritable.pipeTo(writable, { preventClose: true }).catch((error) => {
2534
- console.error("Error piping to writable stream:", error);
2639
+ streamForWritable.pipeTo(writable, {
2640
+ preventClose: true,
2641
+ signal
2642
+ }).catch((error) => {
2643
+ if (!isAbortError(error)) console.error("Error piping to writable stream:", error);
2535
2644
  });
2645
+ const processingStream = signal ? streamForProcessing.pipeThrough(new TransformStream(), { signal }) : streamForProcessing;
2536
2646
  this.processChatResponse({
2537
- stream: streamForProcessing,
2647
+ stream: processingStream,
2538
2648
  update: ({ message }) => {
2539
2649
  const existingIndex = messages.findIndex((m) => m.id === message.id);
2540
2650
  if (existingIndex !== -1) messages[existingIndex] = message;
2541
2651
  else messages.push(message);
2542
2652
  },
2543
2653
  onFinish: async ({ finishReason, message }) => {
2654
+ if (isAborted()) return;
2544
2655
  if (finishReason === "tool-calls") {
2545
2656
  const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
2546
2657
  if (toolCall) {
@@ -2572,6 +2683,7 @@ var Agent = class extends BaseResource {
2572
2683
  }
2573
2684
  }
2574
2685
  });
2686
+ if (isAborted()) return;
2575
2687
  const writer = writable.getWriter();
2576
2688
  try {
2577
2689
  await writer.write(new TextEncoder().encode("a:" + JSON.stringify({
@@ -2601,21 +2713,21 @@ var Agent = class extends BaseResource {
2601
2713
  ...processedParams,
2602
2714
  clientTools: processClientTools(processedParams.clientToolsResolver?.() ?? processedParams.clientTools),
2603
2715
  messages: updatedMessages
2604
- }, writable).catch((error) => {
2605
- console.error("Error processing stream response:", error);
2716
+ }, writable, signal).catch((error) => {
2717
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2606
2718
  });
2607
2719
  }
2608
2720
  }
2609
2721
  } else setTimeout(() => {
2610
- writable.close();
2722
+ writable.close().catch(() => {});
2611
2723
  }, 0);
2612
2724
  },
2613
2725
  lastMessage: void 0
2614
2726
  }).catch((error) => {
2615
- console.error("Error processing stream response:", error);
2727
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2616
2728
  });
2617
2729
  } catch (error) {
2618
- console.error("Error processing stream response:", error);
2730
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2619
2731
  }
2620
2732
  return response;
2621
2733
  }
@@ -2691,6 +2803,22 @@ var Agent = class extends BaseResource {
2691
2803
  //#endregion
2692
2804
  //#region src/resources/memory-thread.ts
2693
2805
  /**
2806
+ * Serializes the message-listing filters both memory message routes accept. The network route
2807
+ * takes the same filters under a different path, so the two callers share one serializer.
2808
+ */
2809
+ const memoryMessagesQuery = ({ agentId, resourceId, page, perPage, orderBy, filter, include, includeSystemReminders }) => {
2810
+ const query = new URLSearchParams();
2811
+ if (agentId) query.set("agentId", agentId);
2812
+ if (resourceId) query.set("resourceId", resourceId);
2813
+ if (page !== void 0) query.set("page", String(page));
2814
+ if (perPage !== void 0) query.set("perPage", String(perPage));
2815
+ if (orderBy) query.set("orderBy", JSON.stringify(orderBy));
2816
+ if (filter) query.set("filter", JSON.stringify(filter));
2817
+ if (include) query.set("include", JSON.stringify(include));
2818
+ if (includeSystemReminders !== void 0) query.set("includeSystemReminders", String(includeSystemReminders));
2819
+ return query;
2820
+ };
2821
+ /**
2694
2822
  * MemoryThread resource for interacting with memory threads.
2695
2823
  *
2696
2824
  * `agentId` is optional for read operations (`get`, `listMessages`) — when omitted the server
@@ -2766,18 +2894,11 @@ var MemoryThread = class extends BaseResource {
2766
2894
  * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
2767
2895
  */
2768
2896
  listMessages(params = {}) {
2769
- const { page, perPage, orderBy, filter, include, resourceId, requestContext, includeSystemReminders } = params;
2770
- const queryParams = {};
2771
- if (this.agentId) queryParams.agentId = this.agentId;
2772
- if (resourceId) queryParams.resourceId = resourceId;
2773
- if (page !== void 0) queryParams.page = String(page);
2774
- if (perPage !== void 0) queryParams.perPage = String(perPage);
2775
- if (orderBy) queryParams.orderBy = JSON.stringify(orderBy);
2776
- if (filter) queryParams.filter = JSON.stringify(filter);
2777
- if (include) queryParams.include = JSON.stringify(include);
2778
- if (includeSystemReminders !== void 0) queryParams.includeSystemReminders = String(includeSystemReminders);
2779
- const queryString = new URLSearchParams(queryParams).toString();
2780
- const url = `/memory/threads/${this.threadId}/messages${queryString ? `?${queryString}` : ""}${requestContextQueryString(requestContext, queryString ? "&" : "?")}`;
2897
+ const query = memoryMessagesQuery({
2898
+ ...params,
2899
+ agentId: params.agentId ?? this.agentId
2900
+ }).toString();
2901
+ const url = `/memory/threads/${this.threadId}/messages${query ? `?${query}` : ""}${requestContextQueryString(params.requestContext, query ? "&" : "?")}`;
2781
2902
  return this.request(url);
2782
2903
  }
2783
2904
  /**
@@ -3235,7 +3356,7 @@ var Run = class extends BaseResource {
3235
3356
  resourceId: params.resourceId,
3236
3357
  perStep: params.perStep
3237
3358
  }
3238
- }).then(deserializeWorkflowError);
3359
+ }).then((result) => deserializeWorkflowError(result));
3239
3360
  }
3240
3361
  /**
3241
3362
  * Starts a workflow run and returns a stream
@@ -3317,7 +3438,7 @@ var Run = class extends BaseResource {
3317
3438
  perStep: params.perStep,
3318
3439
  forEachIndex: params.forEachIndex
3319
3440
  }
3320
- }).then(deserializeWorkflowError);
3441
+ }).then((result) => deserializeWorkflowError(result));
3321
3442
  }
3322
3443
  /**
3323
3444
  * Resumes a suspended workflow step without waiting for the workflow to complete (fire-and-forget)
@@ -3401,7 +3522,7 @@ var Run = class extends BaseResource {
3401
3522
  requestContext,
3402
3523
  tracingOptions: params?.tracingOptions
3403
3524
  }
3404
- }).then(deserializeWorkflowError);
3525
+ }).then((result) => deserializeWorkflowError(result));
3405
3526
  }
3406
3527
  /**
3407
3528
  * Time travels a workflow run synchronously without waiting for the workflow to complete
@@ -3431,7 +3552,7 @@ var Run = class extends BaseResource {
3431
3552
  ...params,
3432
3553
  requestContext
3433
3554
  }
3434
- }).then(deserializeWorkflowError);
3555
+ }).then((result) => deserializeWorkflowError(result));
3435
3556
  }
3436
3557
  /**
3437
3558
  * Time travels a workflow run and returns a stream
@@ -3943,12 +4064,27 @@ var A2AV1 = class extends BaseResource {
3943
4064
  }
3944
4065
  }));
3945
4066
  }
4067
+ async createTaskPushNotificationConfig(params) {
4068
+ const result = await this.rpc("CreateTaskPushNotificationConfig", _mastra_core_a2a_v1.TaskPushNotificationConfig.toJSON(params));
4069
+ return _mastra_core_a2a_v1.TaskPushNotificationConfig.fromJSON(result);
4070
+ }
4071
+ async getTaskPushNotificationConfig(params) {
4072
+ const result = await this.rpc("GetTaskPushNotificationConfig", _mastra_core_a2a_v1.GetTaskPushNotificationConfigRequest.toJSON(params));
4073
+ return _mastra_core_a2a_v1.TaskPushNotificationConfig.fromJSON(result);
4074
+ }
4075
+ async listTaskPushNotificationConfigs(params) {
4076
+ const result = await this.rpc("ListTaskPushNotificationConfigs", _mastra_core_a2a_v1.ListTaskPushNotificationConfigsRequest.toJSON(params));
4077
+ return _mastra_core_a2a_v1.ListTaskPushNotificationConfigsResponse.fromJSON(result);
4078
+ }
4079
+ async deleteTaskPushNotificationConfig(params) {
4080
+ await this.rpc("DeleteTaskPushNotificationConfig", _mastra_core_a2a_v1.DeleteTaskPushNotificationConfigRequest.toJSON(params));
4081
+ }
3946
4082
  async getAgentCard() {
3947
4083
  const card = await this.request(`/.well-known/${this.agentId}/agent-card.json`, { headers: { "A2A-Version": "1.0" } });
3948
4084
  return _mastra_core_a2a_v1.AgentCard.fromJSON(card);
3949
4085
  }
3950
4086
  async sendMessage(params) {
3951
- const result = await this.rpc("message/send", _mastra_core_a2a_v1.SendMessageRequest.toJSON(params));
4087
+ const result = await this.rpc("SendMessage", _mastra_core_a2a_v1.SendMessageRequest.toJSON(params));
3952
4088
  return _mastra_core_a2a_v1.SendMessageResponse.fromJSON(result);
3953
4089
  }
3954
4090
  async *sendMessageStream(params) {
@@ -3958,7 +4094,7 @@ var A2AV1 = class extends BaseResource {
3958
4094
  body: {
3959
4095
  jsonrpc: "2.0",
3960
4096
  id: crypto.randomUUID(),
3961
- method: "message/stream",
4097
+ method: "SendStreamingMessage",
3962
4098
  params: _mastra_core_a2a_v1.SendMessageRequest.toJSON(params)
3963
4099
  },
3964
4100
  stream: true
@@ -3966,15 +4102,15 @@ var A2AV1 = class extends BaseResource {
3966
4102
  for await (const event of processA2AStream(await requireResponseBody(response, "message/stream"))) yield _mastra_core_a2a_v1.StreamResponse.fromJSON(event);
3967
4103
  }
3968
4104
  async getTask(params) {
3969
- const result = await this.rpc("tasks/get", _mastra_core_a2a_v1.GetTaskRequest.toJSON(params));
4105
+ const result = await this.rpc("GetTask", _mastra_core_a2a_v1.GetTaskRequest.toJSON(params));
3970
4106
  return _mastra_core_a2a_v1.Task.fromJSON(result);
3971
4107
  }
3972
4108
  async listTasks(params) {
3973
- const result = await this.rpc("tasks/list", _mastra_core_a2a_v1.ListTasksRequest.toJSON(params));
4109
+ const result = await this.rpc("ListTasks", _mastra_core_a2a_v1.ListTasksRequest.toJSON(params));
3974
4110
  return _mastra_core_a2a_v1.ListTasksResponse.fromJSON(result);
3975
4111
  }
3976
4112
  async cancelTask(params) {
3977
- const result = await this.rpc("tasks/cancel", _mastra_core_a2a_v1.CancelTaskRequest.toJSON(params));
4113
+ const result = await this.rpc("CancelTask", _mastra_core_a2a_v1.CancelTaskRequest.toJSON(params));
3978
4114
  return _mastra_core_a2a_v1.Task.fromJSON(result);
3979
4115
  }
3980
4116
  async *resubscribeTask(params) {
@@ -3984,7 +4120,7 @@ var A2AV1 = class extends BaseResource {
3984
4120
  body: {
3985
4121
  jsonrpc: "2.0",
3986
4122
  id: crypto.randomUUID(),
3987
- method: "tasks/resubscribe",
4123
+ method: "SubscribeToTask",
3988
4124
  params: _mastra_core_a2a_v1.SubscribeToTaskRequest.toJSON(params)
3989
4125
  },
3990
4126
  stream: true
@@ -4017,13 +4153,14 @@ var MCPTool = class extends BaseResource {
4017
4153
  /**
4018
4154
  * Executes this specific tool on the MCP server.
4019
4155
  * @param params - Parameters for tool execution, including data/args and optional requestContext.
4020
- * @returns Promise containing the result of the tool execution.
4156
+ * On a 2026-07-28 server a tool can answer `{ status: 'suspended', suspendPayload, resumeSchema }`;
4157
+ * call again with the same `data` plus `resumeData` (matching `resumeSchema`) and the echoed
4158
+ * `suspendPayload` to continue it.
4159
+ * @returns Promise containing `{ result }`, or the suspended shape described above.
4021
4160
  */
4022
4161
  execute(params) {
4023
- const body = {};
4024
- if (params.data !== void 0) body.data = params.data;
4025
- if (params.requestContext !== void 0) body.requestContext = params.requestContext;
4026
- return this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}/execute`, {
4162
+ const { requestContext, ...body } = params;
4163
+ return this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}/execute${requestContextQueryString(requestContext)}`, {
4027
4164
  method: "POST",
4028
4165
  body
4029
4166
  });
@@ -4041,23 +4178,29 @@ var AgentBuilder = class extends BaseResource {
4041
4178
  this.actionId = actionId;
4042
4179
  }
4043
4180
  transformWorkflowResult(result) {
4044
- if (result.status === "success") return {
4045
- success: result.result.success || false,
4046
- applied: result.result.applied || false,
4047
- branchName: result.result.branchName,
4048
- message: result.result.message || "Agent builder action completed",
4049
- validationResults: result.result.validationResults,
4050
- error: result.result.error,
4051
- errors: result.result.errors,
4052
- stepResults: result.result.stepResults
4053
- };
4054
- else if (result.status === "failed") return {
4055
- success: false,
4056
- applied: false,
4057
- message: `Agent builder action failed: ${result.error.message}`,
4058
- error: result.error.message
4059
- };
4060
- else return {
4181
+ if (result.status === "success") {
4182
+ const actionResult = result.result;
4183
+ return {
4184
+ success: actionResult?.success ?? false,
4185
+ applied: actionResult?.applied ?? false,
4186
+ branchName: actionResult?.branchName,
4187
+ message: actionResult?.message ?? "Agent builder action completed",
4188
+ validationResults: actionResult?.validationResults,
4189
+ error: actionResult?.error,
4190
+ errors: actionResult?.errors,
4191
+ stepResults: actionResult?.stepResults
4192
+ };
4193
+ }
4194
+ if (result.status === "failed") {
4195
+ const message = result.error?.message ?? "Agent builder action failed";
4196
+ return {
4197
+ success: false,
4198
+ applied: false,
4199
+ message: `Agent builder action failed: ${message}`,
4200
+ error: message
4201
+ };
4202
+ }
4203
+ return {
4061
4204
  success: false,
4062
4205
  applied: false,
4063
4206
  message: "Agent builder action was suspended",
@@ -4253,7 +4396,7 @@ var AgentBuilder = class extends BaseResource {
4253
4396
  * This calls `/agent-builder/:actionId`.
4254
4397
  */
4255
4398
  async details() {
4256
- return await this.request(`/agent-builder/${this.actionId}`);
4399
+ return this.request(`/agent-builder/${this.actionId}`);
4257
4400
  }
4258
4401
  /**
4259
4402
  * Gets all runs for this agent builder action.
@@ -4386,6 +4529,24 @@ var Observability = class extends BaseResource {
4386
4529
  body: params
4387
4530
  });
4388
4531
  }
4532
+ /** Returns canonical and observed fields available to the advanced trace-query grammar. */
4533
+ getTraceQueryFields(params, options) {
4534
+ return this.request("/observability/traces/query/fields", {
4535
+ method: "POST",
4536
+ body: params,
4537
+ retries: 0,
4538
+ signal: options?.signal
4539
+ });
4540
+ }
4541
+ /** Returns bounded string suggestions for one eligible trace-query field. */
4542
+ getTraceQueryValues(params, options) {
4543
+ return this.request("/observability/traces/query/values", {
4544
+ method: "POST",
4545
+ body: params,
4546
+ retries: 0,
4547
+ signal: options?.signal
4548
+ });
4549
+ }
4389
4550
  /**
4390
4551
  * Queries thread identities using eligible-trace and cross-trace predicates.
4391
4552
  *
@@ -4482,7 +4643,7 @@ var Observability = class extends BaseResource {
4482
4643
  deleteTraces(params) {
4483
4644
  return this.request(`/observability/traces/delete`, {
4484
4645
  method: "POST",
4485
- body: { traceIds: params.traceIds }
4646
+ body: params
4486
4647
  });
4487
4648
  }
4488
4649
  /**
@@ -6534,12 +6695,15 @@ var MastraClient = class extends BaseResource {
6534
6695
  * @returns Promise containing the thread messages
6535
6696
  */
6536
6697
  listThreadMessages(threadId, opts = {}) {
6537
- let url = "";
6538
- const includeSystemRemindersQuery = opts.includeSystemReminders === void 0 ? "" : `includeSystemReminders=${opts.includeSystemReminders}`;
6539
- if (opts.networkId) url = `/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}${includeSystemRemindersQuery ? `&${includeSystemRemindersQuery}` : ""}${requestContextQueryString(opts.requestContext, includeSystemRemindersQuery ? "&" : "&")}`;
6540
- else if (opts.agentId) url = `/memory/threads/${threadId}/messages?agentId=${opts.agentId}${includeSystemRemindersQuery ? `&${includeSystemRemindersQuery}` : ""}${requestContextQueryString(opts.requestContext, "&")}`;
6541
- else url = `/memory/threads/${threadId}/messages${includeSystemRemindersQuery ? `?${includeSystemRemindersQuery}` : ""}${requestContextQueryString(opts.requestContext, includeSystemRemindersQuery ? "&" : "?")}`;
6542
- return this.request(url);
6698
+ if (opts.networkId) {
6699
+ const query = memoryMessagesQuery(opts);
6700
+ query.set("networkId", opts.networkId);
6701
+ return this.request(`/memory/network/threads/${threadId}/messages?${query.toString()}${requestContextQueryString(opts.requestContext, "&")}`);
6702
+ }
6703
+ return this.getMemoryThread({
6704
+ threadId,
6705
+ agentId: opts.agentId
6706
+ }).listMessages(opts);
6543
6707
  }
6544
6708
  deleteThread(threadId, opts) {
6545
6709
  if (!opts || !!opts.agentId === !!opts.networkId) throw new Error("MastraClient.deleteThread() requires exactly one of agentId or networkId. The server cannot resolve which memory store owns the thread without one, and passing both is ambiguous.");
@@ -6964,6 +7128,14 @@ var MastraClient = class extends BaseResource {
6964
7128
  queryTraces(params) {
6965
7129
  return this.observability.queryTraces(params);
6966
7130
  }
7131
+ /** Returns canonical and observed fields available to the advanced trace-query grammar. */
7132
+ getTraceQueryFields(params, options) {
7133
+ return this.observability.getTraceQueryFields(params, options);
7134
+ }
7135
+ /** Returns bounded string suggestions for one eligible trace-query field. */
7136
+ getTraceQueryValues(params, options) {
7137
+ return this.observability.getTraceQueryValues(params, options);
7138
+ }
6967
7139
  /** Queries thread identities using eligible-trace and cross-trace predicates. */
6968
7140
  queryTraceThreads(params) {
6969
7141
  return this.observability.queryTraceThreads(params);