@mastra/client-js 1.47.0-alpha.4 → 1.47.0-alpha.6

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.
package/dist/index.d.ts CHANGED
@@ -11,5 +11,6 @@ export type { ObservabilityCollector } from './observability/types.js';
11
11
  export type { QueryTraceThreadsInput, QueryTraceThreadsResult, QueryTracesInput } from './resources/observability.js';
12
12
  export type { UIMessageWithMetadata } from '@mastra/core/agent';
13
13
  export type { GetMetricTimeSeriesResponse } from './types.js';
14
+ export type { GetTraceQueryFieldsArgs, GetTraceQueryFieldsResponse, GetTraceQueryValuesArgs, GetTraceQueryValuesResponse, TraceQueryCanonicalFieldDescriptor, TraceQueryObservedFieldDescriptor, TraceQueryOperator, TraceQueryPredicateScope, TraceQueryValueKind, } from './resources/observability-route-types.js';
14
15
  export type { Body, Client, ClientMethod, ClientPath, ClientRequest, ClientResponse, ClientResponseKind, ClientRoute, PathParams, QueryParams, RouteKey, RouteRequest, RouteResponse, RouteResponseType, RouteTypes, } from './route-types.generated.js';
15
16
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,YAAY,EACV,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,EACnB,sBAAsB,EACtB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,kCAAkC,EAClC,wBAAwB,EACxB,mBAAmB,EACnB,+BAA+B,GAChC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AACvG,YAAY,EACV,eAAe,EACf,sBAAsB,EACtB,iBAAiB,EACjB,oBAAoB,EACpB,yBAAyB,EACzB,yBAAyB,EACzB,6BAA6B,EAC7B,sCAAsC,EACtC,2BAA2B,EAC3B,UAAU,GACX,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAG9D,YAAY,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACpE,YAAY,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AACnH,YAAY,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAChE,YAAY,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AAC3D,YAAY,EACV,IAAI,EACJ,MAAM,EACN,YAAY,EACZ,UAAU,EACV,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,UAAU,GACX,MAAM,4BAA4B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,YAAY,EACV,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,EACnB,sBAAsB,EACtB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,kCAAkC,EAClC,wBAAwB,EACxB,mBAAmB,EACnB,+BAA+B,GAChC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AACvG,YAAY,EACV,eAAe,EACf,sBAAsB,EACtB,iBAAiB,EACjB,oBAAoB,EACpB,yBAAyB,EACzB,yBAAyB,EACzB,6BAA6B,EAC7B,sCAAsC,EACtC,2BAA2B,EAC3B,UAAU,GACX,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAG9D,YAAY,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACpE,YAAY,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AACnH,YAAY,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAChE,YAAY,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AAC3D,YAAY,EACV,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,EACvB,2BAA2B,EAC3B,kCAAkC,EAClC,iCAAiC,EACjC,kBAAkB,EAClB,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,uCAAuC,CAAC;AAC/C,YAAY,EACV,IAAI,EACJ,MAAM,EACN,YAAY,EACZ,UAAU,EACV,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,UAAU,GACX,MAAM,4BAA4B,CAAC"}
package/dist/index.js CHANGED
@@ -341,6 +341,33 @@ function buildTenancyQuery(tenancy) {
341
341
  const queryString = searchParams.toString();
342
342
  return queryString ? `?${queryString}` : "";
343
343
  }
344
+ /**
345
+ * Merges multiple optional abort signals into one. Returns `undefined` when no
346
+ * signals are provided, the single signal when only one is provided, and a
347
+ * combined signal otherwise. Uses `AbortSignal.any` when available and falls
348
+ * back to a manual listener merge for runtimes that lack it.
349
+ */
350
+ function mergeAbortSignals(...signals) {
351
+ const defined = signals.filter((signal) => signal !== void 0);
352
+ if (defined.length === 0) return void 0;
353
+ if (defined.length === 1) return defined[0];
354
+ if (typeof AbortSignal.any === "function") return AbortSignal.any(defined);
355
+ const controller = new AbortController();
356
+ const alreadyAborted = defined.find((signal) => signal.aborted);
357
+ if (alreadyAborted) {
358
+ controller.abort(alreadyAborted.reason);
359
+ return controller.signal;
360
+ }
361
+ const cleanup = () => {
362
+ for (const signal of defined) signal.removeEventListener("abort", onAbort);
363
+ };
364
+ function onAbort() {
365
+ cleanup();
366
+ controller.abort(this.reason);
367
+ }
368
+ for (const signal of defined) signal.addEventListener("abort", onAbort);
369
+ return controller.signal;
370
+ }
344
371
  //#endregion
345
372
  //#region src/utils/client-tool-model-output.ts
346
373
  /**
@@ -535,43 +562,61 @@ var BaseResource = class {
535
562
  */
536
563
  async request(path, options = {}) {
537
564
  let lastError = null;
538
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials, fetch: customFetch } = this.options;
565
+ const { baseUrl, retries: defaultRetries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials, fetch: customFetch } = this.options;
566
+ const { retries: requestRetries, ...fetchOptions } = options;
567
+ const retries = requestRetries ?? defaultRetries;
568
+ if (!Number.isSafeInteger(retries) || retries < 0) throw new RangeError("retries must be a non-negative safe integer");
569
+ const signal = mergeAbortSignals(this.options.abortSignal, fetchOptions.signal);
539
570
  const fetchFn = customFetch || fetch;
540
571
  let delay = backoffMs;
541
572
  const fullPath = `${this.apiPrefix}${path}`;
542
- for (let attempt = 0; attempt <= retries; attempt++) try {
543
- const response = await fetchFn(`${baseUrl.replace(/\/$/, "")}${fullPath}`, {
544
- ...options,
545
- headers: {
546
- ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT" || options.method === "PATCH" || options.method === "DELETE") ? { "content-type": "application/json" } : {},
547
- ...headers,
548
- ...options.headers
549
- },
550
- signal: this.options.abortSignal,
551
- credentials: options.credentials ?? credentials,
552
- body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
553
- });
554
- if (!response.ok) {
555
- const errorBody = await response.text();
556
- let parsedBody;
557
- let errorMessage = `HTTP error! status: ${response.status}`;
558
- try {
559
- parsedBody = JSON.parse(errorBody);
560
- errorMessage += ` - ${JSON.stringify(parsedBody)}`;
561
- } catch {
562
- if (errorBody) errorMessage += ` - ${errorBody}`;
573
+ for (let attempt = 0; attempt <= retries; attempt++) {
574
+ if (signal?.aborted) throw signal.reason ?? new DOMException("This operation was aborted", "AbortError");
575
+ try {
576
+ const response = await fetchFn(`${baseUrl.replace(/\/$/, "")}${fullPath}`, {
577
+ ...fetchOptions,
578
+ headers: {
579
+ ...fetchOptions.body && !(fetchOptions.body instanceof FormData) && (fetchOptions.method === "POST" || fetchOptions.method === "PUT" || fetchOptions.method === "PATCH" || fetchOptions.method === "DELETE") ? { "content-type": "application/json" } : {},
580
+ ...headers,
581
+ ...fetchOptions.headers
582
+ },
583
+ signal,
584
+ credentials: fetchOptions.credentials ?? credentials,
585
+ body: fetchOptions.body instanceof FormData ? fetchOptions.body : fetchOptions.body ? JSON.stringify(fetchOptions.body) : void 0
586
+ });
587
+ if (!response.ok) {
588
+ const errorBody = await response.text();
589
+ let parsedBody;
590
+ let errorMessage = `HTTP error! status: ${response.status}`;
591
+ try {
592
+ parsedBody = JSON.parse(errorBody);
593
+ errorMessage += ` - ${JSON.stringify(parsedBody)}`;
594
+ } catch {
595
+ if (errorBody) errorMessage += ` - ${errorBody}`;
596
+ }
597
+ throw new MastraClientError(response.status, response.statusText, errorMessage, parsedBody);
563
598
  }
564
- throw new MastraClientError(response.status, response.statusText, errorMessage, parsedBody);
599
+ if (options.stream) return response;
600
+ return await response.json();
601
+ } catch (error) {
602
+ lastError = error;
603
+ if (signal?.aborted || error?.name === "AbortError") throw error;
604
+ const status = error.status;
605
+ if (status !== void 0 && status >= 400 && status < 500) throw error;
606
+ if (attempt === retries) break;
607
+ await new Promise((resolve, reject) => {
608
+ const timer = setTimeout(() => {
609
+ signal?.removeEventListener("abort", onAbort);
610
+ resolve();
611
+ }, delay);
612
+ const onAbort = () => {
613
+ clearTimeout(timer);
614
+ reject(signal?.reason ?? new DOMException("This operation was aborted", "AbortError"));
615
+ };
616
+ signal?.addEventListener("abort", onAbort, { once: true });
617
+ });
618
+ delay = Math.min(delay * 2, maxBackoffMs);
565
619
  }
566
- if (options.stream) return response;
567
- return await response.json();
568
- } catch (error) {
569
- lastError = error;
570
- const status = error.status;
571
- if (status !== void 0 && status >= 400 && status < 500) throw error;
572
- if (attempt === retries) break;
573
- await new Promise((resolve) => setTimeout(resolve, delay));
574
- delay = Math.min(delay * 2, maxBackoffMs);
575
620
  }
576
621
  throw lastError || /* @__PURE__ */ new Error("Request failed");
577
622
  }
@@ -1301,8 +1346,10 @@ var Agent = class extends BaseResource {
1301
1346
  return this.request(`/stored/agents/${encodeURIComponent(this.agentId)}/versions/compare?${queryParams.toString()}${contextString ? `&${contextString.slice(1)}` : ""}`);
1302
1347
  }
1303
1348
  async generateLegacy(params) {
1349
+ const { abortSignal: perCallSignal, ...bodyParams } = params;
1350
+ const abortSignal = mergeAbortSignals(this.options.abortSignal, perCallSignal);
1304
1351
  const processedParams = {
1305
- ...params,
1352
+ ...bodyParams,
1306
1353
  output: params.output ? zodToJsonSchema$1(params.output) : void 0,
1307
1354
  experimental_output: params.experimental_output ? zodToJsonSchema$1(params.experimental_output) : void 0,
1308
1355
  requestContext: parseClientRequestContext(params.requestContext),
@@ -1311,9 +1358,11 @@ var Agent = class extends BaseResource {
1311
1358
  const { resourceId, threadId, requestContext } = processedParams;
1312
1359
  const response = await this.request(`/agents/${this.agentId}/generate-legacy`, {
1313
1360
  method: "POST",
1314
- body: processedParams
1361
+ body: processedParams,
1362
+ signal: abortSignal
1315
1363
  });
1316
1364
  if (response.finishReason === "tool-calls") {
1365
+ if (abortSignal?.aborted) throw abortSignal.reason ?? new DOMException("This operation was aborted", "AbortError");
1317
1366
  const toolCalls = response.toolCalls;
1318
1367
  if (!toolCalls || !Array.isArray(toolCalls)) return response;
1319
1368
  for (const toolCall of toolCalls) {
@@ -1362,8 +1411,10 @@ var Agent = class extends BaseResource {
1362
1411
  messages
1363
1412
  };
1364
1413
  const resolvedClientTools = params.clientToolsResolver?.() ?? params.clientTools;
1414
+ const abortSignal = mergeAbortSignals(this.options.abortSignal, params.abortSignal);
1365
1415
  const processedParams = {
1366
1416
  ...params,
1417
+ abortSignal: void 0,
1367
1418
  requestContext: parseClientRequestContext(params.requestContext),
1368
1419
  clientTools: processClientTools(resolvedClientTools),
1369
1420
  structuredOutput: params.structuredOutput ? {
@@ -1377,20 +1428,24 @@ var Agent = class extends BaseResource {
1377
1428
  const threadId = typeof thread === "string" ? thread : thread?.id;
1378
1429
  const response = await this.request(`/agents/${this.agentId}/generate`, {
1379
1430
  method: "POST",
1380
- body: processedParams
1381
- });
1382
- if (response.finishReason === "tool-calls") return executeToolCallAndRespond({
1383
- response,
1384
- params: {
1385
- ...params,
1386
- clientTools: resolvedClientTools
1387
- },
1388
- agentId: this.agentId,
1389
- resourceId,
1390
- threadId,
1391
- requestContext,
1392
- respondFn: this.generate.bind(this)
1431
+ body: processedParams,
1432
+ signal: abortSignal
1393
1433
  });
1434
+ if (response.finishReason === "tool-calls") {
1435
+ if (abortSignal?.aborted) throw abortSignal.reason ?? new DOMException("This operation was aborted", "AbortError");
1436
+ return executeToolCallAndRespond({
1437
+ response,
1438
+ params: {
1439
+ ...params,
1440
+ clientTools: resolvedClientTools
1441
+ },
1442
+ agentId: this.agentId,
1443
+ resourceId,
1444
+ threadId,
1445
+ requestContext,
1446
+ respondFn: this.generate.bind(this)
1447
+ });
1448
+ }
1394
1449
  return response;
1395
1450
  }
1396
1451
  async processChatResponse({ stream, update, onToolCall, onFinish, getCurrentDate = () => /* @__PURE__ */ new Date(), lastMessage }) {
@@ -1626,7 +1681,7 @@ var Agent = class extends BaseResource {
1626
1681
  throw new Error(error);
1627
1682
  }
1628
1683
  });
1629
- onFinish?.({
1684
+ await onFinish?.({
1630
1685
  message,
1631
1686
  finishReason,
1632
1687
  usage
@@ -1645,8 +1700,22 @@ var Agent = class extends BaseResource {
1645
1700
  requestContext: parseClientRequestContext(params.requestContext),
1646
1701
  clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
1647
1702
  };
1648
- const { readable, writable } = new TransformStream();
1649
- const response = await this.processStreamResponseLegacy(processedParams, writable);
1703
+ const { readable: innerReadable, writable } = new TransformStream();
1704
+ const abortController = new AbortController();
1705
+ const signal = mergeAbortSignals(abortController.signal, params.abortSignal, this.options.abortSignal);
1706
+ const innerReader = innerReadable.getReader();
1707
+ const readable = new ReadableStream({
1708
+ async pull(controller) {
1709
+ const { done, value } = await innerReader.read();
1710
+ if (done) controller.close();
1711
+ else controller.enqueue(value);
1712
+ },
1713
+ cancel(reason) {
1714
+ abortController.abort(reason);
1715
+ return innerReader.cancel(reason).catch(() => {});
1716
+ }
1717
+ });
1718
+ const response = await this.processStreamResponseLegacy(processedParams, writable, signal);
1650
1719
  const streamResponse = new Response(readable, {
1651
1720
  status: response.status,
1652
1721
  statusText: response.statusText,
@@ -1887,29 +1956,63 @@ var Agent = class extends BaseResource {
1887
1956
  }
1888
1957
  }
1889
1958
  });
1890
- onFinish?.({
1959
+ await onFinish?.({
1891
1960
  message,
1892
1961
  finishReason,
1893
1962
  usage
1894
1963
  });
1895
1964
  }
1896
- async processStreamResponse(processedParams, controller, route = "stream") {
1965
+ /**
1966
+ * Creates the consumer-facing stream for the streaming methods. Cancelling the
1967
+ * returned stream (or aborting `externalSignal`) aborts the underlying request
1968
+ * and stops any client-tool continuations.
1969
+ */
1970
+ createCancellableStream(externalSignal) {
1971
+ const abortController = new AbortController();
1972
+ let readableController;
1973
+ return {
1974
+ readable: new ReadableStream({
1975
+ start(controller) {
1976
+ readableController = controller;
1977
+ },
1978
+ cancel(reason) {
1979
+ abortController.abort(reason);
1980
+ }
1981
+ }),
1982
+ controller: readableController,
1983
+ signal: mergeAbortSignals(abortController.signal, externalSignal, this.options.abortSignal)
1984
+ };
1985
+ }
1986
+ async processStreamResponse(processedParams, controller, route = "stream", signal) {
1897
1987
  const { memory } = processedParams ?? {};
1898
1988
  const { resource, thread } = memory ?? {};
1899
1989
  const threadId = processedParams.threadId ?? (typeof thread === "string" ? thread : thread?.id);
1900
1990
  const resourceId = processedParams.resourceId ?? resource;
1901
- let requestBody = processedParams;
1991
+ const { abortSignal: _abortSignal, ...serializableParams } = processedParams;
1992
+ let requestBody = serializableParams;
1902
1993
  if (route === "resume-stream") {
1903
- const { messages: _messages, ...resumeStreamBody } = processedParams;
1994
+ const { messages: _messages, ...resumeStreamBody } = serializableParams;
1904
1995
  requestBody = resumeStreamBody;
1905
1996
  }
1906
1997
  const requestPath = route === "stream" && this.routeOverrides?.stream ? this.routeOverrides.stream : `/agents/${this.agentId}/${route}`;
1907
1998
  const response = await this.request(requestPath, {
1908
1999
  method: "POST",
1909
2000
  body: requestBody,
1910
- stream: true
2001
+ stream: true,
2002
+ signal
1911
2003
  });
1912
2004
  if (!response.body) throw new Error("No response body");
2005
+ const isAborted = () => Boolean(signal?.aborted);
2006
+ const isAbortError = (error) => isAborted() || error?.name === "AbortError";
2007
+ const safeClose = () => {
2008
+ try {
2009
+ controller.close();
2010
+ } catch {}
2011
+ };
2012
+ const safeEnqueue = (chunk) => {
2013
+ if (isAborted()) return;
2014
+ controller.enqueue(chunk);
2015
+ };
1913
2016
  try {
1914
2017
  let messages = [];
1915
2018
  let streamRunId = processedParams.runId;
@@ -1921,7 +2024,7 @@ var Agent = class extends BaseResource {
1921
2024
  const lines = pendingText.split("\n\n");
1922
2025
  pendingText = isFinal ? "" : lines.pop() ?? "";
1923
2026
  const readableLines = lines.filter((line) => line.trim() !== "[DONE]" && line.trim() !== "data: [DONE]").join("\n\n");
1924
- if (readableLines) controller.enqueue(new TextEncoder().encode(`${readableLines}\n\n`));
2027
+ if (readableLines) safeEnqueue(new TextEncoder().encode(`${readableLines}\n\n`));
1925
2028
  };
1926
2029
  const pipePromise = streamForController.pipeTo(new WritableStream({
1927
2030
  async write(chunk) {
@@ -1929,26 +2032,32 @@ var Agent = class extends BaseResource {
1929
2032
  enqueueReadableText(decoder.decode(chunk, { stream: true }));
1930
2033
  } catch (error) {
1931
2034
  console.error("Error enqueueing to controller:", error);
1932
- controller.enqueue(chunk);
2035
+ safeEnqueue(chunk);
1933
2036
  }
1934
2037
  },
1935
2038
  close() {
1936
2039
  enqueueReadableText(decoder.decode(), true);
1937
2040
  }
1938
- })).catch((error) => {
1939
- console.error("Error piping to controller:", error);
2041
+ }), { signal }).catch((error) => {
2042
+ if (!isAbortError(error)) console.error("Error piping to controller:", error);
2043
+ safeClose();
2044
+ });
2045
+ const onAbort = () => {
1940
2046
  try {
1941
- controller.close();
2047
+ controller.error(signal?.reason);
1942
2048
  } catch {}
1943
- });
2049
+ };
2050
+ signal?.addEventListener("abort", onAbort, { once: true });
2051
+ const processingStream = signal ? streamForProcessing.pipeThrough(new TransformStream(), { signal }) : streamForProcessing;
1944
2052
  this.processChatResponse_vNext({
1945
- stream: streamForProcessing,
2053
+ stream: processingStream,
1946
2054
  update: ({ message }) => {
1947
2055
  const existingIndex = messages.findIndex((m) => m.id === message.id);
1948
2056
  if (existingIndex !== -1) messages[existingIndex] = message;
1949
2057
  else messages.push(message);
1950
2058
  },
1951
2059
  onFinish: async ({ finishReason, message }) => {
2060
+ if (isAborted()) return;
1952
2061
  if (finishReason === "tool-calls") {
1953
2062
  const toolInvocationsById = /* @__PURE__ */ new Map();
1954
2063
  for (const part of message?.parts ?? []) {
@@ -1975,6 +2084,7 @@ var Agent = class extends BaseResource {
1975
2084
  const syntheticChunks = [];
1976
2085
  const toolResultContents = [];
1977
2086
  for (const toolCall of executableToolCalls) {
2087
+ if (isAborted()) return;
1978
2088
  const clientTool = processedParams.clientTools?.[toolCall.toolName];
1979
2089
  const runId = streamRunId ?? toolCall.toolCallId;
1980
2090
  let result;
@@ -2042,6 +2152,7 @@ var Agent = class extends BaseResource {
2042
2152
  try {
2043
2153
  await pipePromise;
2044
2154
  } catch {}
2155
+ if (isAborted()) return;
2045
2156
  for (const synthetic of syntheticChunks) try {
2046
2157
  const errorForSerialization = synthetic.type === "tool-error" ? synthetic.payload.error : void 0;
2047
2158
  const serializedError = errorForSerialization instanceof Error ? {
@@ -2057,7 +2168,7 @@ var Agent = class extends BaseResource {
2057
2168
  }
2058
2169
  } : synthetic;
2059
2170
  const sseLine = `data: ${JSON.stringify(payloadForWire)}\n\n`;
2060
- controller.enqueue(new TextEncoder().encode(sseLine));
2171
+ safeEnqueue(new TextEncoder().encode(sseLine));
2061
2172
  } catch (enqueueErr) {
2062
2173
  console.error("Failed to enqueue synthetic tool-result chunk:", enqueueErr);
2063
2174
  }
@@ -2071,22 +2182,23 @@ var Agent = class extends BaseResource {
2071
2182
  toolResultMessage
2072
2183
  ];
2073
2184
  const recursionRoute = route === "resume-stream" ? "stream" : route === "resume-stream-until-idle" ? "stream-until-idle" : route;
2185
+ if (isAborted()) return;
2074
2186
  try {
2075
2187
  await this.processStreamResponse({
2076
2188
  ...processedParams,
2077
2189
  messages: updatedMessages,
2078
2190
  clientTools: processClientTools(processedParams.clientToolsResolver?.() ?? processedParams.clientTools)
2079
- }, controller, recursionRoute);
2191
+ }, controller, recursionRoute, signal);
2080
2192
  } catch (error) {
2081
- console.error("Error processing recursive stream response:", error);
2193
+ if (!isAbortError(error)) console.error("Error processing recursive stream response:", error);
2082
2194
  }
2083
2195
  } else {
2084
2196
  await pipePromise;
2085
- controller.close();
2197
+ safeClose();
2086
2198
  }
2087
2199
  } else {
2088
2200
  await pipePromise;
2089
- controller.close();
2201
+ safeClose();
2090
2202
  }
2091
2203
  },
2092
2204
  onStreamChunk: (chunk) => {
@@ -2094,14 +2206,16 @@ var Agent = class extends BaseResource {
2094
2206
  },
2095
2207
  lastMessage: void 0
2096
2208
  }).catch(async (error) => {
2097
- console.error("Error processing stream response:", error);
2209
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2098
2210
  try {
2099
2211
  await pipePromise;
2100
- controller.close();
2101
2212
  } catch {}
2213
+ safeClose();
2214
+ }).finally(() => {
2215
+ signal?.removeEventListener("abort", onAbort);
2102
2216
  });
2103
2217
  } catch (error) {
2104
- console.error("Error processing stream response:", error);
2218
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2105
2219
  }
2106
2220
  return response;
2107
2221
  }
@@ -2198,11 +2312,8 @@ var Agent = class extends BaseResource {
2198
2312
  clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools),
2199
2313
  structuredOutput
2200
2314
  };
2201
- let readableController;
2202
- const readable = new ReadableStream({ start(controller) {
2203
- readableController = controller;
2204
- } });
2205
- const response = await this.processStreamResponse(processedParams, readableController);
2315
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2316
+ const response = await this.processStreamResponse(processedParams, readableController, "stream", signal);
2206
2317
  const streamResponse = new Response(readable, {
2207
2318
  status: response.status,
2208
2319
  statusText: response.statusText,
@@ -2232,11 +2343,8 @@ var Agent = class extends BaseResource {
2232
2343
  clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools),
2233
2344
  structuredOutput
2234
2345
  };
2235
- let readableController;
2236
- const readable = new ReadableStream({ start(controller) {
2237
- readableController = controller;
2238
- } });
2239
- const response = await this.processStreamResponse(processedParams, readableController, "stream-until-idle");
2346
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2347
+ const response = await this.processStreamResponse(processedParams, readableController, "stream-until-idle", signal);
2240
2348
  const streamResponse = new Response(readable, {
2241
2349
  status: response.status,
2242
2350
  statusText: response.statusText,
@@ -2276,11 +2384,8 @@ var Agent = class extends BaseResource {
2276
2384
  ...rest,
2277
2385
  requestContext: parseClientRequestContext(requestContext)
2278
2386
  };
2279
- let readableController;
2280
- const readable = new ReadableStream({ start(controller) {
2281
- readableController = controller;
2282
- } });
2283
- const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call");
2387
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2388
+ const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call", signal);
2284
2389
  const streamResponse = new Response(readable, {
2285
2390
  status: response.status,
2286
2391
  statusText: response.statusText,
@@ -2310,11 +2415,8 @@ var Agent = class extends BaseResource {
2310
2415
  ...rest,
2311
2416
  requestContext: parseClientRequestContext(requestContext)
2312
2417
  };
2313
- let readableController;
2314
- const readable = new ReadableStream({ start(controller) {
2315
- readableController = controller;
2316
- } });
2317
- const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call");
2418
+ const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2419
+ const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call", signal);
2318
2420
  const streamResponse = new Response(readable, {
2319
2421
  status: response.status,
2320
2422
  statusText: response.statusText,
@@ -2384,11 +2486,8 @@ var Agent = class extends BaseResource {
2384
2486
  schema: standardSchemaToJSONSchema(toStandardSchema(options.structuredOutput.schema))
2385
2487
  } : void 0
2386
2488
  };
2387
- let readableController;
2388
- const readable = new ReadableStream({ start(controller) {
2389
- readableController = controller;
2390
- } });
2391
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream");
2489
+ const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
2490
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream", signal);
2392
2491
  const streamResponse = new Response(readable, {
2393
2492
  status: response.status,
2394
2493
  statusText: response.statusText,
@@ -2447,11 +2546,8 @@ var Agent = class extends BaseResource {
2447
2546
  schema: standardSchemaToJSONSchema(toStandardSchema(options.structuredOutput.schema))
2448
2547
  } : void 0
2449
2548
  };
2450
- let readableController;
2451
- const readable = new ReadableStream({ start(controller) {
2452
- readableController = controller;
2453
- } });
2454
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle");
2549
+ const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
2550
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle", signal);
2455
2551
  const streamResponse = new Response(readable, {
2456
2552
  status: response.status,
2457
2553
  statusText: response.statusText,
@@ -2496,32 +2592,41 @@ var Agent = class extends BaseResource {
2496
2592
  /**
2497
2593
  * Processes the stream response and handles tool calls
2498
2594
  */
2499
- async processStreamResponseLegacy(processedParams, writable) {
2595
+ async processStreamResponseLegacy(processedParams, writable, signal) {
2500
2596
  const { memory } = processedParams ?? {};
2501
2597
  const { resource, thread } = memory ?? {};
2502
2598
  const threadId = processedParams.threadId ?? (typeof thread === "string" ? thread : thread?.id);
2503
2599
  const resourceId = processedParams.resourceId ?? resource;
2600
+ const { abortSignal: _abortSignal, ...bodyParams } = processedParams ?? {};
2601
+ const isAborted = () => signal?.aborted === true;
2602
+ const isAbortError = (error) => isAborted() || error?.name === "AbortError";
2504
2603
  const response = await this.request(this.routeOverrides?.stream ?? `/agents/${this.agentId}/stream-legacy`, {
2505
2604
  method: "POST",
2506
- body: processedParams,
2507
- stream: true
2605
+ body: bodyParams,
2606
+ stream: true,
2607
+ signal
2508
2608
  });
2509
2609
  if (!response.body) throw new Error("No response body");
2510
2610
  try {
2511
2611
  let toolCalls = [];
2512
2612
  let messages = [];
2513
2613
  const [streamForWritable, streamForProcessing] = response.body.tee();
2514
- streamForWritable.pipeTo(writable, { preventClose: true }).catch((error) => {
2515
- console.error("Error piping to writable stream:", error);
2614
+ streamForWritable.pipeTo(writable, {
2615
+ preventClose: true,
2616
+ signal
2617
+ }).catch((error) => {
2618
+ if (!isAbortError(error)) console.error("Error piping to writable stream:", error);
2516
2619
  });
2620
+ const processingStream = signal ? streamForProcessing.pipeThrough(new TransformStream(), { signal }) : streamForProcessing;
2517
2621
  this.processChatResponse({
2518
- stream: streamForProcessing,
2622
+ stream: processingStream,
2519
2623
  update: ({ message }) => {
2520
2624
  const existingIndex = messages.findIndex((m) => m.id === message.id);
2521
2625
  if (existingIndex !== -1) messages[existingIndex] = message;
2522
2626
  else messages.push(message);
2523
2627
  },
2524
2628
  onFinish: async ({ finishReason, message }) => {
2629
+ if (isAborted()) return;
2525
2630
  if (finishReason === "tool-calls") {
2526
2631
  const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
2527
2632
  if (toolCall) {
@@ -2553,6 +2658,7 @@ var Agent = class extends BaseResource {
2553
2658
  }
2554
2659
  }
2555
2660
  });
2661
+ if (isAborted()) return;
2556
2662
  const writer = writable.getWriter();
2557
2663
  try {
2558
2664
  await writer.write(new TextEncoder().encode("a:" + JSON.stringify({
@@ -2582,21 +2688,21 @@ var Agent = class extends BaseResource {
2582
2688
  ...processedParams,
2583
2689
  clientTools: processClientTools(processedParams.clientToolsResolver?.() ?? processedParams.clientTools),
2584
2690
  messages: updatedMessages
2585
- }, writable).catch((error) => {
2586
- console.error("Error processing stream response:", error);
2691
+ }, writable, signal).catch((error) => {
2692
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2587
2693
  });
2588
2694
  }
2589
2695
  }
2590
2696
  } else setTimeout(() => {
2591
- writable.close();
2697
+ writable.close().catch(() => {});
2592
2698
  }, 0);
2593
2699
  },
2594
2700
  lastMessage: void 0
2595
2701
  }).catch((error) => {
2596
- console.error("Error processing stream response:", error);
2702
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2597
2703
  });
2598
2704
  } catch (error) {
2599
- console.error("Error processing stream response:", error);
2705
+ if (!isAbortError(error)) console.error("Error processing stream response:", error);
2600
2706
  }
2601
2707
  return response;
2602
2708
  }
@@ -4389,6 +4495,24 @@ var Observability = class extends BaseResource {
4389
4495
  body: params
4390
4496
  });
4391
4497
  }
4498
+ /** Returns canonical and observed fields available to the advanced trace-query grammar. */
4499
+ getTraceQueryFields(params, options) {
4500
+ return this.request("/observability/traces/query/fields", {
4501
+ method: "POST",
4502
+ body: params,
4503
+ retries: 0,
4504
+ signal: options?.signal
4505
+ });
4506
+ }
4507
+ /** Returns bounded string suggestions for one eligible trace-query field. */
4508
+ getTraceQueryValues(params, options) {
4509
+ return this.request("/observability/traces/query/values", {
4510
+ method: "POST",
4511
+ body: params,
4512
+ retries: 0,
4513
+ signal: options?.signal
4514
+ });
4515
+ }
4392
4516
  /**
4393
4517
  * Queries thread identities using eligible-trace and cross-trace predicates.
4394
4518
  *
@@ -6967,6 +7091,14 @@ var MastraClient = class extends BaseResource {
6967
7091
  queryTraces(params) {
6968
7092
  return this.observability.queryTraces(params);
6969
7093
  }
7094
+ /** Returns canonical and observed fields available to the advanced trace-query grammar. */
7095
+ getTraceQueryFields(params, options) {
7096
+ return this.observability.getTraceQueryFields(params, options);
7097
+ }
7098
+ /** Returns bounded string suggestions for one eligible trace-query field. */
7099
+ getTraceQueryValues(params, options) {
7100
+ return this.observability.getTraceQueryValues(params, options);
7101
+ }
6970
7102
  /** Queries thread identities using eligible-trace and cross-trace predicates. */
6971
7103
  queryTraceThreads(params) {
6972
7104
  return this.observability.queryTraceThreads(params);