@mastra/ai-sdk 1.6.2 → 1.6.3-alpha.1

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
@@ -10,7 +10,7 @@ import { TripWire, MessageList, aiV5ModelMessageToV2PromptMessage } from '@mastr
10
10
  import { RequestContext } from '@mastra/core/di';
11
11
  import { WorkingMemory, MessageHistory, SemanticRecall } from '@mastra/core/processors';
12
12
 
13
- // ../../packages/_vendored/ai_v5/dist/chunk-ZMFCHGXT.js
13
+ // ../../packages/_vendored/ai_v5/dist/chunk-NFYQIWQU.js
14
14
  var marker = "vercel.ai.error";
15
15
  var symbol = Symbol.for(marker);
16
16
  var _a;
@@ -565,7 +565,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
565
565
  );
566
566
  return Object.fromEntries(normalizedHeaders.entries());
567
567
  }
568
- var VERSION = "3.0.28";
568
+ var VERSION = "3.0.29";
569
569
  var getOriginalFetch = () => globalThis.fetch;
570
570
  var getFromApi = async ({
571
571
  url,
@@ -714,7 +714,7 @@ function lazyValidator(createValidator) {
714
714
  };
715
715
  }
716
716
  function asValidator(value) {
717
- return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
717
+ return isValidator(value) ? value : "~standard" in value ? standardSchemaValidator(value) : value();
718
718
  }
719
719
  function standardSchemaValidator(standardSchema2) {
720
720
  return validator(async (value) => {
@@ -2339,18 +2339,27 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
2339
2339
  var name22 = "GatewayForbiddenError";
2340
2340
  var marker32 = `vercel.ai.gateway.error.${name22}`;
2341
2341
  var symbol32 = Symbol.for(marker32);
2342
+ var forbiddenParamSchema = lazyValidator(
2343
+ () => zodSchema(
2344
+ z.object({
2345
+ ruleId: z.string()
2346
+ })
2347
+ )
2348
+ );
2342
2349
  var _a32;
2343
2350
  var _b32;
2344
2351
  var GatewayForbiddenError = class extends (_b32 = GatewayError, _a32 = symbol32, _b32) {
2345
2352
  constructor({
2346
2353
  message = "Forbidden",
2347
2354
  statusCode = 403,
2348
- cause
2355
+ cause,
2356
+ ruleId
2349
2357
  } = {}) {
2350
2358
  super({ message, statusCode, cause });
2351
2359
  this[_a32] = true;
2352
2360
  this.name = name22;
2353
2361
  this.type = "forbidden";
2362
+ this.ruleId = ruleId;
2354
2363
  }
2355
2364
  static isInstance(error) {
2356
2365
  return GatewayError.hasMarker(error) && symbol32 in error;
@@ -2518,8 +2527,18 @@ async function createGatewayErrorFromResponse({
2518
2527
  }
2519
2528
  case "internal_server_error":
2520
2529
  return new GatewayInternalServerError({ message, statusCode, cause });
2521
- case "forbidden":
2522
- return new GatewayForbiddenError({ message, statusCode, cause });
2530
+ case "forbidden": {
2531
+ const ruleResult = await safeValidateTypes({
2532
+ value: validatedResponse.error.param,
2533
+ schema: forbiddenParamSchema
2534
+ });
2535
+ return new GatewayForbiddenError({
2536
+ message,
2537
+ statusCode,
2538
+ cause,
2539
+ ruleId: ruleResult.success ? ruleResult.value.ruleId : void 0
2540
+ });
2541
+ }
2523
2542
  default:
2524
2543
  return new GatewayInternalServerError({ message, statusCode, cause });
2525
2544
  }
@@ -3421,7 +3440,7 @@ async function getVercelRequestId() {
3421
3440
  var _a1032;
3422
3441
  return (_a1032 = getContext().headers) == null ? void 0 : _a1032["x-vercel-id"];
3423
3442
  }
3424
- var VERSION2 = "2.0.109";
3443
+ var VERSION2 = "2.0.113";
3425
3444
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
3426
3445
  function createGatewayProvider(options = {}) {
3427
3446
  var _a1032, _b103;
@@ -7028,11 +7047,18 @@ function asSchema2(schema) {
7028
7047
  }
7029
7048
  function standardSchema(standardSchema2) {
7030
7049
  return jsonSchema2(
7031
- () => addAdditionalPropertiesToJsonSchema2(
7032
- standardSchema2["~standard"].jsonSchema.input({
7033
- target: "draft-07"
7034
- })
7035
- ),
7050
+ () => {
7051
+ if (!hasStandardJsonSchema(standardSchema2)) {
7052
+ throw new Error(
7053
+ `Standard schema vendor '${standardSchema2["~standard"].vendor}' does not support JSON Schema conversion.`
7054
+ );
7055
+ }
7056
+ return addAdditionalPropertiesToJsonSchema2(
7057
+ standardSchema2["~standard"].jsonSchema.input({
7058
+ target: "draft-07"
7059
+ })
7060
+ );
7061
+ },
7036
7062
  {
7037
7063
  validate: async (value) => {
7038
7064
  const result = await standardSchema2["~standard"].validate(value);
@@ -7047,6 +7073,9 @@ function standardSchema(standardSchema2) {
7047
7073
  }
7048
7074
  );
7049
7075
  }
7076
+ function hasStandardJsonSchema(schema) {
7077
+ return schema["~standard"].jsonSchema != null;
7078
+ }
7050
7079
  function zod3Schema2(zodSchema22, options) {
7051
7080
  var _a223;
7052
7081
  const useReferences = (_a223 = void 0 ) != null ? _a223 : false;
@@ -9810,13 +9839,14 @@ function convertMastraChunkToAISDKBase({
9810
9839
  // Preserve messageId from the payload so it can be sent to useChat
9811
9840
  ...chunk.payload?.messageId ? { messageId: chunk.payload.messageId } : {}
9812
9841
  };
9813
- case "step-start":
9814
- const { messageId: _messageId, ...rest } = chunk.payload;
9842
+ case "step-start": {
9843
+ const { messageId: _messageId, ...rest } = chunk.payload ?? {};
9815
9844
  return {
9816
9845
  type: "start-step",
9817
9846
  request: rest.request,
9818
9847
  warnings: normalizeWarnings(rest.warnings)
9819
9848
  };
9849
+ }
9820
9850
  case "raw":
9821
9851
  return {
9822
9852
  type: "raw",
@@ -9964,14 +9994,14 @@ function convertMastraChunkToAISDKBase({
9964
9994
  providerMetadata: chunk.payload.providerMetadata
9965
9995
  };
9966
9996
  case "step-finish": {
9967
- const { request: _request, providerMetadata, ...rest2 } = chunk.payload.metadata;
9997
+ const { request: _request, providerMetadata, ...rest } = chunk.payload.metadata;
9968
9998
  return {
9969
9999
  type: "finish-step",
9970
10000
  response: {
9971
10001
  id: chunk.payload.id || "",
9972
10002
  timestamp: /* @__PURE__ */ new Date(),
9973
- modelId: rest2.modelId || "",
9974
- ...rest2
10003
+ modelId: rest.modelId || "",
10004
+ ...rest
9975
10005
  },
9976
10006
  usage: normalizeUsage(chunk.payload.output.usage),
9977
10007
  finishReason: normalizeFinishReason(chunk.payload.stepResult.reason),
@@ -11589,28 +11619,95 @@ function toAISdkStream(stream, options = {
11589
11619
  }
11590
11620
 
11591
11621
  // src/chat-route.ts
11592
- function extractV6NativeApproval(messages) {
11593
- const lastAssistantMsg = messages.at(-1);
11594
- if (!lastAssistantMsg || lastAssistantMsg.role !== "assistant") return null;
11595
- const parts = lastAssistantMsg.parts ?? [];
11596
- for (let i = parts.length - 1; i >= 0; i--) {
11597
- const part = parts[i];
11598
- if (!isToolUIPart2(part) || part.state !== "approval-responded") continue;
11599
- const lastSep = part.approval.id.lastIndexOf(APPROVAL_ID_SEPARATOR);
11600
- if (lastSep === -1) continue;
11601
- const runId = part.approval.id.slice(0, lastSep);
11602
- const toolCallId = part.approval.id.slice(lastSep + APPROVAL_ID_SEPARATOR.length);
11603
- if (!runId || !toolCallId) continue;
11604
- return {
11605
- resumeData: {
11606
- approved: part.approval.approved,
11607
- ...part.approval.reason != null ? { reason: part.approval.reason } : {}
11608
- },
11609
- runId,
11610
- toolCallId
11611
- };
11622
+ function extractV6NativeApprovals(messages) {
11623
+ const byTarget = /* @__PURE__ */ new Map();
11624
+ const separator = APPROVAL_ID_SEPARATOR;
11625
+ for (const message of messages) {
11626
+ if (message.role !== "assistant") continue;
11627
+ for (const part of message.parts ?? []) {
11628
+ if (!isToolUIPart2(part) || part.state !== "approval-responded") continue;
11629
+ const lastSep = part.approval.id.lastIndexOf(separator);
11630
+ if (lastSep === -1) continue;
11631
+ const runId = part.approval.id.slice(0, lastSep);
11632
+ const toolCallId = part.approval.id.slice(lastSep + separator.length);
11633
+ if (!runId || !toolCallId) continue;
11634
+ if (toolCallId !== part.toolCallId) continue;
11635
+ byTarget.set(`${runId}${separator}${toolCallId}`, {
11636
+ resumeData: {
11637
+ approved: part.approval.approved,
11638
+ ...part.approval.reason != null ? { reason: part.approval.reason } : {}
11639
+ },
11640
+ runId,
11641
+ toolCallId
11642
+ });
11643
+ }
11612
11644
  }
11613
- return null;
11645
+ return [...byTarget.values()];
11646
+ }
11647
+ function streamV6ApprovalResumes(args) {
11648
+ const { agent, approvals, baseOptions, structuredOutput, messages, lastMessageId } = args;
11649
+ const { sendStart, sendFinish, sendReasoning, sendSources, onError, messageMetadata } = args;
11650
+ return createUIMessageStream2({
11651
+ originalMessages: messages,
11652
+ onError,
11653
+ execute: async ({ writer }) => {
11654
+ let startWritten = false;
11655
+ let successfulLegs = 0;
11656
+ let firstResolvedTargetError;
11657
+ let finalFinish;
11658
+ for (const approval of approvals) {
11659
+ try {
11660
+ const result = await agent.resumeStream(approval.resumeData, {
11661
+ ...baseOptions,
11662
+ runId: approval.runId,
11663
+ toolCallId: approval.toolCallId,
11664
+ ...structuredOutput ? { structuredOutput } : {}
11665
+ });
11666
+ for await (const part of toAISdkStream(result, {
11667
+ from: "agent",
11668
+ version: "v6",
11669
+ lastMessageId,
11670
+ sendStart,
11671
+ sendFinish,
11672
+ sendReasoning,
11673
+ sendSources,
11674
+ onError,
11675
+ messageMetadata
11676
+ })) {
11677
+ if (part.type === "start") {
11678
+ if (startWritten) continue;
11679
+ startWritten = true;
11680
+ writer.write(part);
11681
+ continue;
11682
+ }
11683
+ if (!startWritten && sendStart) {
11684
+ writer.write({ type: "start", ...lastMessageId ? { messageId: lastMessageId } : {} });
11685
+ startWritten = true;
11686
+ }
11687
+ if (part.type === "finish") {
11688
+ finalFinish = part;
11689
+ continue;
11690
+ }
11691
+ writer.write(part);
11692
+ }
11693
+ successfulLegs++;
11694
+ } catch (error) {
11695
+ const id = error?.id;
11696
+ if (id !== "AGENT_RESUME_TOOL_CALL_NOT_SUSPENDED" && id !== "AGENT_RESUME_NO_SNAPSHOT_FOUND") {
11697
+ throw error;
11698
+ }
11699
+ firstResolvedTargetError ??= error;
11700
+ }
11701
+ }
11702
+ if (successfulLegs === 0 && firstResolvedTargetError) throw firstResolvedTargetError;
11703
+ if (!startWritten && sendStart) {
11704
+ writer.write({ type: "start", ...lastMessageId ? { messageId: lastMessageId } : {} });
11705
+ }
11706
+ if (sendFinish) {
11707
+ writer.write(finalFinish ?? { type: "finish" });
11708
+ }
11709
+ }
11710
+ });
11614
11711
  }
11615
11712
  async function handleChatStream({
11616
11713
  mastra,
@@ -11648,9 +11745,6 @@ async function handleChatStream({
11648
11745
  if (!Array.isArray(messages)) {
11649
11746
  throw new Error("Messages must be an array of UIMessage objects");
11650
11747
  }
11651
- const nativeApproval = version === "v6" && !resumeData ? extractV6NativeApproval(messages) : null;
11652
- const effectiveResumeData = nativeApproval?.resumeData ?? resumeData;
11653
- const effectiveRunId = nativeApproval?.runId ?? runId;
11654
11748
  let lastMessageId;
11655
11749
  let messagesToSend = messages;
11656
11750
  if (messages.length > 0) {
@@ -11672,12 +11766,30 @@ async function handleChatStream({
11672
11766
  const baseOptions = {
11673
11767
  ...defaultOptionsRest,
11674
11768
  ...restOptions,
11675
- ...effectiveRunId && { runId: effectiveRunId },
11676
- ...nativeApproval?.toolCallId && { toolCallId: nativeApproval.toolCallId },
11769
+ ...runId && { runId },
11677
11770
  requestContext: requestContext || defaultOptions3?.requestContext,
11678
11771
  ...Object.keys(mergedProviderOptions).length > 0 && { providerOptions: mergedProviderOptions }
11679
11772
  };
11680
- const result = effectiveResumeData ? structuredOutput ? await agentObj.resumeStream(effectiveResumeData, { ...baseOptions, structuredOutput }) : await agentObj.resumeStream(effectiveResumeData, baseOptions) : structuredOutput ? await agentObj.stream(messagesToSend, { ...baseOptions, structuredOutput }) : await agentObj.stream(messagesToSend, baseOptions);
11773
+ if (version === "v6" && !resumeData && trigger !== "regenerate-message" && messages.at(-1)?.role === "assistant") {
11774
+ const approvals = extractV6NativeApprovals(messages);
11775
+ if (approvals.length > 0) {
11776
+ return streamV6ApprovalResumes({
11777
+ agent: agentObj,
11778
+ approvals,
11779
+ baseOptions,
11780
+ structuredOutput,
11781
+ messages,
11782
+ lastMessageId,
11783
+ sendStart,
11784
+ sendFinish,
11785
+ sendReasoning,
11786
+ sendSources,
11787
+ onError,
11788
+ messageMetadata
11789
+ });
11790
+ }
11791
+ }
11792
+ const result = resumeData ? structuredOutput ? await agentObj.resumeStream(resumeData, { ...baseOptions, structuredOutput }) : await agentObj.resumeStream(resumeData, baseOptions) : structuredOutput ? await agentObj.stream(messagesToSend, { ...baseOptions, structuredOutput }) : await agentObj.stream(messagesToSend, baseOptions);
11681
11793
  if (version === "v6") {
11682
11794
  return createUIMessageStream2({
11683
11795
  originalMessages: messages,