@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.js CHANGED
@@ -59,15 +59,16 @@ function attributesToOtlp(attrs) {
59
59
  key,
60
60
  value: { boolValue: raw }
61
61
  });
62
- else if (typeof raw === "number") if (Number.isInteger(raw)) out.push({
63
- key,
64
- value: { intValue: raw }
65
- });
66
- else out.push({
67
- key,
68
- value: { doubleValue: raw }
69
- });
70
- else try {
62
+ else if (typeof raw === "number") {
63
+ if (Number.isInteger(raw)) out.push({
64
+ key,
65
+ value: { intValue: raw }
66
+ });
67
+ else out.push({
68
+ key,
69
+ value: { doubleValue: raw }
70
+ });
71
+ } else try {
71
72
  out.push({
72
73
  key,
73
74
  value: { stringValue: JSON.stringify(raw) }
@@ -662,7 +663,6 @@ function fixJson(input) {
662
663
  stack.pop();
663
664
  stack.push(swapState);
664
665
  stack.push("INSIDE_ARRAY_START");
665
- break;
666
666
  }
667
667
  }
668
668
  function processAfterObjectValue(char, i) {
@@ -674,7 +674,6 @@ function fixJson(input) {
674
674
  case "}":
675
675
  lastValidIndex = i;
676
676
  stack.pop();
677
- break;
678
677
  }
679
678
  }
680
679
  function processAfterArrayValue(char, i) {
@@ -686,7 +685,6 @@ function fixJson(input) {
686
685
  case "]":
687
686
  lastValidIndex = i;
688
687
  stack.pop();
689
- break;
690
688
  }
691
689
  }
692
690
  for (let i = 0; i < input.length; i++) {
@@ -704,7 +702,6 @@ function fixJson(input) {
704
702
  case "}":
705
703
  lastValidIndex = i;
706
704
  stack.pop();
707
- break;
708
705
  }
709
706
  break;
710
707
  case "INSIDE_OBJECT_AFTER_COMMA":
@@ -712,7 +709,6 @@ function fixJson(input) {
712
709
  case "\"":
713
710
  stack.pop();
714
711
  stack.push("INSIDE_OBJECT_KEY");
715
- break;
716
712
  }
717
713
  break;
718
714
  case "INSIDE_OBJECT_KEY":
@@ -720,7 +716,6 @@ function fixJson(input) {
720
716
  case "\"":
721
717
  stack.pop();
722
718
  stack.push("INSIDE_OBJECT_AFTER_KEY");
723
- break;
724
719
  }
725
720
  break;
726
721
  case "INSIDE_OBJECT_AFTER_KEY":
@@ -728,7 +723,6 @@ function fixJson(input) {
728
723
  case ":":
729
724
  stack.pop();
730
725
  stack.push("INSIDE_OBJECT_BEFORE_VALUE");
731
- break;
732
726
  }
733
727
  break;
734
728
  case "INSIDE_OBJECT_BEFORE_VALUE":
@@ -758,7 +752,6 @@ function fixJson(input) {
758
752
  default:
759
753
  lastValidIndex = i;
760
754
  processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
761
- break;
762
755
  }
763
756
  break;
764
757
  case "INSIDE_ARRAY_AFTER_VALUE":
@@ -771,9 +764,7 @@ function fixJson(input) {
771
764
  lastValidIndex = i;
772
765
  stack.pop();
773
766
  break;
774
- default:
775
- lastValidIndex = i;
776
- break;
767
+ default: lastValidIndex = i;
777
768
  }
778
769
  break;
779
770
  case "INSIDE_ARRAY_AFTER_COMMA":
@@ -814,9 +805,7 @@ function fixJson(input) {
814
805
  stack.pop();
815
806
  if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
816
807
  break;
817
- default:
818
- stack.pop();
819
- break;
808
+ default: stack.pop();
820
809
  }
821
810
  break;
822
811
  case "INSIDE_LITERAL": {
@@ -1225,8 +1214,16 @@ var BaseResource = class {
1225
1214
  };
1226
1215
  //#endregion
1227
1216
  //#region src/resources/agent.ts
1228
- const SIGNAL_RUNTIME_OPTIONS_TTL_MS = 300 * 1e3;
1217
+ const SIGNAL_RUNTIME_OPTIONS_TTL_MS = 3e5;
1229
1218
  const signalRuntimeOptionsByRunId = /* @__PURE__ */ new Map();
1219
+ /**
1220
+ * Client tools a resume request can execute, keyed by run. The stream that stayed open from
1221
+ * before the suspension must not run those tools again, but it must run any resumed client tool
1222
+ * the resume request cannot execute (a server-side approve sends no client tools). Held until the
1223
+ * last stream of the run closes, which is after the resume request returns.
1224
+ */
1225
+ const resumingClientToolNamesByRunKey = /* @__PURE__ */ new Map();
1226
+ const openStreamCountByRunKey = /* @__PURE__ */ new Map();
1230
1227
  const latestSignalRuntimeOptionsByThread = /* @__PURE__ */ new Map();
1231
1228
  const createSignalRuntimeOptionsEntry = (store, key, streamOptions) => {
1232
1229
  const timeout = setTimeout(() => store.delete(key), SIGNAL_RUNTIME_OPTIONS_TTL_MS);
@@ -1419,6 +1416,49 @@ var Agent = class extends BaseResource {
1419
1416
  getSignalRuntimeRunKey(runId) {
1420
1417
  return `${this.options.baseUrl}|${this.apiPrefix}|${this.agentId}|${runId}`;
1421
1418
  }
1419
+ /**
1420
+ * Records that `runId` is being resumed by a request that can execute these client tools, so the
1421
+ * stream that is still open from before the suspension skips them. Released when the last stream
1422
+ * of the run closes, which is after this request returns.
1423
+ */
1424
+ holdResumingClientTools(runId, clientTools) {
1425
+ const names = Object.entries(clientTools ?? {}).filter(([, tool]) => typeof tool.execute === "function").map(([name]) => name);
1426
+ if (names.length === 0) return () => {};
1427
+ const key = this.getSignalRuntimeRunKey(runId);
1428
+ const held = resumingClientToolNamesByRunKey.get(key) ?? /* @__PURE__ */ new Map();
1429
+ for (const name of names) held.set(name, (held.get(name) ?? 0) + 1);
1430
+ resumingClientToolNamesByRunKey.set(key, held);
1431
+ let released = false;
1432
+ return ({ force = false } = {}) => {
1433
+ if (released || !force && openStreamCountByRunKey.has(key)) return;
1434
+ released = true;
1435
+ const current = resumingClientToolNamesByRunKey.get(key);
1436
+ if (!current) return;
1437
+ for (const name of names) {
1438
+ const count = (current.get(name) ?? 1) - 1;
1439
+ if (count > 0) current.set(name, count);
1440
+ else current.delete(name);
1441
+ }
1442
+ if (current.size === 0) resumingClientToolNamesByRunKey.delete(key);
1443
+ };
1444
+ }
1445
+ /** Drops the held tool names when the last stream of the run closes. */
1446
+ trackOpenStream(runId) {
1447
+ const key = this.getSignalRuntimeRunKey(runId);
1448
+ openStreamCountByRunKey.set(key, (openStreamCountByRunKey.get(key) ?? 0) + 1);
1449
+ let released = false;
1450
+ return () => {
1451
+ if (released) return;
1452
+ released = true;
1453
+ const remaining = (openStreamCountByRunKey.get(key) ?? 1) - 1;
1454
+ if (remaining > 0) {
1455
+ openStreamCountByRunKey.set(key, remaining);
1456
+ return;
1457
+ }
1458
+ openStreamCountByRunKey.delete(key);
1459
+ resumingClientToolNamesByRunKey.delete(key);
1460
+ };
1461
+ }
1422
1462
  getSignalRuntimeThreadKey({ resourceId, threadId }) {
1423
1463
  if (!threadId) return void 0;
1424
1464
  return `${this.options.baseUrl}|${this.apiPrefix}|${this.agentId}|${resourceId ?? ""}|${threadId}`;
@@ -2556,7 +2596,6 @@ var Agent = class extends BaseResource {
2556
2596
  case "finish":
2557
2597
  finishReason = chunk.payload?.stepResult?.reason ?? finishReason;
2558
2598
  if (chunk.payload?.usage != null) usage = chunk.payload.usage;
2559
- break;
2560
2599
  }
2561
2600
  }
2562
2601
  });
@@ -2621,6 +2660,9 @@ var Agent = class extends BaseResource {
2621
2660
  let messages = [];
2622
2661
  let streamRunId = processedParams.runId;
2623
2662
  let finishedHistory;
2663
+ let suspended = false;
2664
+ const resumedToolCallIds = /* @__PURE__ */ new Set();
2665
+ const releaseOpenStream = streamRunId ? this.trackOpenStream(streamRunId) : () => {};
2624
2666
  const [streamForController, streamForProcessing] = response.body.tee();
2625
2667
  const decoder = new TextDecoder();
2626
2668
  let pendingText = "";
@@ -2689,6 +2731,9 @@ var Agent = class extends BaseResource {
2689
2731
  });
2690
2732
  }
2691
2733
  const executableToolCalls = [...toolInvocationsById.values()].filter((toolCall) => {
2734
+ if (resumedToolCallIds.has(toolCall.toolCallId)) {
2735
+ if ((streamRunId ? resumingClientToolNamesByRunKey.get(this.getSignalRuntimeRunKey(streamRunId)) : void 0)?.has(toolCall.toolName)) return false;
2736
+ }
2692
2737
  const clientTool = processedParams.clientTools?.[toolCall.toolName];
2693
2738
  return Boolean(clientTool?.execute);
2694
2739
  });
@@ -2815,6 +2860,12 @@ var Agent = class extends BaseResource {
2815
2860
  },
2816
2861
  onStreamChunk: (chunk) => {
2817
2862
  if (!streamRunId && typeof chunk.runId === "string") streamRunId = chunk.runId;
2863
+ if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") suspended = true;
2864
+ else if (suspended && chunk.type === "tool-call" && typeof chunk.payload?.toolCallId === "string") {
2865
+ const toolName = chunk.payload.toolName;
2866
+ const held = streamRunId ? resumingClientToolNamesByRunKey.get(this.getSignalRuntimeRunKey(streamRunId)) : void 0;
2867
+ if (typeof toolName === "string" && held?.has(toolName)) resumedToolCallIds.add(chunk.payload.toolCallId);
2868
+ }
2818
2869
  },
2819
2870
  lastMessage: void 0
2820
2871
  }).catch(async (error) => {
@@ -2825,6 +2876,7 @@ var Agent = class extends BaseResource {
2825
2876
  safeClose();
2826
2877
  }).finally(() => {
2827
2878
  signal?.removeEventListener("abort", onAbort);
2879
+ releaseOpenStream();
2828
2880
  });
2829
2881
  } catch (error) {
2830
2882
  if (!isAbortError(error)) console.error("Error processing stream response:", error);
@@ -2992,13 +3044,18 @@ var Agent = class extends BaseResource {
2992
3044
  }
2993
3045
  async approveToolCall(params) {
2994
3046
  const { requestContext, ...rest } = params;
3047
+ const executableClientTools = params.clientToolsResolver?.() ?? params.clientTools;
3048
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
2995
3049
  const processedParams = {
2996
3050
  ...rest,
2997
3051
  requestContext: parseClientRequestContext(requestContext),
2998
- clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
3052
+ clientTools: processClientTools(executableClientTools)
2999
3053
  };
3000
3054
  const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
3001
- const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call", signal);
3055
+ const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call", signal).catch((error) => {
3056
+ releaseHold({ force: true });
3057
+ throw error;
3058
+ });
3002
3059
  const streamResponse = new Response(readable, {
3003
3060
  status: response.status,
3004
3061
  statusText: response.statusText,
@@ -3024,13 +3081,18 @@ var Agent = class extends BaseResource {
3024
3081
  }
3025
3082
  async declineToolCall(params) {
3026
3083
  const { requestContext, ...rest } = params;
3084
+ const executableClientTools = params.clientToolsResolver?.() ?? params.clientTools;
3085
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
3027
3086
  const processedParams = {
3028
3087
  ...rest,
3029
3088
  requestContext: parseClientRequestContext(requestContext),
3030
- clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
3089
+ clientTools: processClientTools(executableClientTools)
3031
3090
  };
3032
3091
  const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
3033
- const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call", signal);
3092
+ const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call", signal).catch((error) => {
3093
+ releaseHold({ force: true });
3094
+ throw error;
3095
+ });
3034
3096
  const streamResponse = new Response(readable, {
3035
3097
  status: response.status,
3036
3098
  statusText: response.statusText,
@@ -3090,18 +3152,23 @@ var Agent = class extends BaseResource {
3090
3152
  * Used to continue execution after a suspension point (e.g., workflow suspend within an agent).
3091
3153
  */
3092
3154
  async resumeStream(resumeData, options) {
3155
+ const executableClientTools = options.clientToolsResolver?.() ?? options.clientTools;
3156
+ const releaseHold = this.holdResumingClientTools(options.runId, executableClientTools);
3093
3157
  const processedParams = {
3094
3158
  ...options,
3095
3159
  resumeData,
3096
3160
  requestContext: parseClientRequestContext(options.requestContext),
3097
- clientTools: processClientTools(options.clientToolsResolver?.() ?? options.clientTools),
3161
+ clientTools: processClientTools(executableClientTools),
3098
3162
  structuredOutput: options.structuredOutput ? {
3099
3163
  ...options.structuredOutput,
3100
3164
  schema: standardSchemaToJSONSchema(toStandardSchema(options.structuredOutput.schema))
3101
3165
  } : void 0
3102
3166
  };
3103
3167
  const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
3104
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream", signal);
3168
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream", signal).catch((error) => {
3169
+ releaseHold({ force: true });
3170
+ throw error;
3171
+ });
3105
3172
  const streamResponse = new Response(readable, {
3106
3173
  status: response.status,
3107
3174
  statusText: response.statusText,
@@ -3154,18 +3221,23 @@ var Agent = class extends BaseResource {
3154
3221
  * Used to continue execution after a suspension point (e.g., workflow suspend within an agent).
3155
3222
  */
3156
3223
  async resumeStreamUntilIdle(resumeData, options) {
3224
+ const executableClientTools = options.clientToolsResolver?.() ?? options.clientTools;
3225
+ const releaseHold = this.holdResumingClientTools(options.runId, executableClientTools);
3157
3226
  const processedParams = {
3158
3227
  ...options,
3159
3228
  resumeData,
3160
3229
  requestContext: parseClientRequestContext(options.requestContext),
3161
- clientTools: processClientTools(options.clientToolsResolver?.() ?? options.clientTools),
3230
+ clientTools: processClientTools(executableClientTools),
3162
3231
  structuredOutput: options.structuredOutput ? {
3163
3232
  ...options.structuredOutput,
3164
3233
  schema: standardSchemaToJSONSchema(toStandardSchema(options.structuredOutput.schema))
3165
3234
  } : void 0
3166
3235
  };
3167
3236
  const { readable, controller: readableController, signal } = this.createCancellableStream(options.abortSignal);
3168
- const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle", signal);
3237
+ const response = await this.processStreamResponse(processedParams, readableController, "resume-stream-until-idle", signal).catch((error) => {
3238
+ releaseHold({ force: true });
3239
+ throw error;
3240
+ });
3169
3241
  const streamResponse = new Response(readable, {
3170
3242
  status: response.status,
3171
3243
  statusText: response.statusText,
@@ -3185,20 +3257,32 @@ var Agent = class extends BaseResource {
3185
3257
  */
3186
3258
  async approveToolCallGenerate(params) {
3187
3259
  const { requestContext, clientTools, clientToolsResolver, memory, ...rest } = params;
3188
- const response = await this.request(`/agents/${this.agentId}/approve-tool-call-generate`, {
3189
- method: "POST",
3190
- body: {
3191
- ...rest,
3192
- requestContext: parseClientRequestContext(requestContext),
3193
- clientTools: processClientTools(clientToolsResolver?.() ?? clientTools)
3194
- }
3195
- });
3196
- return this.continueResumedGenerate(response, {
3197
- requestContext,
3198
- clientTools,
3199
- clientToolsResolver,
3200
- memory
3201
- });
3260
+ const executableClientTools = clientToolsResolver?.() ?? clientTools;
3261
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
3262
+ let response;
3263
+ try {
3264
+ response = await this.request(`/agents/${this.agentId}/approve-tool-call-generate`, {
3265
+ method: "POST",
3266
+ body: {
3267
+ ...rest,
3268
+ requestContext: parseClientRequestContext(requestContext),
3269
+ clientTools: processClientTools(executableClientTools)
3270
+ }
3271
+ });
3272
+ } catch (error) {
3273
+ releaseHold({ force: true });
3274
+ throw error;
3275
+ }
3276
+ try {
3277
+ return await this.continueResumedGenerate(response, {
3278
+ requestContext,
3279
+ clientTools: executableClientTools,
3280
+ clientToolsResolver,
3281
+ memory
3282
+ });
3283
+ } finally {
3284
+ releaseHold();
3285
+ }
3202
3286
  }
3203
3287
  /**
3204
3288
  * Declines a pending tool call and returns the complete response (non-streaming).
@@ -3206,20 +3290,32 @@ var Agent = class extends BaseResource {
3206
3290
  */
3207
3291
  async declineToolCallGenerate(params) {
3208
3292
  const { requestContext, clientTools, clientToolsResolver, memory, ...rest } = params;
3209
- const response = await this.request(`/agents/${this.agentId}/decline-tool-call-generate`, {
3210
- method: "POST",
3211
- body: {
3212
- ...rest,
3213
- requestContext: parseClientRequestContext(requestContext),
3214
- clientTools: processClientTools(clientToolsResolver?.() ?? clientTools)
3215
- }
3216
- });
3217
- return this.continueResumedGenerate(response, {
3218
- requestContext,
3219
- clientTools,
3220
- clientToolsResolver,
3221
- memory
3222
- });
3293
+ const executableClientTools = clientToolsResolver?.() ?? clientTools;
3294
+ const releaseHold = this.holdResumingClientTools(rest.runId, executableClientTools);
3295
+ let response;
3296
+ try {
3297
+ response = await this.request(`/agents/${this.agentId}/decline-tool-call-generate`, {
3298
+ method: "POST",
3299
+ body: {
3300
+ ...rest,
3301
+ requestContext: parseClientRequestContext(requestContext),
3302
+ clientTools: processClientTools(executableClientTools)
3303
+ }
3304
+ });
3305
+ } catch (error) {
3306
+ releaseHold({ force: true });
3307
+ throw error;
3308
+ }
3309
+ try {
3310
+ return await this.continueResumedGenerate(response, {
3311
+ requestContext,
3312
+ clientTools: executableClientTools,
3313
+ clientToolsResolver,
3314
+ memory
3315
+ });
3316
+ } finally {
3317
+ releaseHold();
3318
+ }
3223
3319
  }
3224
3320
  /**
3225
3321
  * Runs executable client tools the model called after an approval decision and continues on
@@ -4444,7 +4540,8 @@ async function verifyAgentCardSignatureIfPresent(agentCard, options) {
4444
4540
  index
4445
4541
  });
4446
4542
  if (!verificationKey) throw new Error("No verification key was provided for Agent Card signature verification");
4447
- await compactVerify(compactJws, await importVerificationKey(verificationKey, protectedHeader.alg), { algorithms: allowedAlgorithms });
4543
+ const importedKey = await importVerificationKey(verificationKey, protectedHeader.alg);
4544
+ await compactVerify(compactJws, importedKey, { algorithms: allowedAlgorithms });
4448
4545
  return agentCard;
4449
4546
  } catch (error) {
4450
4547
  verificationErrors.push(error instanceof Error ? error.message : "Unknown verification failure");
@@ -6776,48 +6873,40 @@ function hydrateEventTimestamps(event) {
6776
6873
  return isKnownParsedEvent(event) ? hydrateKnownEvent(event) : event;
6777
6874
  }
6778
6875
  /**
6779
- * A session bound to a `resourceId` within one agent controller. Sessions are
6780
- * get-or-create on the server, so re-creating the same resourceId (and scope)
6781
- * resumes the existing conversation rather than forking it.
6782
- *
6783
- * Pass a `scope` to address an independent session over the same resourceId:
6784
- * two sessions with the same resourceId but different scopes have their own
6785
- * run loop, thread binding, and mode/model/state (e.g. one session per git
6786
- * worktree, with the worktree path as the scope). The scope travels on every
6787
- * request as a `sessionScope` query param.
6876
+ * A session addressed by its `sessionId` within one agent controller. Sessions
6877
+ * are get-or-create on the server, so re-creating the same sessionId resumes
6878
+ * the existing conversation rather than forking it. Many sessions can work on
6879
+ * one `resourceId` (whose threads and memory they use); each has its own run
6880
+ * loop, thread binding, and mode/model/state.
6788
6881
  */
6789
6882
  var AgentControllerSession = class extends BaseResource {
6790
6883
  controllerId;
6791
- resourceId;
6792
- scope;
6793
- constructor(options, controllerId, resourceId, scope) {
6884
+ sessionId;
6885
+ constructor(options, controllerId, sessionId) {
6794
6886
  super(options);
6795
6887
  this.controllerId = controllerId;
6796
- this.resourceId = resourceId;
6797
- this.scope = scope;
6888
+ this.sessionId = sessionId;
6798
6889
  }
6799
6890
  base() {
6800
- return `/agent-controller/${encodeURIComponent(this.controllerId)}/sessions/${encodeURIComponent(this.resourceId)}`;
6801
- }
6802
- /** Append this session's scope (if any) as a `sessionScope` query param. */
6803
- url(path) {
6804
- if (this.scope === void 0) return path;
6805
- return `${path}${path.includes("?") ? "&" : "?"}sessionScope=${encodeURIComponent(this.scope)}`;
6891
+ return `/agent-controller/${encodeURIComponent(this.controllerId)}/sessions/${encodeURIComponent(this.sessionId)}`;
6806
6892
  }
6807
6893
  /**
6808
- * Create or resume this session. Pass `tags` to scope initial thread
6809
- * selection — a thread is a resume candidate only when its metadata matches
6810
- * every tag. Pass `threadId` to bind the session to one exact thread,
6811
- * creating it with that id when it does not exist.
6894
+ * Create or resume this session. `resourceId` names whose threads and memory
6895
+ * the session works on. Without it the server resumes the session on the
6896
+ * resource it already has (the live session's, or the resource of the thread
6897
+ * with the session's id), falling back to the sessionId. Pass `tags` to scope
6898
+ * initial thread selection — a thread is a resume candidate only when its
6899
+ * metadata matches every tag. Pass `threadId` to bind the session to one
6900
+ * exact thread, creating it with that id when it does not exist.
6812
6901
  */
6813
6902
  create(options) {
6814
6903
  return this.request(`/agent-controller/${encodeURIComponent(this.controllerId)}/sessions`, {
6815
6904
  method: "POST",
6816
6905
  body: {
6817
- resourceId: this.resourceId,
6906
+ resourceId: options?.resourceId,
6907
+ sessionId: this.sessionId,
6818
6908
  tags: options?.tags,
6819
- threadId: options?.threadId,
6820
- sessionScope: this.scope
6909
+ threadId: options?.threadId
6821
6910
  }
6822
6911
  });
6823
6912
  }
@@ -6873,7 +6962,7 @@ var AgentControllerSession = class extends BaseResource {
6873
6962
  const abort = new AbortController();
6874
6963
  currentAbort = abort;
6875
6964
  let openTimer;
6876
- const request = this.request(this.url(`${this.base()}/stream`), {
6965
+ const request = this.request(`${this.base()}/stream`, {
6877
6966
  stream: true,
6878
6967
  signal: abort.signal
6879
6968
  });
@@ -7083,7 +7172,7 @@ var AgentControllerSession = class extends BaseResource {
7083
7172
  files: void 0
7084
7173
  } : message;
7085
7174
  const requestContext = parseClientRequestContext(options?.requestContext);
7086
- await this.request(this.url(`${this.base()}/messages`), {
7175
+ await this.request(`${this.base()}/messages`, {
7087
7176
  method: "POST",
7088
7177
  body: {
7089
7178
  message: content,
@@ -7094,7 +7183,7 @@ var AgentControllerSession = class extends BaseResource {
7094
7183
  }
7095
7184
  /** Abort the in-flight run for this session. */
7096
7185
  async abort() {
7097
- await this.request(this.url(`${this.base()}/abort`), { method: "POST" });
7186
+ await this.request(`${this.base()}/abort`, { method: "POST" });
7098
7187
  }
7099
7188
  /**
7100
7189
  * Approve or decline a pending tool call (`tool_approval_required`). Resolves
@@ -7102,7 +7191,7 @@ var AgentControllerSession = class extends BaseResource {
7102
7191
  */
7103
7192
  async approveTool(toolCallId, approved, options) {
7104
7193
  const requestContext = parseClientRequestContext(options?.requestContext);
7105
- return this.request(this.url(`${this.base()}/tool-approval`), {
7194
+ return this.request(`${this.base()}/tool-approval`, {
7106
7195
  method: "POST",
7107
7196
  retries: 0,
7108
7197
  body: {
@@ -7120,7 +7209,7 @@ var AgentControllerSession = class extends BaseResource {
7120
7209
  */
7121
7210
  async respondToToolSuspension(toolCallId, resumeData, options) {
7122
7211
  const requestContext = parseClientRequestContext(options?.requestContext);
7123
- return this.request(this.url(`${this.base()}/tool-suspension`), {
7212
+ return this.request(`${this.base()}/tool-suspension`, {
7124
7213
  method: "POST",
7125
7214
  retries: 0,
7126
7215
  body: {
@@ -7140,7 +7229,7 @@ var AgentControllerSession = class extends BaseResource {
7140
7229
  files: void 0
7141
7230
  } : message;
7142
7231
  const requestContext = parseClientRequestContext(options?.requestContext);
7143
- await this.request(this.url(`${this.base()}/steer`), {
7232
+ await this.request(`${this.base()}/steer`, {
7144
7233
  method: "POST",
7145
7234
  body: {
7146
7235
  message: content,
@@ -7152,18 +7241,18 @@ var AgentControllerSession = class extends BaseResource {
7152
7241
  /** Get the current mode, model, and thread (for initial UI hydration). */
7153
7242
  state(options) {
7154
7243
  const path = options?.threadId ? `${this.base()}?threadId=${encodeURIComponent(options.threadId)}` : this.base();
7155
- return this.request(this.url(path));
7244
+ return this.request(path);
7156
7245
  }
7157
7246
  /** Merge key-value pairs into the session state. Existing keys not in the payload are preserved. */
7158
7247
  async setState(updates) {
7159
- await this.request(this.url(`${this.base()}/state`), {
7248
+ await this.request(`${this.base()}/state`, {
7160
7249
  method: "PUT",
7161
7250
  body: { state: updates }
7162
7251
  });
7163
7252
  }
7164
7253
  /** Switch the active mode (e.g. `build`, `plan`). */
7165
7254
  async switchMode(modeId) {
7166
- await this.request(this.url(`${this.base()}/mode`), {
7255
+ await this.request(`${this.base()}/mode`, {
7167
7256
  method: "POST",
7168
7257
  body: { modeId }
7169
7258
  });
@@ -7173,7 +7262,7 @@ var AgentControllerSession = class extends BaseResource {
7173
7262
  * `thinkingLevel` is provided it is applied and persisted with the model.
7174
7263
  */
7175
7264
  async switchModel(modelId, { thinkingLevel } = {}) {
7176
- await this.request(this.url(`${this.base()}/model`), {
7265
+ await this.request(`${this.base()}/model`, {
7177
7266
  method: "POST",
7178
7267
  body: thinkingLevel !== void 0 ? {
7179
7268
  modelId,
@@ -7194,36 +7283,36 @@ var AgentControllerSession = class extends BaseResource {
7194
7283
  if (opts.limit != null) params.set("limit", String(opts.limit));
7195
7284
  if (opts.tags && Object.keys(opts.tags).length > 0) params.set("tags", JSON.stringify(opts.tags));
7196
7285
  const query = params.toString() ? `?${params.toString()}` : "";
7197
- return (await this.request(this.url(`${this.base()}/threads${query}`))).threads;
7286
+ return (await this.request(`${this.base()}/threads${query}`)).threads;
7198
7287
  }
7199
7288
  /** Switch the session to an existing thread (rebinds stream + state). */
7200
7289
  async switchThread(threadId) {
7201
- await this.request(this.url(`${this.base()}/thread`), {
7290
+ await this.request(`${this.base()}/thread`, {
7202
7291
  method: "POST",
7203
7292
  body: { threadId }
7204
7293
  });
7205
7294
  }
7206
7295
  /** Create a new thread (unbinds previous, binds the new one). */
7207
7296
  async createThread(title) {
7208
- return this.request(this.url(`${this.base()}/threads`), {
7297
+ return this.request(`${this.base()}/threads`, {
7209
7298
  method: "POST",
7210
7299
  body: { title }
7211
7300
  });
7212
7301
  }
7213
7302
  /** Delete a thread. If it's the active thread the session unbinds. */
7214
7303
  async deleteThread(threadId) {
7215
- await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}`), { method: "DELETE" });
7304
+ await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}`, { method: "DELETE" });
7216
7305
  }
7217
7306
  /** Rename a thread. */
7218
7307
  async renameThread(threadId, title) {
7219
- await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}`), {
7308
+ await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}`, {
7220
7309
  method: "PUT",
7221
7310
  body: { title }
7222
7311
  });
7223
7312
  }
7224
7313
  /** Clone a thread (and its messages). The session binds to the clone. */
7225
7314
  async cloneThread(options) {
7226
- return this.request(this.url(`${this.base()}/threads/clone`), {
7315
+ return this.request(`${this.base()}/threads/clone`, {
7227
7316
  method: "POST",
7228
7317
  body: options ?? {}
7229
7318
  });
@@ -7244,7 +7333,7 @@ var AgentControllerSession = class extends BaseResource {
7244
7333
  if (include) queryParams.set("include", JSON.stringify(include));
7245
7334
  }
7246
7335
  const query = queryParams.toString();
7247
- const body = await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}/messages${query ? `?${query}` : ""}`));
7336
+ const body = await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}/messages${query ? `?${query}` : ""}`);
7248
7337
  const messages = body.messages.map(hydrateMessage);
7249
7338
  if (legacy) return messages;
7250
7339
  return {
@@ -7263,7 +7352,7 @@ var AgentControllerSession = class extends BaseResource {
7263
7352
  files: void 0
7264
7353
  } : message;
7265
7354
  const requestContext = parseClientRequestContext(options?.requestContext);
7266
- await this.request(this.url(`${this.base()}/follow-up`), {
7355
+ await this.request(`${this.base()}/follow-up`, {
7267
7356
  method: "POST",
7268
7357
  body: {
7269
7358
  message: content,
@@ -7274,26 +7363,26 @@ var AgentControllerSession = class extends BaseResource {
7274
7363
  }
7275
7364
  /** Get the observational memory record for this session's thread. */
7276
7365
  async getOMRecord() {
7277
- return (await this.request(this.url(`${this.base()}/om`))).record;
7366
+ return (await this.request(`${this.base()}/om`)).record;
7278
7367
  }
7279
7368
  /** Change the session's resource identity. */
7280
7369
  async setResourceId(newResourceId) {
7281
- await this.request(this.url(`${this.base()}/resource`), {
7370
+ await this.request(`${this.base()}/resource`, {
7282
7371
  method: "POST",
7283
7372
  body: { newResourceId }
7284
7373
  });
7285
7374
  }
7286
7375
  /** Get known resource IDs for this session. */
7287
7376
  async getResourceIds() {
7288
- return (await this.request(this.url(`${this.base()}/resources`))).resourceIds;
7377
+ return (await this.request(`${this.base()}/resources`)).resourceIds;
7289
7378
  }
7290
7379
  /** Get the current goal for this session's thread. */
7291
7380
  async getGoal() {
7292
- return (await this.request(this.url(`${this.base()}/goal`))).goal;
7381
+ return (await this.request(`${this.base()}/goal`)).goal;
7293
7382
  }
7294
7383
  /** Set a new goal objective. The agent's in-loop judge evaluates progress after each turn. */
7295
7384
  async setGoal(objective, options) {
7296
- return (await this.request(this.url(`${this.base()}/goal`), {
7385
+ return (await this.request(`${this.base()}/goal`, {
7297
7386
  method: "POST",
7298
7387
  body: {
7299
7388
  objective,
@@ -7303,22 +7392,22 @@ var AgentControllerSession = class extends BaseResource {
7303
7392
  }
7304
7393
  /** Update goal options (judge model, max runs, status). */
7305
7394
  async updateGoal(options) {
7306
- return (await this.request(this.url(`${this.base()}/goal`), {
7395
+ return (await this.request(`${this.base()}/goal`, {
7307
7396
  method: "PUT",
7308
7397
  body: options
7309
7398
  })).goal;
7310
7399
  }
7311
7400
  /** Clear the current goal. */
7312
7401
  async clearGoal() {
7313
- await this.request(this.url(`${this.base()}/goal`), { method: "DELETE" });
7402
+ await this.request(`${this.base()}/goal`, { method: "DELETE" });
7314
7403
  }
7315
7404
  /** Get the current permission rules (per-category and per-tool policies). */
7316
7405
  async getPermissions() {
7317
- return this.request(this.url(`${this.base()}/permissions`));
7406
+ return this.request(`${this.base()}/permissions`);
7318
7407
  }
7319
7408
  /** Set the approval policy for a tool category. */
7320
7409
  async setPermissionForCategory(category, policy) {
7321
- await this.request(this.url(`${this.base()}/permissions/category`), {
7410
+ await this.request(`${this.base()}/permissions/category`, {
7322
7411
  method: "PUT",
7323
7412
  body: {
7324
7413
  category,
@@ -7328,7 +7417,7 @@ var AgentControllerSession = class extends BaseResource {
7328
7417
  }
7329
7418
  /** Set the approval policy for a specific tool. */
7330
7419
  async setPermissionForTool(toolName, policy) {
7331
- await this.request(this.url(`${this.base()}/permissions/tool`), {
7420
+ await this.request(`${this.base()}/permissions/tool`, {
7332
7421
  method: "PUT",
7333
7422
  body: {
7334
7423
  toolName,
@@ -7342,7 +7431,7 @@ var AgentControllerSession = class extends BaseResource {
7342
7431
  * or is persisted for later.
7343
7432
  */
7344
7433
  async sendNotification(input) {
7345
- return this.request(this.url(`${this.base()}/notifications`), {
7434
+ return this.request(`${this.base()}/notifications`, {
7346
7435
  method: "POST",
7347
7436
  body: input
7348
7437
  });
@@ -7375,12 +7464,11 @@ var AgentController = class extends BaseResource {
7375
7464
  return this.request(`${this.basePath()}/workspace`);
7376
7465
  }
7377
7466
  /**
7378
- * Scope to a session bound to `resourceId` (e.g. a user or conversation id).
7379
- * Pass `scope` to address an independent session over the same resourceId
7380
- * (e.g. one session per git worktree, with the worktree path as the scope).
7467
+ * Address the session with this `sessionId`. Sessions created without an
7468
+ * explicit id are addressed by their `resourceId`.
7381
7469
  */
7382
- session(resourceId, scope) {
7383
- return new AgentControllerSession(this.options, this.controllerId, resourceId, scope);
7470
+ session(sessionId) {
7471
+ return new AgentControllerSession(this.options, this.controllerId, sessionId);
7384
7472
  }
7385
7473
  };
7386
7474
  /** Pull the plain text out of an assistant message's nested content parts. */
@@ -7454,7 +7542,7 @@ var MastraClient = class extends BaseResource {
7454
7542
  }
7455
7543
  /**
7456
7544
  * Scopes to an agent controller hosted on the connected Mastra instance. Use
7457
- * `getAgentController(id).session(resourceId)` to create/resume a session,
7545
+ * `getAgentController(id).session(sessionId)` to create/resume a session,
7458
7546
  * stream its events, and send messages.
7459
7547
  * @param controllerId - The id the agent controller is registered under on Mastra
7460
7548
  */
@@ -7705,8 +7793,10 @@ var MastraClient = class extends BaseResource {
7705
7793
  if (logLevel) searchParams.set("logLevel", logLevel);
7706
7794
  if (page !== void 0) searchParams.set("page", String(page));
7707
7795
  if (perPage !== void 0) searchParams.set("perPage", String(perPage));
7708
- if (_filters) if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7709
- else searchParams.set("filters", _filters);
7796
+ if (_filters) {
7797
+ if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7798
+ else searchParams.set("filters", _filters);
7799
+ }
7710
7800
  if (searchParams.size) return this.request(`/logs?${searchParams}`);
7711
7801
  else return this.request(`/logs`);
7712
7802
  }
@@ -7726,8 +7816,10 @@ var MastraClient = class extends BaseResource {
7726
7816
  if (logLevel) searchParams.set("logLevel", logLevel);
7727
7817
  if (page !== void 0) searchParams.set("page", String(page));
7728
7818
  if (perPage !== void 0) searchParams.set("perPage", String(perPage));
7729
- if (_filters) if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7730
- else searchParams.set("filters", _filters);
7819
+ if (_filters) {
7820
+ if (Array.isArray(_filters)) for (const filter of _filters) searchParams.append("filters", filter);
7821
+ else searchParams.set("filters", _filters);
7822
+ }
7731
7823
  if (searchParams.size) return this.request(`/logs/${runId}?${searchParams}`);
7732
7824
  else return this.request(`/logs/${runId}`);
7733
7825
  }
@@ -7804,6 +7896,77 @@ var MastraClient = class extends BaseResource {
7804
7896
  });
7805
7897
  }
7806
7898
  /**
7899
+ * Lists the event types an MCP server declares (experimental).
7900
+ * `testEmit` is true when the server serves {@link emitMcpServerEvent} (under `mastra dev`).
7901
+ * @param serverId - The ID of the MCP server.
7902
+ */
7903
+ getMcpServerEvents(serverId) {
7904
+ return this.request(`/mcp/${encodeURIComponent(serverId)}/events`);
7905
+ }
7906
+ /**
7907
+ * Reads occurrences of an MCP server event type, like the `events/poll` MCP request (experimental).
7908
+ * Pass the returned `cursor` to the next call to resume.
7909
+ * @param serverId - The ID of the MCP server.
7910
+ * @param eventName - The event type name.
7911
+ * @param body - Event arguments, resume cursor and page size.
7912
+ */
7913
+ pollMcpServerEvent(serverId, eventName, body = {}) {
7914
+ return this.request(`/mcp/${encodeURIComponent(serverId)}/events/${encodeURIComponent(eventName)}/poll`, {
7915
+ method: "POST",
7916
+ body
7917
+ });
7918
+ }
7919
+ /**
7920
+ * Streams occurrences of a push-capable MCP server event type (experimental).
7921
+ * Yields an `active` frame first, then `event`, `heartbeat` and `error` frames, and ends
7922
+ * when the server ends the stream. Abort `options.signal` or break out of the loop to stop.
7923
+ *
7924
+ * @example
7925
+ * ```typescript
7926
+ * const controller = new AbortController();
7927
+ * for await (const frame of client.streamMcpServerEvent('tickets', 'ticket.created', {}, { signal: controller.signal })) {
7928
+ * if (frame.type === 'event') console.log(frame.occurrence.data);
7929
+ * }
7930
+ * ```
7931
+ */
7932
+ async *streamMcpServerEvent(serverId, eventName, body = {}, options = {}) {
7933
+ const response = await this.request(`/mcp/${encodeURIComponent(serverId)}/events/${encodeURIComponent(eventName)}/stream`, {
7934
+ method: "POST",
7935
+ body,
7936
+ stream: true,
7937
+ signal: options.signal,
7938
+ retries: 0
7939
+ });
7940
+ if (!response.body) throw new Error("Response body is null");
7941
+ const reader = response.body.pipeThrough(createSseJsonTransform()).getReader();
7942
+ const cancel = () => void reader.cancel().catch(() => {});
7943
+ options.signal?.addEventListener("abort", cancel, { once: true });
7944
+ try {
7945
+ while (true) {
7946
+ const { value, done } = await reader.read();
7947
+ if (done) return;
7948
+ yield value;
7949
+ }
7950
+ } finally {
7951
+ options.signal?.removeEventListener("abort", cancel);
7952
+ await reader.cancel().catch(() => {});
7953
+ }
7954
+ }
7955
+ /**
7956
+ * Emits a test occurrence of an emit-fed MCP server event type (experimental).
7957
+ * Only served under `mastra dev`; other servers respond 404. The occurrence's
7958
+ * `eventId` starts with `mastra-test-`.
7959
+ * @param serverId - The ID of the MCP server.
7960
+ * @param eventName - The event type name.
7961
+ * @param data - The event payload; validated against the event's payload schema.
7962
+ */
7963
+ emitMcpServerEvent(serverId, eventName, data) {
7964
+ return this.request(`/mcp/${encodeURIComponent(serverId)}/events/${encodeURIComponent(eventName)}/emit`, {
7965
+ method: "POST",
7966
+ body: { data }
7967
+ });
7968
+ }
7969
+ /**
7807
7970
  * Gets an A2A client for interacting with an agent via the A2A protocol
7808
7971
  * @param agentId - ID of the agent to interact with
7809
7972
  * @returns A2A client instance