@mastra/client-js 1.17.2-alpha.2 → 1.18.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.
package/dist/index.cjs CHANGED
@@ -7,6 +7,12 @@ var schema = require('@mastra/schema-compat/schema');
7
7
  var requestContext = require('@mastra/core/request-context');
8
8
  var zodToJson = require('@mastra/schema-compat/zod-to-json');
9
9
  var a2a = require('@mastra/core/a2a');
10
+ var canonicalize = require('canonicalize');
11
+ var jose = require('jose');
12
+
13
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
+
15
+ var canonicalize__default = /*#__PURE__*/_interopDefault(canonicalize);
10
16
 
11
17
  // src/resources/agent.ts
12
18
  function normalizeRoutePath(path) {
@@ -465,8 +471,14 @@ var Agent = class extends BaseResource {
465
471
  const queryParams = new URLSearchParams();
466
472
  if (params?.page !== void 0) queryParams.set("page", String(params.page));
467
473
  if (params?.perPage !== void 0) queryParams.set("perPage", String(params.perPage));
468
- if (params?.orderBy) queryParams.set("orderBy", params.orderBy);
469
- if (params?.sortDirection) queryParams.set("sortDirection", params.sortDirection);
474
+ if (params?.orderBy) {
475
+ if (params.orderBy.field) {
476
+ queryParams.set("orderBy[field]", params.orderBy.field);
477
+ }
478
+ if (params.orderBy.direction) {
479
+ queryParams.set("orderBy[direction]", params.orderBy.direction);
480
+ }
481
+ }
470
482
  const queryString = queryParams.toString();
471
483
  const contextString = requestContextQueryString(requestContext);
472
484
  return this.request(
@@ -1640,6 +1652,43 @@ var Agent = class extends BaseResource {
1640
1652
  };
1641
1653
  return streamResponse;
1642
1654
  }
1655
+ /**
1656
+ * Resumes a suspended agent stream until idle with custom resume data.
1657
+ * Used to continue execution after a suspension point (e.g., workflow suspend within an agent).
1658
+ */
1659
+ async resumeStreamUntilIdle(resumeData, options) {
1660
+ const processedParams = {
1661
+ ...options,
1662
+ resumeData,
1663
+ requestContext: parseClientRequestContext(options.requestContext),
1664
+ clientTools: processClientTools(options.clientTools),
1665
+ structuredOutput: options.structuredOutput ? {
1666
+ ...options.structuredOutput,
1667
+ schema: schema.standardSchemaToJSONSchema(schema.toStandardSchema(options.structuredOutput.schema))
1668
+ } : void 0
1669
+ };
1670
+ let readableController;
1671
+ const readable = new ReadableStream({
1672
+ start(controller) {
1673
+ readableController = controller;
1674
+ }
1675
+ });
1676
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle");
1677
+ const streamResponse = new Response(readable, {
1678
+ status: response.status,
1679
+ statusText: response.statusText,
1680
+ headers: response.headers
1681
+ });
1682
+ streamResponse.processDataStream = async ({
1683
+ onChunk
1684
+ }) => {
1685
+ await processMastraStream({
1686
+ stream: streamResponse.body,
1687
+ onChunk
1688
+ });
1689
+ };
1690
+ return streamResponse;
1691
+ }
1643
1692
  /**
1644
1693
  * Approves a pending tool call and returns the complete response (non-streaming).
1645
1694
  * Used when `requireToolApproval` is enabled with generate() to allow the agent to proceed.
@@ -1861,8 +1910,22 @@ var MemoryThread = class extends BaseResource {
1861
1910
  /**
1862
1911
  * Builds the query string for agentId (if provided)
1863
1912
  */
1864
- getAgentIdQueryParam(prefix = "?") {
1865
- return this.agentId ? `${prefix}agentId=${this.agentId}` : "";
1913
+ getAgentIdQueryParam(prefix = "?", overrideAgentId) {
1914
+ const agentId = overrideAgentId ?? this.agentId;
1915
+ return agentId ? `${prefix}agentId=${agentId}` : "";
1916
+ }
1917
+ /**
1918
+ * Resolves the agentId to use for a write request. Prefers the per-call value, falls back
1919
+ * to the constructor value, and throws if neither is set.
1920
+ */
1921
+ requireAgentId(perCallAgentId, methodName) {
1922
+ const agentId = perCallAgentId ?? this.agentId;
1923
+ if (!agentId) {
1924
+ throw new Error(
1925
+ `MemoryThread.${methodName}() requires an agentId. Pass it via getMemoryThread({ threadId, agentId }) or as a parameter to ${methodName}().`
1926
+ );
1927
+ }
1928
+ return agentId;
1866
1929
  }
1867
1930
  /**
1868
1931
  * Retrieves the memory thread details
@@ -1876,25 +1939,30 @@ var MemoryThread = class extends BaseResource {
1876
1939
  }
1877
1940
  /**
1878
1941
  * Updates the memory thread properties
1879
- * @param params - Update parameters including title, metadata, and optional request context
1942
+ * @param params - Update parameters including title, metadata, and optional request context.
1943
+ * `agentId` is required by the server; pass it here if not supplied on the constructor.
1880
1944
  * @returns Promise containing updated thread details
1881
1945
  */
1882
1946
  update(params) {
1883
- const agentIdParam = this.getAgentIdQueryParam("?");
1884
- const contextParam = requestContextQueryString(params.requestContext, agentIdParam ? "&" : "?");
1947
+ const agentId = this.requireAgentId(params.agentId, "update");
1948
+ const { agentId: _omitAgentId, requestContext, ...body } = params;
1949
+ const agentIdParam = `?agentId=${agentId}`;
1950
+ const contextParam = requestContextQueryString(requestContext, "&");
1885
1951
  return this.request(`/memory/threads/${this.threadId}${agentIdParam}${contextParam}`, {
1886
1952
  method: "PATCH",
1887
- body: params
1953
+ body
1888
1954
  });
1889
1955
  }
1890
1956
  /**
1891
1957
  * Deletes the memory thread
1892
- * @param requestContext - Optional request context to pass as query parameter
1958
+ * @param opts - Optional `agentId` (required by the server when not supplied on the constructor)
1959
+ * and request context.
1893
1960
  * @returns Promise containing deletion result
1894
1961
  */
1895
- delete(requestContext) {
1896
- const agentIdParam = this.getAgentIdQueryParam("?");
1897
- const contextParam = requestContextQueryString(requestContext, agentIdParam ? "&" : "?");
1962
+ delete(opts = {}) {
1963
+ const agentId = this.requireAgentId(opts.agentId, "delete");
1964
+ const agentIdParam = `?agentId=${agentId}`;
1965
+ const contextParam = requestContextQueryString(opts.requestContext, "&");
1898
1966
  return this.request(`/memory/threads/${this.threadId}${agentIdParam}${contextParam}`, {
1899
1967
  method: "DELETE"
1900
1968
  });
@@ -1924,37 +1992,46 @@ var MemoryThread = class extends BaseResource {
1924
1992
  * Deletes one or more messages from the thread
1925
1993
  * @param messageIds - Can be a single message ID (string), array of message IDs,
1926
1994
  * message object with id property, or array of message objects
1927
- * @param requestContext - Optional request context to pass as query parameter
1995
+ * @param opts - Optional `agentId` (required by the server when not supplied on the constructor)
1996
+ * and request context. For backwards compatibility a `RequestContext` may also be
1997
+ * passed directly as the second argument.
1928
1998
  * @returns Promise containing deletion result
1929
1999
  */
1930
- deleteMessages(messageIds, requestContext) {
1931
- const queryParams = {};
1932
- if (this.agentId) queryParams.agentId = this.agentId;
1933
- const query = new URLSearchParams(queryParams);
1934
- const queryString = query.toString();
1935
- return this.request(
1936
- `/memory/messages/delete${queryString ? `?${queryString}` : ""}${requestContextQueryString(requestContext, queryString ? "&" : "?")}`,
1937
- {
1938
- method: "POST",
1939
- body: { messageIds }
1940
- }
1941
- );
2000
+ deleteMessages(messageIds, opts = {}) {
2001
+ const { agentId: explicitAgentId, requestContext } = normalizeWriteOpts(opts);
2002
+ const agentId = this.requireAgentId(explicitAgentId, "deleteMessages");
2003
+ const queryString = `agentId=${agentId}`;
2004
+ return this.request(`/memory/messages/delete?${queryString}${requestContextQueryString(requestContext, "&")}`, {
2005
+ method: "POST",
2006
+ body: { messageIds }
2007
+ });
1942
2008
  }
1943
2009
  /**
1944
2010
  * Clones the thread with all its messages to a new thread
1945
- * @param params - Clone parameters including optional new thread ID, title, metadata, and message filters
2011
+ * @param params - Clone parameters including optional new thread ID, title, metadata, and message filters.
2012
+ * `agentId` is required by the server; pass it here if not supplied on the constructor.
1946
2013
  * @returns Promise containing the cloned thread and copied messages
1947
2014
  */
1948
2015
  clone(params = {}) {
1949
- const { requestContext, ...body } = params;
1950
- const agentIdParam = this.getAgentIdQueryParam("?");
1951
- const contextParam = requestContextQueryString(requestContext, agentIdParam ? "&" : "?");
2016
+ const agentId = this.requireAgentId(params.agentId, "clone");
2017
+ const { agentId: _omitAgentId, requestContext, ...body } = params;
2018
+ const agentIdParam = `?agentId=${agentId}`;
2019
+ const contextParam = requestContextQueryString(requestContext, "&");
1952
2020
  return this.request(`/memory/threads/${this.threadId}/clone${agentIdParam}${contextParam}`, {
1953
2021
  method: "POST",
1954
2022
  body
1955
2023
  });
1956
2024
  }
1957
2025
  };
2026
+ function normalizeWriteOpts(opts) {
2027
+ if (!opts || typeof opts !== "object") return {};
2028
+ if ("agentId" in opts || "requestContext" in opts) {
2029
+ const o = opts;
2030
+ return { agentId: o.agentId, requestContext: o.requestContext };
2031
+ }
2032
+ if (Object.keys(opts).length === 0) return {};
2033
+ return { requestContext: opts };
2034
+ }
1958
2035
 
1959
2036
  // src/resources/vector.ts
1960
2037
  var Vector = class extends BaseResource {
@@ -2775,6 +2852,102 @@ async function* processA2AStream(stream) {
2775
2852
  reader.releaseLock();
2776
2853
  }
2777
2854
  }
2855
+ var DEFAULT_AGENT_CARD_SIGNATURE_ALGORITHMS = [
2856
+ "ES256",
2857
+ "ES384",
2858
+ "ES512",
2859
+ "RS256",
2860
+ "RS384",
2861
+ "RS512",
2862
+ "PS256",
2863
+ "PS384",
2864
+ "PS512"
2865
+ ];
2866
+ function stripAgentCardSignatures(agentCard) {
2867
+ const unsignedCard = structuredClone(agentCard);
2868
+ delete unsignedCard.signatures;
2869
+ return unsignedCard;
2870
+ }
2871
+ function isCryptoKey(value) {
2872
+ const cryptoKeyConstructor = globalThis.CryptoKey;
2873
+ return typeof cryptoKeyConstructor !== "undefined" && value instanceof cryptoKeyConstructor;
2874
+ }
2875
+ function isPem(value) {
2876
+ return value.includes("-----BEGIN ");
2877
+ }
2878
+ function isCertificate(value) {
2879
+ return value.includes("-----BEGIN CERTIFICATE-----");
2880
+ }
2881
+ async function importVerificationKey(key, algorithm) {
2882
+ if (isCryptoKey(key) || key instanceof Uint8Array) {
2883
+ return key;
2884
+ }
2885
+ if (key instanceof ArrayBuffer) {
2886
+ return new Uint8Array(key);
2887
+ }
2888
+ if (typeof key === "string") {
2889
+ if (algorithm.startsWith("HS")) {
2890
+ return new TextEncoder().encode(key);
2891
+ }
2892
+ if (!isPem(key)) {
2893
+ throw new Error("Expected a PEM-encoded public key or certificate string for Agent Card verification");
2894
+ }
2895
+ if (isCertificate(key)) {
2896
+ return jose.importX509(key, algorithm);
2897
+ }
2898
+ return jose.importSPKI(key, algorithm);
2899
+ }
2900
+ return jose.importJWK(key, algorithm);
2901
+ }
2902
+ async function verifyAgentCardSignatureIfPresent(agentCard, options) {
2903
+ const signatures = agentCard.signatures ?? [];
2904
+ if (signatures.length === 0) {
2905
+ return agentCard;
2906
+ }
2907
+ const canonicalPayload = canonicalize__default.default(stripAgentCardSignatures(agentCard));
2908
+ if (!canonicalPayload) {
2909
+ throw new MastraClientError(200, "OK", "Failed to canonicalize A2A Agent Card for signature verification");
2910
+ }
2911
+ const allowedAlgorithms = options.algorithms ?? [...DEFAULT_AGENT_CARD_SIGNATURE_ALGORITHMS];
2912
+ const encodedPayload = jose.base64url.encode(canonicalPayload);
2913
+ const verificationErrors = [];
2914
+ for (const [index, signature] of signatures.entries()) {
2915
+ try {
2916
+ const compactJws = `${signature.protected}.${encodedPayload}.${signature.signature}`;
2917
+ const protectedHeader = jose.decodeProtectedHeader(compactJws);
2918
+ if (typeof protectedHeader.alg !== "string") {
2919
+ throw new Error('Agent Card signature is missing a protected "alg" header');
2920
+ }
2921
+ if (!allowedAlgorithms.includes(protectedHeader.alg)) {
2922
+ throw new Error(`Agent Card signature algorithm "${protectedHeader.alg}" is not allowed`);
2923
+ }
2924
+ const verificationKey = await options.keyProvider({
2925
+ agentCard,
2926
+ signature,
2927
+ protectedHeader,
2928
+ alg: protectedHeader.alg,
2929
+ kid: typeof protectedHeader.kid === "string" ? protectedHeader.kid : void 0,
2930
+ jku: typeof protectedHeader.jku === "string" ? protectedHeader.jku : void 0,
2931
+ index
2932
+ });
2933
+ if (!verificationKey) {
2934
+ throw new Error("No verification key was provided for Agent Card signature verification");
2935
+ }
2936
+ const importedKey = await importVerificationKey(verificationKey, protectedHeader.alg);
2937
+ await jose.compactVerify(compactJws, importedKey, {
2938
+ algorithms: allowedAlgorithms
2939
+ });
2940
+ return agentCard;
2941
+ } catch (error) {
2942
+ verificationErrors.push(error instanceof Error ? error.message : "Unknown verification failure");
2943
+ }
2944
+ }
2945
+ throw new MastraClientError(
2946
+ 200,
2947
+ "OK",
2948
+ `A2A Agent Card signature verification failed: ${verificationErrors.join("; ")}`
2949
+ );
2950
+ }
2778
2951
 
2779
2952
  // src/resources/a2a.ts
2780
2953
  function createA2AJsonRpcError(response) {
@@ -2817,16 +2990,21 @@ var A2A = class extends BaseResource {
2817
2990
  agentId;
2818
2991
  /**
2819
2992
  * Get the agent card with metadata about the agent.
2993
+ * @param options - Optional Agent Card verification settings
2820
2994
  * @returns Promise containing the agent card information
2821
2995
  */
2822
- async getAgentCard() {
2823
- return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2996
+ async getAgentCard(options) {
2997
+ const agentCard = await this.request(`/.well-known/${this.agentId}/agent-card.json`);
2998
+ if (!options?.verifySignature) {
2999
+ return agentCard;
3000
+ }
3001
+ return verifyAgentCardSignatureIfPresent(agentCard, options.verifySignature);
2824
3002
  }
2825
3003
  /**
2826
3004
  * @deprecated Use getAgentCard() instead.
2827
3005
  */
2828
- async getCard() {
2829
- return this.getAgentCard();
3006
+ async getCard(options) {
3007
+ return this.getAgentCard(options);
2830
3008
  }
2831
3009
  /**
2832
3010
  * Get the authenticated extended agent card.
@@ -3839,8 +4017,14 @@ var StoredAgent = class extends BaseResource {
3839
4017
  const queryParams = new URLSearchParams();
3840
4018
  if (params?.page !== void 0) queryParams.set("page", String(params.page));
3841
4019
  if (params?.perPage !== void 0) queryParams.set("perPage", String(params.perPage));
3842
- if (params?.orderBy) queryParams.set("orderBy", params.orderBy);
3843
- if (params?.sortDirection) queryParams.set("sortDirection", params.sortDirection);
4020
+ if (params?.orderBy) {
4021
+ if (params.orderBy.field) {
4022
+ queryParams.set("orderBy[field]", params.orderBy.field);
4023
+ }
4024
+ if (params.orderBy.direction) {
4025
+ queryParams.set("orderBy[direction]", params.orderBy.direction);
4026
+ }
4027
+ }
3844
4028
  const queryString = queryParams.toString();
3845
4029
  const contextString = requestContextQueryString(requestContext);
3846
4030
  return this.request(
@@ -3993,8 +4177,14 @@ var StoredPromptBlock = class extends BaseResource {
3993
4177
  const queryParams = new URLSearchParams();
3994
4178
  if (params?.page !== void 0) queryParams.set("page", String(params.page));
3995
4179
  if (params?.perPage !== void 0) queryParams.set("perPage", String(params.perPage));
3996
- if (params?.orderBy) queryParams.set("orderBy", params.orderBy);
3997
- if (params?.sortDirection) queryParams.set("sortDirection", params.sortDirection);
4180
+ if (params?.orderBy) {
4181
+ if (params.orderBy.field) {
4182
+ queryParams.set("orderBy[field]", params.orderBy.field);
4183
+ }
4184
+ if (params.orderBy.direction) {
4185
+ queryParams.set("orderBy[direction]", params.orderBy.direction);
4186
+ }
4187
+ }
3998
4188
  const queryString = queryParams.toString();
3999
4189
  const contextString = requestContextQueryString(requestContext, queryString ? "&" : "?");
4000
4190
  return this.request(
@@ -4195,8 +4385,14 @@ var StoredScorer = class extends BaseResource {
4195
4385
  const queryParams = new URLSearchParams();
4196
4386
  if (params?.page !== void 0) queryParams.set("page", String(params.page));
4197
4387
  if (params?.perPage !== void 0) queryParams.set("perPage", String(params.perPage));
4198
- if (params?.orderBy) queryParams.set("orderBy", params.orderBy);
4199
- if (params?.sortDirection) queryParams.set("sortDirection", params.sortDirection);
4388
+ if (params?.orderBy) {
4389
+ if (params.orderBy.field) {
4390
+ queryParams.set("orderBy[field]", params.orderBy.field);
4391
+ }
4392
+ if (params.orderBy.direction) {
4393
+ queryParams.set("orderBy[direction]", params.orderBy.direction);
4394
+ }
4395
+ }
4200
4396
  const queryString = queryParams.toString();
4201
4397
  const contextString = requestContextQueryString(requestContext);
4202
4398
  return this.request(
@@ -4872,8 +5068,14 @@ var MastraClient = class extends BaseResource {
4872
5068
  if (params.agentId) queryParams.set("agentId", params.agentId);
4873
5069
  if (params.page !== void 0) queryParams.set("page", params.page.toString());
4874
5070
  if (params.perPage !== void 0) queryParams.set("perPage", params.perPage.toString());
4875
- if (params.orderBy) queryParams.set("orderBy", params.orderBy);
4876
- if (params.sortDirection) queryParams.set("sortDirection", params.sortDirection);
5071
+ if (params.orderBy) {
5072
+ if (params.orderBy.field) {
5073
+ queryParams.set("orderBy[field]", params.orderBy.field);
5074
+ }
5075
+ if (params.orderBy.direction) {
5076
+ queryParams.set("orderBy[direction]", params.orderBy.direction);
5077
+ }
5078
+ }
4877
5079
  const queryString = queryParams.toString();
4878
5080
  const response = await this.request(
4879
5081
  `/memory/threads${queryString ? `?${queryString}` : ""}${requestContextQueryString(params.requestContext, queryString ? "&" : "?")}`
@@ -4938,13 +5140,13 @@ var MastraClient = class extends BaseResource {
4938
5140
  }
4939
5141
  return this.request(url);
4940
5142
  }
4941
- deleteThread(threadId, opts = {}) {
4942
- let url = "";
4943
- if (opts.agentId) {
4944
- url = `/memory/threads/${threadId}?agentId=${opts.agentId}${requestContextQueryString(opts.requestContext, "&")}`;
4945
- } else if (opts.networkId) {
4946
- url = `/memory/network/threads/${threadId}?networkId=${opts.networkId}${requestContextQueryString(opts.requestContext, "&")}`;
5143
+ deleteThread(threadId, opts) {
5144
+ if (!opts || !!opts.agentId === !!opts.networkId) {
5145
+ throw new Error(
5146
+ "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."
5147
+ );
4947
5148
  }
5149
+ const url = opts.agentId ? `/memory/threads/${threadId}?agentId=${opts.agentId}${requestContextQueryString(opts.requestContext, "&")}` : `/memory/network/threads/${threadId}?networkId=${opts.networkId}${requestContextQueryString(opts.requestContext, "&")}`;
4948
5150
  return this.request(url, { method: "DELETE" });
4949
5151
  }
4950
5152
  /**
@@ -6214,6 +6416,8 @@ var MastraClient = class extends BaseResource {
6214
6416
  if (params.runId) searchParams.set("runId", params.runId);
6215
6417
  if (params.threadId) searchParams.set("threadId", params.threadId);
6216
6418
  if (params.resourceId) searchParams.set("resourceId", params.resourceId);
6419
+ if (params.toolName) searchParams.set("toolName", params.toolName);
6420
+ if (params.toolCallId) searchParams.set("toolCallId", params.toolCallId);
6217
6421
  if (params.fromDate) searchParams.set("fromDate", params.fromDate.toISOString());
6218
6422
  if (params.toDate) searchParams.set("toDate", params.toDate.toISOString());
6219
6423
  if (params.dateFilterBy) searchParams.set("dateFilterBy", params.dateFilterBy);