@mastra/client-js 1.56.0-alpha.8 → 1.56.0

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
@@ -16,7 +16,7 @@ var __copyProps = (to, from, except, desc) => {
16
16
  }
17
17
  return to;
18
18
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
@@ -83,15 +83,16 @@ function attributesToOtlp(attrs) {
83
83
  key,
84
84
  value: { boolValue: raw }
85
85
  });
86
- else if (typeof raw === "number") if (Number.isInteger(raw)) out.push({
87
- key,
88
- value: { intValue: raw }
89
- });
90
- else out.push({
91
- key,
92
- value: { doubleValue: raw }
93
- });
94
- else try {
86
+ else if (typeof raw === "number") {
87
+ if (Number.isInteger(raw)) out.push({
88
+ key,
89
+ value: { intValue: raw }
90
+ });
91
+ else out.push({
92
+ key,
93
+ value: { doubleValue: raw }
94
+ });
95
+ } else try {
95
96
  out.push({
96
97
  key,
97
98
  value: { stringValue: JSON.stringify(raw) }
@@ -686,7 +687,6 @@ function fixJson(input) {
686
687
  stack.pop();
687
688
  stack.push(swapState);
688
689
  stack.push("INSIDE_ARRAY_START");
689
- break;
690
690
  }
691
691
  }
692
692
  function processAfterObjectValue(char, i) {
@@ -698,7 +698,6 @@ function fixJson(input) {
698
698
  case "}":
699
699
  lastValidIndex = i;
700
700
  stack.pop();
701
- break;
702
701
  }
703
702
  }
704
703
  function processAfterArrayValue(char, i) {
@@ -710,7 +709,6 @@ function fixJson(input) {
710
709
  case "]":
711
710
  lastValidIndex = i;
712
711
  stack.pop();
713
- break;
714
712
  }
715
713
  }
716
714
  for (let i = 0; i < input.length; i++) {
@@ -728,7 +726,6 @@ function fixJson(input) {
728
726
  case "}":
729
727
  lastValidIndex = i;
730
728
  stack.pop();
731
- break;
732
729
  }
733
730
  break;
734
731
  case "INSIDE_OBJECT_AFTER_COMMA":
@@ -736,7 +733,6 @@ function fixJson(input) {
736
733
  case "\"":
737
734
  stack.pop();
738
735
  stack.push("INSIDE_OBJECT_KEY");
739
- break;
740
736
  }
741
737
  break;
742
738
  case "INSIDE_OBJECT_KEY":
@@ -744,7 +740,6 @@ function fixJson(input) {
744
740
  case "\"":
745
741
  stack.pop();
746
742
  stack.push("INSIDE_OBJECT_AFTER_KEY");
747
- break;
748
743
  }
749
744
  break;
750
745
  case "INSIDE_OBJECT_AFTER_KEY":
@@ -752,7 +747,6 @@ function fixJson(input) {
752
747
  case ":":
753
748
  stack.pop();
754
749
  stack.push("INSIDE_OBJECT_BEFORE_VALUE");
755
- break;
756
750
  }
757
751
  break;
758
752
  case "INSIDE_OBJECT_BEFORE_VALUE":
@@ -782,7 +776,6 @@ function fixJson(input) {
782
776
  default:
783
777
  lastValidIndex = i;
784
778
  processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
785
- break;
786
779
  }
787
780
  break;
788
781
  case "INSIDE_ARRAY_AFTER_VALUE":
@@ -795,9 +788,7 @@ function fixJson(input) {
795
788
  lastValidIndex = i;
796
789
  stack.pop();
797
790
  break;
798
- default:
799
- lastValidIndex = i;
800
- break;
791
+ default: lastValidIndex = i;
801
792
  }
802
793
  break;
803
794
  case "INSIDE_ARRAY_AFTER_COMMA":
@@ -838,9 +829,7 @@ function fixJson(input) {
838
829
  stack.pop();
839
830
  if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
840
831
  break;
841
- default:
842
- stack.pop();
843
- break;
832
+ default: stack.pop();
844
833
  }
845
834
  break;
846
835
  case "INSIDE_LITERAL": {
@@ -1249,8 +1238,16 @@ var BaseResource = class {
1249
1238
  };
1250
1239
  //#endregion
1251
1240
  //#region src/resources/agent.ts
1252
- const SIGNAL_RUNTIME_OPTIONS_TTL_MS = 300 * 1e3;
1241
+ const SIGNAL_RUNTIME_OPTIONS_TTL_MS = 3e5;
1253
1242
  const signalRuntimeOptionsByRunId = /* @__PURE__ */ new Map();
1243
+ /**
1244
+ * Client tools a resume request can execute, keyed by run. The stream that stayed open from
1245
+ * before the suspension must not run those tools again, but it must run any resumed client tool
1246
+ * the resume request cannot execute (a server-side approve sends no client tools). Held until the
1247
+ * last stream of the run closes, which is after the resume request returns.
1248
+ */
1249
+ const resumingClientToolNamesByRunKey = /* @__PURE__ */ new Map();
1250
+ const openStreamCountByRunKey = /* @__PURE__ */ new Map();
1254
1251
  const latestSignalRuntimeOptionsByThread = /* @__PURE__ */ new Map();
1255
1252
  const createSignalRuntimeOptionsEntry = (store, key, streamOptions) => {
1256
1253
  const timeout = setTimeout(() => store.delete(key), SIGNAL_RUNTIME_OPTIONS_TTL_MS);
@@ -1443,6 +1440,49 @@ var Agent = class extends BaseResource {
1443
1440
  getSignalRuntimeRunKey(runId) {
1444
1441
  return `${this.options.baseUrl}|${this.apiPrefix}|${this.agentId}|${runId}`;
1445
1442
  }
1443
+ /**
1444
+ * Records that `runId` is being resumed by a request that can execute these client tools, so the
1445
+ * stream that is still open from before the suspension skips them. Released when the last stream
1446
+ * of the run closes, which is after this request returns.
1447
+ */
1448
+ holdResumingClientTools(runId, clientTools) {
1449
+ const names = Object.entries(clientTools ?? {}).filter(([, tool]) => typeof tool.execute === "function").map(([name]) => name);
1450
+ if (names.length === 0) return () => {};
1451
+ const key = this.getSignalRuntimeRunKey(runId);
1452
+ const held = resumingClientToolNamesByRunKey.get(key) ?? /* @__PURE__ */ new Map();
1453
+ for (const name of names) held.set(name, (held.get(name) ?? 0) + 1);
1454
+ resumingClientToolNamesByRunKey.set(key, held);
1455
+ let released = false;
1456
+ return ({ force = false } = {}) => {
1457
+ if (released || !force && openStreamCountByRunKey.has(key)) return;
1458
+ released = true;
1459
+ const current = resumingClientToolNamesByRunKey.get(key);
1460
+ if (!current) return;
1461
+ for (const name of names) {
1462
+ const count = (current.get(name) ?? 1) - 1;
1463
+ if (count > 0) current.set(name, count);
1464
+ else current.delete(name);
1465
+ }
1466
+ if (current.size === 0) resumingClientToolNamesByRunKey.delete(key);
1467
+ };
1468
+ }
1469
+ /** Drops the held tool names when the last stream of the run closes. */
1470
+ trackOpenStream(runId) {
1471
+ const key = this.getSignalRuntimeRunKey(runId);
1472
+ openStreamCountByRunKey.set(key, (openStreamCountByRunKey.get(key) ?? 0) + 1);
1473
+ let released = false;
1474
+ return () => {
1475
+ if (released) return;
1476
+ released = true;
1477
+ const remaining = (openStreamCountByRunKey.get(key) ?? 1) - 1;
1478
+ if (remaining > 0) {
1479
+ openStreamCountByRunKey.set(key, remaining);
1480
+ return;
1481
+ }
1482
+ openStreamCountByRunKey.delete(key);
1483
+ resumingClientToolNamesByRunKey.delete(key);
1484
+ };
1485
+ }
1446
1486
  getSignalRuntimeThreadKey({ resourceId, threadId }) {
1447
1487
  if (!threadId) return void 0;
1448
1488
  return `${this.options.baseUrl}|${this.apiPrefix}|${this.agentId}|${resourceId ?? ""}|${threadId}`;
@@ -2580,7 +2620,6 @@ var Agent = class extends BaseResource {
2580
2620
  case "finish":
2581
2621
  finishReason = chunk.payload?.stepResult?.reason ?? finishReason;
2582
2622
  if (chunk.payload?.usage != null) usage = chunk.payload.usage;
2583
- break;
2584
2623
  }
2585
2624
  }
2586
2625
  });
@@ -2645,6 +2684,9 @@ var Agent = class extends BaseResource {
2645
2684
  let messages = [];
2646
2685
  let streamRunId = processedParams.runId;
2647
2686
  let finishedHistory;
2687
+ let suspended = false;
2688
+ const resumedToolCallIds = /* @__PURE__ */ new Set();
2689
+ const releaseOpenStream = streamRunId ? this.trackOpenStream(streamRunId) : () => {};
2648
2690
  const [streamForController, streamForProcessing] = response.body.tee();
2649
2691
  const decoder = new TextDecoder();
2650
2692
  let pendingText = "";
@@ -2713,6 +2755,9 @@ var Agent = class extends BaseResource {
2713
2755
  });
2714
2756
  }
2715
2757
  const executableToolCalls = [...toolInvocationsById.values()].filter((toolCall) => {
2758
+ if (resumedToolCallIds.has(toolCall.toolCallId)) {
2759
+ if ((streamRunId ? resumingClientToolNamesByRunKey.get(this.getSignalRuntimeRunKey(streamRunId)) : void 0)?.has(toolCall.toolName)) return false;
2760
+ }
2716
2761
  const clientTool = processedParams.clientTools?.[toolCall.toolName];
2717
2762
  return Boolean(clientTool?.execute);
2718
2763
  });
@@ -2839,6 +2884,12 @@ var Agent = class extends BaseResource {
2839
2884
  },
2840
2885
  onStreamChunk: (chunk) => {
2841
2886
  if (!streamRunId && typeof chunk.runId === "string") streamRunId = chunk.runId;
2887
+ if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") suspended = true;
2888
+ else if (suspended && chunk.type === "tool-call" && typeof chunk.payload?.toolCallId === "string") {
2889
+ const toolName = chunk.payload.toolName;
2890
+ const held = streamRunId ? resumingClientToolNamesByRunKey.get(this.getSignalRuntimeRunKey(streamRunId)) : void 0;
2891
+ if (typeof toolName === "string" && held?.has(toolName)) resumedToolCallIds.add(chunk.payload.toolCallId);
2892
+ }
2842
2893
  },
2843
2894
  lastMessage: void 0
2844
2895
  }).catch(async (error) => {
@@ -2849,6 +2900,7 @@ var Agent = class extends BaseResource {
2849
2900
  safeClose();
2850
2901
  }).finally(() => {
2851
2902
  signal?.removeEventListener("abort", onAbort);
2903
+ releaseOpenStream();
2852
2904
  });
2853
2905
  } catch (error) {
2854
2906
  if (!isAbortError(error)) console.error("Error processing stream response:", error);
@@ -3016,13 +3068,18 @@ var Agent = class extends BaseResource {
3016
3068
  }
3017
3069
  async approveToolCall(params) {
3018
3070
  const { requestContext, ...rest } = params;
3071
+ const executableClientTools = params.clientToolsResolver?.() ?? params.clientTools;
3072
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
3019
3073
  const processedParams = {
3020
3074
  ...rest,
3021
3075
  requestContext: parseClientRequestContext(requestContext),
3022
- clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
3076
+ clientTools: processClientTools(executableClientTools)
3023
3077
  };
3024
3078
  const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
3025
- const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call", signal);
3079
+ const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call", signal).catch((error) => {
3080
+ releaseHold({ force: true });
3081
+ throw error;
3082
+ });
3026
3083
  const streamResponse = new Response(readable, {
3027
3084
  status: response.status,
3028
3085
  statusText: response.statusText,
@@ -3048,13 +3105,18 @@ var Agent = class extends BaseResource {
3048
3105
  }
3049
3106
  async declineToolCall(params) {
3050
3107
  const { requestContext, ...rest } = params;
3108
+ const executableClientTools = params.clientToolsResolver?.() ?? params.clientTools;
3109
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
3051
3110
  const processedParams = {
3052
3111
  ...rest,
3053
3112
  requestContext: parseClientRequestContext(requestContext),
3054
- clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
3113
+ clientTools: processClientTools(executableClientTools)
3055
3114
  };
3056
3115
  const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
3057
- const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call", signal);
3116
+ const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call", signal).catch((error) => {
3117
+ releaseHold({ force: true });
3118
+ throw error;
3119
+ });
3058
3120
  const streamResponse = new Response(readable, {
3059
3121
  status: response.status,
3060
3122
  statusText: response.statusText,
@@ -3114,18 +3176,23 @@ var Agent = class extends BaseResource {
3114
3176
  * Used to continue execution after a suspension point (e.g., workflow suspend within an agent).
3115
3177
  */
3116
3178
  async resumeStream(resumeData, options) {
3179
+ const executableClientTools = options.clientToolsResolver?.() ?? options.clientTools;
3180
+ const releaseHold = this.holdResumingClientTools(options.runId, executableClientTools);
3117
3181
  const processedParams = {
3118
3182
  ...options,
3119
3183
  resumeData,
3120
3184
  requestContext: parseClientRequestContext(options.requestContext),
3121
- clientTools: processClientTools(options.clientToolsResolver?.() ?? options.clientTools),
3185
+ clientTools: processClientTools(executableClientTools),
3122
3186
  structuredOutput: options.structuredOutput ? {
3123
3187
  ...options.structuredOutput,
3124
3188
  schema: (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)((0, _mastra_schema_compat_schema.toStandardSchema)(options.structuredOutput.schema))
3125
3189
  } : void 0
3126
3190
  };
3127
3191
  const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
3128
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream", signal);
3192
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream", signal).catch((error) => {
3193
+ releaseHold({ force: true });
3194
+ throw error;
3195
+ });
3129
3196
  const streamResponse = new Response(readable, {
3130
3197
  status: response.status,
3131
3198
  statusText: response.statusText,
@@ -3178,18 +3245,23 @@ var Agent = class extends BaseResource {
3178
3245
  * Used to continue execution after a suspension point (e.g., workflow suspend within an agent).
3179
3246
  */
3180
3247
  async resumeStreamUntilIdle(resumeData, options) {
3248
+ const executableClientTools = options.clientToolsResolver?.() ?? options.clientTools;
3249
+ const releaseHold = this.holdResumingClientTools(options.runId, executableClientTools);
3181
3250
  const processedParams = {
3182
3251
  ...options,
3183
3252
  resumeData,
3184
3253
  requestContext: parseClientRequestContext(options.requestContext),
3185
- clientTools: processClientTools(options.clientToolsResolver?.() ?? options.clientTools),
3254
+ clientTools: processClientTools(executableClientTools),
3186
3255
  structuredOutput: options.structuredOutput ? {
3187
3256
  ...options.structuredOutput,
3188
3257
  schema: (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)((0, _mastra_schema_compat_schema.toStandardSchema)(options.structuredOutput.schema))
3189
3258
  } : void 0
3190
3259
  };
3191
3260
  const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
3192
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle", signal);
3261
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle", signal).catch((error) => {
3262
+ releaseHold({ force: true });
3263
+ throw error;
3264
+ });
3193
3265
  const streamResponse = new Response(readable, {
3194
3266
  status: response.status,
3195
3267
  statusText: response.statusText,
@@ -3209,20 +3281,32 @@ var Agent = class extends BaseResource {
3209
3281
  */
3210
3282
  async approveToolCallGenerate(params) {
3211
3283
  const { requestContext, clientTools, clientToolsResolver, memory, ...rest } = params;
3212
- const response = await this.request(`/agents/${this.agentId}/approve-tool-call-generate`, {
3213
- method: "POST",
3214
- body: {
3215
- ...rest,
3216
- requestContext: parseClientRequestContext(requestContext),
3217
- clientTools: processClientTools(clientToolsResolver?.() ?? clientTools)
3218
- }
3219
- });
3220
- return this.continueResumedGenerate(response, {
3221
- requestContext,
3222
- clientTools,
3223
- clientToolsResolver,
3224
- memory
3225
- });
3284
+ const executableClientTools = clientToolsResolver?.() ?? clientTools;
3285
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
3286
+ let response;
3287
+ try {
3288
+ response = await this.request(`/agents/${this.agentId}/approve-tool-call-generate`, {
3289
+ method: "POST",
3290
+ body: {
3291
+ ...rest,
3292
+ requestContext: parseClientRequestContext(requestContext),
3293
+ clientTools: processClientTools(executableClientTools)
3294
+ }
3295
+ });
3296
+ } catch (error) {
3297
+ releaseHold({ force: true });
3298
+ throw error;
3299
+ }
3300
+ try {
3301
+ return await this.continueResumedGenerate(response, {
3302
+ requestContext,
3303
+ clientTools: executableClientTools,
3304
+ clientToolsResolver,
3305
+ memory
3306
+ });
3307
+ } finally {
3308
+ releaseHold();
3309
+ }
3226
3310
  }
3227
3311
  /**
3228
3312
  * Declines a pending tool call and returns the complete response (non-streaming).
@@ -3230,20 +3314,32 @@ var Agent = class extends BaseResource {
3230
3314
  */
3231
3315
  async declineToolCallGenerate(params) {
3232
3316
  const { requestContext, clientTools, clientToolsResolver, memory, ...rest } = params;
3233
- const response = await this.request(`/agents/${this.agentId}/decline-tool-call-generate`, {
3234
- method: "POST",
3235
- body: {
3236
- ...rest,
3237
- requestContext: parseClientRequestContext(requestContext),
3238
- clientTools: processClientTools(clientToolsResolver?.() ?? clientTools)
3239
- }
3240
- });
3241
- return this.continueResumedGenerate(response, {
3242
- requestContext,
3243
- clientTools,
3244
- clientToolsResolver,
3245
- memory
3246
- });
3317
+ const executableClientTools = clientToolsResolver?.() ?? clientTools;
3318
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
3319
+ let response;
3320
+ try {
3321
+ response = await this.request(`/agents/${this.agentId}/decline-tool-call-generate`, {
3322
+ method: "POST",
3323
+ body: {
3324
+ ...rest,
3325
+ requestContext: parseClientRequestContext(requestContext),
3326
+ clientTools: processClientTools(executableClientTools)
3327
+ }
3328
+ });
3329
+ } catch (error) {
3330
+ releaseHold({ force: true });
3331
+ throw error;
3332
+ }
3333
+ try {
3334
+ return await this.continueResumedGenerate(response, {
3335
+ requestContext,
3336
+ clientTools: executableClientTools,
3337
+ clientToolsResolver,
3338
+ memory
3339
+ });
3340
+ } finally {
3341
+ releaseHold();
3342
+ }
3247
3343
  }
3248
3344
  /**
3249
3345
  * Runs executable client tools the model called after an approval decision and continues on
@@ -4468,7 +4564,8 @@ async function verifyAgentCardSignatureIfPresent(agentCard, options) {
4468
4564
  index
4469
4565
  });
4470
4566
  if (!verificationKey) throw new Error("No verification key was provided for Agent Card signature verification");
4471
- await (0, jose.compactVerify)(compactJws, await importVerificationKey(verificationKey, protectedHeader.alg), { algorithms: allowedAlgorithms });
4567
+ const importedKey = await importVerificationKey(verificationKey, protectedHeader.alg);
4568
+ await (0, jose.compactVerify)(compactJws, importedKey, { algorithms: allowedAlgorithms });
4472
4569
  return agentCard;
4473
4570
  } catch (error) {
4474
4571
  verificationErrors.push(error instanceof Error ? error.message : "Unknown verification failure");
@@ -6800,48 +6897,40 @@ function hydrateEventTimestamps(event) {
6800
6897
  return isKnownParsedEvent(event) ? hydrateKnownEvent(event) : event;
6801
6898
  }
6802
6899
  /**
6803
- * A session bound to a `resourceId` within one agent controller. Sessions are
6804
- * get-or-create on the server, so re-creating the same resourceId (and scope)
6805
- * resumes the existing conversation rather than forking it.
6806
- *
6807
- * Pass a `scope` to address an independent session over the same resourceId:
6808
- * two sessions with the same resourceId but different scopes have their own
6809
- * run loop, thread binding, and mode/model/state (e.g. one session per git
6810
- * worktree, with the worktree path as the scope). The scope travels on every
6811
- * request as a `sessionScope` query param.
6900
+ * A session addressed by its `sessionId` within one agent controller. Sessions
6901
+ * are get-or-create on the server, so re-creating the same sessionId resumes
6902
+ * the existing conversation rather than forking it. Many sessions can work on
6903
+ * one `resourceId` (whose threads and memory they use); each has its own run
6904
+ * loop, thread binding, and mode/model/state.
6812
6905
  */
6813
6906
  var AgentControllerSession = class extends BaseResource {
6814
6907
  controllerId;
6815
- resourceId;
6816
- scope;
6817
- constructor(options, controllerId, resourceId, scope) {
6908
+ sessionId;
6909
+ constructor(options, controllerId, sessionId) {
6818
6910
  super(options);
6819
6911
  this.controllerId = controllerId;
6820
- this.resourceId = resourceId;
6821
- this.scope = scope;
6912
+ this.sessionId = sessionId;
6822
6913
  }
6823
6914
  base() {
6824
- return `/agent-controller/${encodeURIComponent(this.controllerId)}/sessions/${encodeURIComponent(this.resourceId)}`;
6825
- }
6826
- /** Append this session's scope (if any) as a `sessionScope` query param. */
6827
- url(path) {
6828
- if (this.scope === void 0) return path;
6829
- return `${path}${path.includes("?") ? "&" : "?"}sessionScope=${encodeURIComponent(this.scope)}`;
6915
+ return `/agent-controller/${encodeURIComponent(this.controllerId)}/sessions/${encodeURIComponent(this.sessionId)}`;
6830
6916
  }
6831
6917
  /**
6832
- * Create or resume this session. Pass `tags` to scope initial thread
6833
- * selection — a thread is a resume candidate only when its metadata matches
6834
- * every tag. Pass `threadId` to bind the session to one exact thread,
6835
- * creating it with that id when it does not exist.
6918
+ * Create or resume this session. `resourceId` names whose threads and memory
6919
+ * the session works on. Without it the server resumes the session on the
6920
+ * resource it already has (the live session's, or the resource of the thread
6921
+ * with the session's id), falling back to the sessionId. Pass `tags` to scope
6922
+ * initial thread selection — a thread is a resume candidate only when its
6923
+ * metadata matches every tag. Pass `threadId` to bind the session to one
6924
+ * exact thread, creating it with that id when it does not exist.
6836
6925
  */
6837
6926
  create(options) {
6838
6927
  return this.request(`/agent-controller/${encodeURIComponent(this.controllerId)}/sessions`, {
6839
6928
  method: "POST",
6840
6929
  body: {
6841
- resourceId: this.resourceId,
6930
+ resourceId: options?.resourceId,
6931
+ sessionId: this.sessionId,
6842
6932
  tags: options?.tags,
6843
- threadId: options?.threadId,
6844
- sessionScope: this.scope
6933
+ threadId: options?.threadId
6845
6934
  }
6846
6935
  });
6847
6936
  }
@@ -6897,7 +6986,7 @@ var AgentControllerSession = class extends BaseResource {
6897
6986
  const abort = new AbortController();
6898
6987
  currentAbort = abort;
6899
6988
  let openTimer;
6900
- const request = this.request(this.url(`${this.base()}/stream`), {
6989
+ const request = this.request(`${this.base()}/stream`, {
6901
6990
  stream: true,
6902
6991
  signal: abort.signal
6903
6992
  });
@@ -7107,7 +7196,7 @@ var AgentControllerSession = class extends BaseResource {
7107
7196
  files: void 0
7108
7197
  } : message;
7109
7198
  const requestContext = parseClientRequestContext(options?.requestContext);
7110
- await this.request(this.url(`${this.base()}/messages`), {
7199
+ await this.request(`${this.base()}/messages`, {
7111
7200
  method: "POST",
7112
7201
  body: {
7113
7202
  message: content,
@@ -7118,7 +7207,7 @@ var AgentControllerSession = class extends BaseResource {
7118
7207
  }
7119
7208
  /** Abort the in-flight run for this session. */
7120
7209
  async abort() {
7121
- await this.request(this.url(`${this.base()}/abort`), { method: "POST" });
7210
+ await this.request(`${this.base()}/abort`, { method: "POST" });
7122
7211
  }
7123
7212
  /**
7124
7213
  * Approve or decline a pending tool call (`tool_approval_required`). Resolves
@@ -7126,7 +7215,7 @@ var AgentControllerSession = class extends BaseResource {
7126
7215
  */
7127
7216
  async approveTool(toolCallId, approved, options) {
7128
7217
  const requestContext = parseClientRequestContext(options?.requestContext);
7129
- return this.request(this.url(`${this.base()}/tool-approval`), {
7218
+ return this.request(`${this.base()}/tool-approval`, {
7130
7219
  method: "POST",
7131
7220
  retries: 0,
7132
7221
  body: {
@@ -7144,7 +7233,7 @@ var AgentControllerSession = class extends BaseResource {
7144
7233
  */
7145
7234
  async respondToToolSuspension(toolCallId, resumeData, options) {
7146
7235
  const requestContext = parseClientRequestContext(options?.requestContext);
7147
- return this.request(this.url(`${this.base()}/tool-suspension`), {
7236
+ return this.request(`${this.base()}/tool-suspension`, {
7148
7237
  method: "POST",
7149
7238
  retries: 0,
7150
7239
  body: {
@@ -7164,7 +7253,7 @@ var AgentControllerSession = class extends BaseResource {
7164
7253
  files: void 0
7165
7254
  } : message;
7166
7255
  const requestContext = parseClientRequestContext(options?.requestContext);
7167
- await this.request(this.url(`${this.base()}/steer`), {
7256
+ await this.request(`${this.base()}/steer`, {
7168
7257
  method: "POST",
7169
7258
  body: {
7170
7259
  message: content,
@@ -7176,18 +7265,18 @@ var AgentControllerSession = class extends BaseResource {
7176
7265
  /** Get the current mode, model, and thread (for initial UI hydration). */
7177
7266
  state(options) {
7178
7267
  const path = options?.threadId ? `${this.base()}?threadId=${encodeURIComponent(options.threadId)}` : this.base();
7179
- return this.request(this.url(path));
7268
+ return this.request(path);
7180
7269
  }
7181
7270
  /** Merge key-value pairs into the session state. Existing keys not in the payload are preserved. */
7182
7271
  async setState(updates) {
7183
- await this.request(this.url(`${this.base()}/state`), {
7272
+ await this.request(`${this.base()}/state`, {
7184
7273
  method: "PUT",
7185
7274
  body: { state: updates }
7186
7275
  });
7187
7276
  }
7188
7277
  /** Switch the active mode (e.g. `build`, `plan`). */
7189
7278
  async switchMode(modeId) {
7190
- await this.request(this.url(`${this.base()}/mode`), {
7279
+ await this.request(`${this.base()}/mode`, {
7191
7280
  method: "POST",
7192
7281
  body: { modeId }
7193
7282
  });
@@ -7197,7 +7286,7 @@ var AgentControllerSession = class extends BaseResource {
7197
7286
  * `thinkingLevel` is provided it is applied and persisted with the model.
7198
7287
  */
7199
7288
  async switchModel(modelId, { thinkingLevel } = {}) {
7200
- await this.request(this.url(`${this.base()}/model`), {
7289
+ await this.request(`${this.base()}/model`, {
7201
7290
  method: "POST",
7202
7291
  body: thinkingLevel !== void 0 ? {
7203
7292
  modelId,
@@ -7218,36 +7307,36 @@ var AgentControllerSession = class extends BaseResource {
7218
7307
  if (opts.limit != null) params.set("limit", String(opts.limit));
7219
7308
  if (opts.tags && Object.keys(opts.tags).length > 0) params.set("tags", JSON.stringify(opts.tags));
7220
7309
  const query = params.toString() ? `?${params.toString()}` : "";
7221
- return (await this.request(this.url(`${this.base()}/threads${query}`))).threads;
7310
+ return (await this.request(`${this.base()}/threads${query}`)).threads;
7222
7311
  }
7223
7312
  /** Switch the session to an existing thread (rebinds stream + state). */
7224
7313
  async switchThread(threadId) {
7225
- await this.request(this.url(`${this.base()}/thread`), {
7314
+ await this.request(`${this.base()}/thread`, {
7226
7315
  method: "POST",
7227
7316
  body: { threadId }
7228
7317
  });
7229
7318
  }
7230
7319
  /** Create a new thread (unbinds previous, binds the new one). */
7231
7320
  async createThread(title) {
7232
- return this.request(this.url(`${this.base()}/threads`), {
7321
+ return this.request(`${this.base()}/threads`, {
7233
7322
  method: "POST",
7234
7323
  body: { title }
7235
7324
  });
7236
7325
  }
7237
7326
  /** Delete a thread. If it's the active thread the session unbinds. */
7238
7327
  async deleteThread(threadId) {
7239
- await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}`), { method: "DELETE" });
7328
+ await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}`, { method: "DELETE" });
7240
7329
  }
7241
7330
  /** Rename a thread. */
7242
7331
  async renameThread(threadId, title) {
7243
- await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}`), {
7332
+ await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}`, {
7244
7333
  method: "PUT",
7245
7334
  body: { title }
7246
7335
  });
7247
7336
  }
7248
7337
  /** Clone a thread (and its messages). The session binds to the clone. */
7249
7338
  async cloneThread(options) {
7250
- return this.request(this.url(`${this.base()}/threads/clone`), {
7339
+ return this.request(`${this.base()}/threads/clone`, {
7251
7340
  method: "POST",
7252
7341
  body: options ?? {}
7253
7342
  });
@@ -7268,7 +7357,7 @@ var AgentControllerSession = class extends BaseResource {
7268
7357
  if (include) queryParams.set("include", JSON.stringify(include));
7269
7358
  }
7270
7359
  const query = queryParams.toString();
7271
- const body = await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}/messages${query ? `?${query}` : ""}`));
7360
+ const body = await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}/messages${query ? `?${query}` : ""}`);
7272
7361
  const messages = body.messages.map(hydrateMessage);
7273
7362
  if (legacy) return messages;
7274
7363
  return {
@@ -7287,7 +7376,7 @@ var AgentControllerSession = class extends BaseResource {
7287
7376
  files: void 0
7288
7377
  } : message;
7289
7378
  const requestContext = parseClientRequestContext(options?.requestContext);
7290
- await this.request(this.url(`${this.base()}/follow-up`), {
7379
+ await this.request(`${this.base()}/follow-up`, {
7291
7380
  method: "POST",
7292
7381
  body: {
7293
7382
  message: content,
@@ -7298,26 +7387,26 @@ var AgentControllerSession = class extends BaseResource {
7298
7387
  }
7299
7388
  /** Get the observational memory record for this session's thread. */
7300
7389
  async getOMRecord() {
7301
- return (await this.request(this.url(`${this.base()}/om`))).record;
7390
+ return (await this.request(`${this.base()}/om`)).record;
7302
7391
  }
7303
7392
  /** Change the session's resource identity. */
7304
7393
  async setResourceId(newResourceId) {
7305
- await this.request(this.url(`${this.base()}/resource`), {
7394
+ await this.request(`${this.base()}/resource`, {
7306
7395
  method: "POST",
7307
7396
  body: { newResourceId }
7308
7397
  });
7309
7398
  }
7310
7399
  /** Get known resource IDs for this session. */
7311
7400
  async getResourceIds() {
7312
- return (await this.request(this.url(`${this.base()}/resources`))).resourceIds;
7401
+ return (await this.request(`${this.base()}/resources`)).resourceIds;
7313
7402
  }
7314
7403
  /** Get the current goal for this session's thread. */
7315
7404
  async getGoal() {
7316
- return (await this.request(this.url(`${this.base()}/goal`))).goal;
7405
+ return (await this.request(`${this.base()}/goal`)).goal;
7317
7406
  }
7318
7407
  /** Set a new goal objective. The agent's in-loop judge evaluates progress after each turn. */
7319
7408
  async setGoal(objective, options) {
7320
- return (await this.request(this.url(`${this.base()}/goal`), {
7409
+ return (await this.request(`${this.base()}/goal`, {
7321
7410
  method: "POST",
7322
7411
  body: {
7323
7412
  objective,
@@ -7327,22 +7416,22 @@ var AgentControllerSession = class extends BaseResource {
7327
7416
  }
7328
7417
  /** Update goal options (judge model, max runs, status). */
7329
7418
  async updateGoal(options) {
7330
- return (await this.request(this.url(`${this.base()}/goal`), {
7419
+ return (await this.request(`${this.base()}/goal`, {
7331
7420
  method: "PUT",
7332
7421
  body: options
7333
7422
  })).goal;
7334
7423
  }
7335
7424
  /** Clear the current goal. */
7336
7425
  async clearGoal() {
7337
- await this.request(this.url(`${this.base()}/goal`), { method: "DELETE" });
7426
+ await this.request(`${this.base()}/goal`, { method: "DELETE" });
7338
7427
  }
7339
7428
  /** Get the current permission rules (per-category and per-tool policies). */
7340
7429
  async getPermissions() {
7341
- return this.request(this.url(`${this.base()}/permissions`));
7430
+ return this.request(`${this.base()}/permissions`);
7342
7431
  }
7343
7432
  /** Set the approval policy for a tool category. */
7344
7433
  async setPermissionForCategory(category, policy) {
7345
- await this.request(this.url(`${this.base()}/permissions/category`), {
7434
+ await this.request(`${this.base()}/permissions/category`, {
7346
7435
  method: "PUT",
7347
7436
  body: {
7348
7437
  category,
@@ -7352,7 +7441,7 @@ var AgentControllerSession = class extends BaseResource {
7352
7441
  }
7353
7442
  /** Set the approval policy for a specific tool. */
7354
7443
  async setPermissionForTool(toolName, policy) {
7355
- await this.request(this.url(`${this.base()}/permissions/tool`), {
7444
+ await this.request(`${this.base()}/permissions/tool`, {
7356
7445
  method: "PUT",
7357
7446
  body: {
7358
7447
  toolName,
@@ -7366,7 +7455,7 @@ var AgentControllerSession = class extends BaseResource {
7366
7455
  * or is persisted for later.
7367
7456
  */
7368
7457
  async sendNotification(input) {
7369
- return this.request(this.url(`${this.base()}/notifications`), {
7458
+ return this.request(`${this.base()}/notifications`, {
7370
7459
  method: "POST",
7371
7460
  body: input
7372
7461
  });
@@ -7399,12 +7488,11 @@ var AgentController = class extends BaseResource {
7399
7488
  return this.request(`${this.basePath()}/workspace`);
7400
7489
  }
7401
7490
  /**
7402
- * Scope to a session bound to `resourceId` (e.g. a user or conversation id).
7403
- * Pass `scope` to address an independent session over the same resourceId
7404
- * (e.g. one session per git worktree, with the worktree path as the scope).
7491
+ * Address the session with this `sessionId`. Sessions created without an
7492
+ * explicit id are addressed by their `resourceId`.
7405
7493
  */
7406
- session(resourceId, scope) {
7407
- return new AgentControllerSession(this.options, this.controllerId, resourceId, scope);
7494
+ session(sessionId) {
7495
+ return new AgentControllerSession(this.options, this.controllerId, sessionId);
7408
7496
  }
7409
7497
  };
7410
7498
  /** Pull the plain text out of an assistant message's nested content parts. */
@@ -7478,7 +7566,7 @@ var MastraClient = class extends BaseResource {
7478
7566
  }
7479
7567
  /**
7480
7568
  * Scopes to an agent controller hosted on the connected Mastra instance. Use
7481
- * `getAgentController(id).session(resourceId)` to create/resume a session,
7569
+ * `getAgentController(id).session(sessionId)` to create/resume a session,
7482
7570
  * stream its events, and send messages.
7483
7571
  * @param controllerId - The id the agent controller is registered under on Mastra
7484
7572
  */
@@ -7729,8 +7817,10 @@ var MastraClient = class extends BaseResource {
7729
7817
  if (logLevel) searchParams.set("logLevel", logLevel);
7730
7818
  if (page !== void 0) searchParams.set("page", String(page));
7731
7819
  if (perPage !== void 0) searchParams.set("perPage", String(perPage));
7732
- if (_filters) if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7733
- else searchParams.set("filters", _filters);
7820
+ if (_filters) {
7821
+ if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7822
+ else searchParams.set("filters", _filters);
7823
+ }
7734
7824
  if (searchParams.size) return this.request(`/logs?${searchParams}`);
7735
7825
  else return this.request(`/logs`);
7736
7826
  }
@@ -7750,8 +7840,10 @@ var MastraClient = class extends BaseResource {
7750
7840
  if (logLevel) searchParams.set("logLevel", logLevel);
7751
7841
  if (page !== void 0) searchParams.set("page", String(page));
7752
7842
  if (perPage !== void 0) searchParams.set("perPage", String(perPage));
7753
- if (_filters) if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7754
- else searchParams.set("filters", _filters);
7843
+ if (_filters) {
7844
+ if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7845
+ else searchParams.set("filters", _filters);
7846
+ }
7755
7847
  if (searchParams.size) return this.request(`/logs/${runId}?${searchParams}`);
7756
7848
  else return this.request(`/logs/${runId}`);
7757
7849
  }
@@ -7828,6 +7920,77 @@ var MastraClient = class extends BaseResource {
7828
7920
  });
7829
7921
  }
7830
7922
  /**
7923
+ * Lists the event types an MCP server declares (experimental).
7924
+ * `testEmit` is true when the server serves {@link emitMcpServerEvent} (under `mastra dev`).
7925
+ * @param serverId - The ID of the MCP server.
7926
+ */
7927
+ getMcpServerEvents(serverId) {
7928
+ return this.request(`/mcp/${encodeURIComponent(serverId)}/events`);
7929
+ }
7930
+ /**
7931
+ * Reads occurrences of an MCP server event type, like the `events/poll` MCP request (experimental).
7932
+ * Pass the returned `cursor` to the next call to resume.
7933
+ * @param serverId - The ID of the MCP server.
7934
+ * @param eventName - The event type name.
7935
+ * @param body - Event arguments, resume cursor and page size.
7936
+ */
7937
+ pollMcpServerEvent(serverId, eventName, body = {}) {
7938
+ return this.request(`/mcp/${encodeURIComponent(serverId)}/events/${encodeURIComponent(eventName)}/poll`, {
7939
+ method: "POST",
7940
+ body
7941
+ });
7942
+ }
7943
+ /**
7944
+ * Streams occurrences of a push-capable MCP server event type (experimental).
7945
+ * Yields an `active` frame first, then `event`, `heartbeat` and `error` frames, and ends
7946
+ * when the server ends the stream. Abort `options.signal` or break out of the loop to stop.
7947
+ *
7948
+ * @example
7949
+ * ```typescript
7950
+ * const controller = new AbortController();
7951
+ * for await (const frame of client.streamMcpServerEvent('tickets', 'ticket.created', {}, { signal: controller.signal })) {
7952
+ * if (frame.type === 'event') console.log(frame.occurrence.data);
7953
+ * }
7954
+ * ```
7955
+ */
7956
+ async *streamMcpServerEvent(serverId, eventName, body = {}, options = {}) {
7957
+ const response = await this.request(`/mcp/${encodeURIComponent(serverId)}/events/${encodeURIComponent(eventName)}/stream`, {
7958
+ method: "POST",
7959
+ body,
7960
+ stream: true,
7961
+ signal: options.signal,
7962
+ retries: 0
7963
+ });
7964
+ if (!response.body) throw new Error("Response body is null");
7965
+ const reader = response.body.pipeThrough(createSseJsonTransform()).getReader();
7966
+ const cancel = () => void reader.cancel().catch(() => {});
7967
+ options.signal?.addEventListener("abort", cancel, { once: true });
7968
+ try {
7969
+ while (true) {
7970
+ const { value, done } = await reader.read();
7971
+ if (done) return;
7972
+ yield value;
7973
+ }
7974
+ } finally {
7975
+ options.signal?.removeEventListener("abort", cancel);
7976
+ await reader.cancel().catch(() => {});
7977
+ }
7978
+ }
7979
+ /**
7980
+ * Emits a test occurrence of an emit-fed MCP server event type (experimental).
7981
+ * Only served under `mastra dev`; other servers respond 404. The occurrence's
7982
+ * `eventId` starts with `mastra-test-`.
7983
+ * @param serverId - The ID of the MCP server.
7984
+ * @param eventName - The event type name.
7985
+ * @param data - The event payload; validated against the event's payload schema.
7986
+ */
7987
+ emitMcpServerEvent(serverId, eventName, data) {
7988
+ return this.request(`/mcp/${encodeURIComponent(serverId)}/events/${encodeURIComponent(eventName)}/emit`, {
7989
+ method: "POST",
7990
+ body: { data }
7991
+ });
7992
+ }
7993
+ /**
7831
7994
  * Gets an A2A client for interacting with an agent via the A2A protocol
7832
7995
  * @param agentId - ID of the agent to interact with
7833
7996
  * @returns A2A client instance