@mastra/client-js 1.32.1-alpha.2 → 1.33.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export * from './tools.js';
4
4
  export type { ChannelPlatformInfo, ChannelInstallationInfo, ChannelConnectOAuth, ChannelConnectDeepLink, ChannelConnectImmediate, ChannelConnectResult, } from './resources/channels.js';
5
5
  export type { AgentCardSignatureKeyProviderInput, AgentCardVerificationKey, GetAgentCardOptions, VerifyAgentCardSignatureOptions, } from './resources/a2a.js';
6
6
  export { agentControllerMessageText } from './resources/agent-controller.js';
7
- export type { AgentControllerInfo, AgentControllerMessage, AgentControllerMessageContent, AgentControllerEvent, KnownAgentControllerEvent, OtherAgentControllerEvent, CreateAgentControllerSessionResponse, SubscribeAgentControllerSessionOptions, AgentControllerSubscription, AgentControllerSessionState, AgentControllerSessionSettings, AgentControllerOMProgress, AgentControllerModeInfo, AgentControllerThreadInfo, AgentControllerTaskSnapshot, AgentControllerAvailableModel, AgentControllerWorkspaceStatus, AgentControllerGoalRecord, SendNotificationInput, SendNotificationResult, PlanResume, PermissionPolicy, PermissionRules, ToolCategory, } from './resources/agent-controller.js';
7
+ export type { AgentControllerInfo, MastraDBMessage, MastraMessageContentV2, MastraMessagePart, AgentControllerEvent, KnownAgentControllerEvent, OtherAgentControllerEvent, CreateAgentControllerSessionResponse, AgentControllerRequestOptions, SubscribeAgentControllerSessionOptions, AgentControllerSubscription, AgentControllerSessionState, AgentControllerSessionSettings, AgentControllerOMProgress, AgentControllerModeInfo, AgentControllerThreadInfo, AgentControllerTaskSnapshot, AgentControllerAvailableModel, AgentControllerWorkspaceStatus, AgentControllerGoalRecord, SendNotificationInput, SendNotificationResult, PlanResume, PermissionPolicy, PermissionRules, ToolCategory, } from './resources/agent-controller.js';
8
8
  export { RequestContext } from '@mastra/core/request-context';
9
9
  export type { ObservabilityCollector } from './observability/types.js';
10
10
  export type { UIMessageWithMetadata } from '@mastra/core/agent';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,YAAY,EACV,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,EACnB,sBAAsB,EACtB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,kCAAkC,EAClC,wBAAwB,EACxB,mBAAmB,EACnB,+BAA+B,GAChC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,YAAY,EACV,mBAAmB,EACnB,sBAAsB,EACtB,6BAA6B,EAC7B,oBAAoB,EACpB,yBAAyB,EACzB,yBAAyB,EACzB,oCAAoC,EACpC,sCAAsC,EACtC,2BAA2B,EAC3B,2BAA2B,EAC3B,8BAA8B,EAC9B,yBAAyB,EACzB,uBAAuB,EACvB,yBAAyB,EACzB,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,yBAAyB,EACzB,qBAAqB,EACrB,sBAAsB,EACtB,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,YAAY,GACb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAG9D,YAAY,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACpE,YAAY,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAChE,YAAY,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AACxE,YAAY,EACV,IAAI,EACJ,MAAM,EACN,YAAY,EACZ,UAAU,EACV,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,UAAU,GACX,MAAM,4BAA4B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,YAAY,EACV,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,EACnB,sBAAsB,EACtB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,kCAAkC,EAClC,wBAAwB,EACxB,mBAAmB,EACnB,+BAA+B,GAChC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,YAAY,EACV,mBAAmB,EACnB,eAAe,EACf,sBAAsB,EACtB,iBAAiB,EACjB,oBAAoB,EACpB,yBAAyB,EACzB,yBAAyB,EACzB,oCAAoC,EACpC,6BAA6B,EAC7B,sCAAsC,EACtC,2BAA2B,EAC3B,2BAA2B,EAC3B,8BAA8B,EAC9B,yBAAyB,EACzB,uBAAuB,EACvB,yBAAyB,EACzB,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,yBAAyB,EACzB,qBAAqB,EACrB,sBAAsB,EACtB,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,YAAY,GACb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAG9D,YAAY,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACpE,YAAY,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAChE,YAAY,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AACxE,YAAY,EACV,IAAI,EACJ,MAAM,EACN,YAAY,EACZ,UAAU,EACV,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,UAAU,GACX,MAAM,4BAA4B,CAAC"}
package/dist/index.js CHANGED
@@ -6139,6 +6139,19 @@ var Channels = class extends BaseResource {
6139
6139
  };
6140
6140
 
6141
6141
  // src/resources/agent-controller.ts
6142
+ function hydrateMessage(message) {
6143
+ return {
6144
+ ...message,
6145
+ createdAt: message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt)
6146
+ };
6147
+ }
6148
+ function hydrateEventMessage(event) {
6149
+ if (event.type !== "message_start" && event.type !== "message_update" && event.type !== "message_end") return event;
6150
+ return {
6151
+ ...event,
6152
+ message: hydrateMessage(event.message)
6153
+ };
6154
+ }
6142
6155
  var AgentControllerSession = class extends BaseResource {
6143
6156
  constructor(options, controllerId, resourceId, scope) {
6144
6157
  super(options);
@@ -6161,59 +6174,175 @@ var AgentControllerSession = class extends BaseResource {
6161
6174
  /**
6162
6175
  * Create or resume this session. Pass `tags` to scope initial thread
6163
6176
  * selection — a thread is a resume candidate only when its metadata matches
6164
- * every tag. Required when sessions share a resourceId (e.g. git worktrees
6165
- * using a `{ projectPath }` tag) so each resumes its own thread instead of the
6166
- * most recent thread across the whole resource.
6177
+ * every tag. Pass `threadId` to bind the session to one exact thread,
6178
+ * creating it with that id when it does not exist.
6167
6179
  */
6168
6180
  create(options) {
6169
6181
  return this.request(`/agent-controller/${encodeURIComponent(this.controllerId)}/sessions`, {
6170
6182
  method: "POST",
6171
- body: { resourceId: this.resourceId, tags: options?.tags, sessionScope: this.scope }
6183
+ body: {
6184
+ resourceId: this.resourceId,
6185
+ tags: options?.tags,
6186
+ threadId: options?.threadId,
6187
+ sessionScope: this.scope
6188
+ }
6172
6189
  });
6173
6190
  }
6174
6191
  /**
6175
6192
  * Subscribe to this session's event stream (SSE). The assistant's reply to a
6176
6193
  * message arrives here as `message_*` events, not on the sendMessage call.
6194
+ *
6195
+ * The returned promise resolves once the stream is actually established and
6196
+ * rejects when it cannot be. A rejected subscribe leaves nothing running —
6197
+ * `reconnect` governs only re-establishment after an established stream
6198
+ * drops, so callers that want connect-time retry can loop around
6199
+ * `subscribe()` themselves and keep cancellation control.
6177
6200
  */
6178
6201
  async subscribe(options) {
6179
- const response = await this.request(this.url(`${this.base()}/stream`), { stream: true });
6180
- if (!response.body) {
6181
- throw new Error("No response body for agent controller session stream");
6182
- }
6183
- const reader = response.body.getReader();
6184
- const decoder = new TextDecoder();
6202
+ const finiteOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
6203
+ const retriesOr = (value, fallback) => value === Infinity || typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
6204
+ const reconnectOptions = options.reconnect === true ? { maxRetries: Infinity, delayMs: 1e3, maxDelayMs: 3e4 } : options.reconnect ? {
6205
+ maxRetries: retriesOr(options.reconnect.maxRetries, Infinity),
6206
+ delayMs: finiteOr(options.reconnect.delayMs, 1e3),
6207
+ maxDelayMs: finiteOr(options.reconnect.maxDelayMs, 3e4)
6208
+ } : null;
6209
+ const backoffDelay = (attempt) => reconnectOptions ? Math.min(reconnectOptions.delayMs * 2 ** (attempt - 1), reconnectOptions.maxDelayMs) : 0;
6185
6210
  let cancelled = false;
6186
- let buffer = "";
6187
- const pump = async () => {
6211
+ let currentReader = null;
6212
+ let reconnectTimer;
6213
+ let delayResolve;
6214
+ const settleDelay = () => {
6215
+ if (reconnectTimer) {
6216
+ clearTimeout(reconnectTimer);
6217
+ reconnectTimer = void 0;
6218
+ }
6219
+ const resolve = delayResolve;
6220
+ delayResolve = void 0;
6221
+ resolve?.();
6222
+ };
6223
+ const delay = (ms) => new Promise((resolve) => {
6224
+ delayResolve = resolve;
6225
+ reconnectTimer = setTimeout(settleDelay, ms);
6226
+ });
6227
+ const requestStream = async () => {
6228
+ const response = await this.request(this.url(`${this.base()}/stream`), { stream: true });
6229
+ if (!response.body) {
6230
+ throw new Error("No response body for agent controller session stream");
6231
+ }
6232
+ return response;
6233
+ };
6234
+ const streamEndedError = () => new Error("Agent controller session stream ended unexpectedly");
6235
+ const findFrameSeparator = (text) => {
6236
+ const candidates = [
6237
+ { index: text.indexOf("\r\n\r\n"), length: 4 },
6238
+ { index: text.indexOf("\n\n"), length: 2 },
6239
+ { index: text.indexOf("\r\r"), length: 2 }
6240
+ ].filter((candidate) => candidate.index !== -1);
6241
+ if (candidates.length === 0) return null;
6242
+ return candidates.reduce((earliest, candidate) => candidate.index < earliest.index ? candidate : earliest);
6243
+ };
6244
+ const pump = async (response) => {
6245
+ const reader = response.body.getReader();
6246
+ currentReader = reader;
6247
+ const decoder = new TextDecoder();
6248
+ let buffer = "";
6188
6249
  try {
6189
6250
  while (!cancelled) {
6190
6251
  const { done, value } = await reader.read();
6191
- if (done) break;
6252
+ if (done) return cancelled ? { kind: "cancelled" } : { kind: "done" };
6192
6253
  buffer += decoder.decode(value, { stream: true });
6193
- let sep;
6194
- while ((sep = buffer.indexOf("\n\n")) !== -1) {
6195
- const frame = buffer.slice(0, sep);
6196
- buffer = buffer.slice(sep + 2);
6197
- for (const line of frame.split("\n")) {
6254
+ let separator;
6255
+ while ((separator = findFrameSeparator(buffer)) !== null) {
6256
+ const frame = buffer.slice(0, separator.index);
6257
+ buffer = buffer.slice(separator.index + separator.length);
6258
+ for (const line of frame.split(/\r\n|\n|\r/)) {
6198
6259
  if (!line.startsWith("data:")) continue;
6199
6260
  const data = line.slice(5).trim();
6200
6261
  if (!data) continue;
6262
+ let event;
6201
6263
  try {
6202
- options.onEvent(JSON.parse(data));
6264
+ event = hydrateEventMessage(JSON.parse(data));
6203
6265
  } catch {
6266
+ continue;
6267
+ }
6268
+ try {
6269
+ options.onEvent(event);
6270
+ } catch (cause) {
6271
+ if (!cancelled) safeOnError(cause);
6272
+ return { kind: "consumer_error" };
6204
6273
  }
6205
6274
  }
6206
6275
  }
6207
6276
  }
6277
+ return { kind: "cancelled" };
6278
+ } catch (error) {
6279
+ return cancelled ? { kind: "cancelled" } : { kind: "transport_error", error };
6280
+ } finally {
6281
+ if (currentReader === reader) currentReader = null;
6282
+ void reader.cancel().catch(() => {
6283
+ });
6284
+ }
6285
+ };
6286
+ const safeOnError = (error) => {
6287
+ try {
6288
+ options.onError?.(error);
6289
+ } catch {
6290
+ }
6291
+ };
6292
+ const reportTerminalError = (result) => {
6293
+ safeOnError(result.kind === "transport_error" ? result.error : streamEndedError());
6294
+ };
6295
+ const pumpSafe = async (response) => {
6296
+ try {
6297
+ return await pump(response);
6208
6298
  } catch (error) {
6209
- if (!cancelled) options.onError?.(error);
6299
+ return cancelled ? { kind: "cancelled" } : { kind: "transport_error", error };
6210
6300
  }
6211
6301
  };
6212
- void pump();
6302
+ const firstResponse = await requestStream();
6303
+ const run = async (initial) => {
6304
+ let response = initial;
6305
+ while (!cancelled) {
6306
+ let result = await pumpSafe(response);
6307
+ if (cancelled || result.kind === "cancelled" || result.kind === "consumer_error") return;
6308
+ if (!reconnectOptions) {
6309
+ reportTerminalError(result);
6310
+ return;
6311
+ }
6312
+ let attempts = 0;
6313
+ let reconnectedResponse;
6314
+ while (!reconnectedResponse) {
6315
+ if (attempts >= reconnectOptions.maxRetries) {
6316
+ reportTerminalError(result);
6317
+ return;
6318
+ }
6319
+ attempts++;
6320
+ await delay(backoffDelay(attempts));
6321
+ if (cancelled) return;
6322
+ try {
6323
+ reconnectedResponse = await requestStream();
6324
+ } catch (error) {
6325
+ result = { kind: "transport_error", error };
6326
+ }
6327
+ }
6328
+ if (cancelled) {
6329
+ void reconnectedResponse.body?.cancel().catch(() => {
6330
+ });
6331
+ return;
6332
+ }
6333
+ response = reconnectedResponse;
6334
+ try {
6335
+ options.onReconnect?.();
6336
+ } catch {
6337
+ }
6338
+ }
6339
+ };
6340
+ void run(firstResponse);
6213
6341
  return {
6214
6342
  unsubscribe: () => {
6215
6343
  cancelled = true;
6216
- void reader.cancel().catch(() => {
6344
+ settleDelay();
6345
+ void currentReader?.cancel().catch(() => {
6217
6346
  });
6218
6347
  }
6219
6348
  };
@@ -6222,12 +6351,18 @@ var AgentControllerSession = class extends BaseResource {
6222
6351
  * Send a user message. The reply streams over `subscribe()`.
6223
6352
  * Pass a structured message to attach files (e.g. pasted images) as base64-encoded data:
6224
6353
  * `sendMessage({ content: 'What is in this image?', files })`.
6354
+ * Pass `options.requestContext` to merge custom context into the run's request context.
6225
6355
  */
6226
- async sendMessage(message) {
6356
+ async sendMessage(message, options) {
6227
6357
  const { content, files } = typeof message === "string" ? { content: message, files: void 0 } : message;
6358
+ const requestContext = parseClientRequestContext(options?.requestContext);
6228
6359
  await this.request(this.url(`${this.base()}/messages`), {
6229
6360
  method: "POST",
6230
- body: { message: content, ...files?.length ? { files } : {} }
6361
+ body: {
6362
+ message: content,
6363
+ ...files?.length ? { files } : {},
6364
+ ...requestContext ? { requestContext } : {}
6365
+ }
6231
6366
  });
6232
6367
  }
6233
6368
  /** Abort the in-flight run for this session. */
@@ -6235,10 +6370,11 @@ var AgentControllerSession = class extends BaseResource {
6235
6370
  await this.request(this.url(`${this.base()}/abort`), { method: "POST" });
6236
6371
  }
6237
6372
  /** Approve or decline a pending tool call (`tool_approval_required`). */
6238
- async approveTool(toolCallId, approved) {
6373
+ async approveTool(toolCallId, approved, options) {
6374
+ const requestContext = parseClientRequestContext(options?.requestContext);
6239
6375
  await this.request(this.url(`${this.base()}/tool-approval`), {
6240
6376
  method: "POST",
6241
- body: { toolCallId, approved }
6377
+ body: { toolCallId, approved, ...requestContext ? { requestContext } : {} }
6242
6378
  });
6243
6379
  }
6244
6380
  /**
@@ -6246,15 +6382,20 @@ var AgentControllerSession = class extends BaseResource {
6246
6382
  * depends on the tool: a string (or string[]) for `ask_user`, "Yes"/"No" for
6247
6383
  * `request_access`, and a {@link PlanResume} for `submit_plan`.
6248
6384
  */
6249
- async respondToToolSuspension(toolCallId, resumeData) {
6385
+ async respondToToolSuspension(toolCallId, resumeData, options) {
6386
+ const requestContext = parseClientRequestContext(options?.requestContext);
6250
6387
  await this.request(this.url(`${this.base()}/tool-suspension`), {
6251
6388
  method: "POST",
6252
- body: { toolCallId, resumeData }
6389
+ body: { toolCallId, resumeData, ...requestContext ? { requestContext } : {} }
6253
6390
  });
6254
6391
  }
6255
6392
  /** Inject a message into the in-flight run without starting a new turn. */
6256
- async steer(message) {
6257
- await this.request(this.url(`${this.base()}/steer`), { method: "POST", body: { message } });
6393
+ async steer(message, options) {
6394
+ const requestContext = parseClientRequestContext(options?.requestContext);
6395
+ await this.request(this.url(`${this.base()}/steer`), {
6396
+ method: "POST",
6397
+ body: { message, ...requestContext ? { requestContext } : {} }
6398
+ });
6258
6399
  }
6259
6400
  /** Get the current mode, model, and thread (for initial UI hydration). */
6260
6401
  state() {
@@ -6330,14 +6471,18 @@ var AgentControllerSession = class extends BaseResource {
6330
6471
  const body = await this.request(
6331
6472
  this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}/messages${params}`)
6332
6473
  );
6333
- return body.messages;
6474
+ return body.messages.map(hydrateMessage);
6334
6475
  }
6335
6476
  /**
6336
6477
  * Queue a follow-up message. If the session is idle it sends immediately;
6337
6478
  * if a run is active it queues for after completion.
6338
6479
  */
6339
- async followUp(message) {
6340
- await this.request(this.url(`${this.base()}/follow-up`), { method: "POST", body: { message } });
6480
+ async followUp(message, options) {
6481
+ const requestContext = parseClientRequestContext(options?.requestContext);
6482
+ await this.request(this.url(`${this.base()}/follow-up`), {
6483
+ method: "POST",
6484
+ body: { message, ...requestContext ? { requestContext } : {} }
6485
+ });
6341
6486
  }
6342
6487
  /** Get the observational memory record for this session's thread. */
6343
6488
  async getOMRecord() {
@@ -6447,7 +6592,7 @@ var AgentController = class extends BaseResource {
6447
6592
  }
6448
6593
  };
6449
6594
  function agentControllerMessageText(message) {
6450
- return message.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("");
6595
+ return message.content.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
6451
6596
  }
6452
6597
 
6453
6598
  // src/client.ts