@mastra/code-sdk 1.21.0 → 1.22.0-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.
@@ -1,11 +1,11 @@
1
1
  import { resolveCredentialStore } from "../agents/credential-resolver.js";
2
- import { resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
3
- import { findRouteModelIndex, getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
2
+ import { advanceHostModelRoute, requestModelRoute, resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
3
+ import { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText, pendingModelFallbackSchema } from "../model-fallback.js";
4
+ import { getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
4
5
  import { isThinkingLevelSetting } from "../thinking.js";
5
6
  import { getRequestAccountSelection, isRequestAccountRoutingExhausted, markRequestAccountRoutingExhausted, setRequestAccountSelection } from "./account-routing-context.js";
6
7
  import { ProviderAuthRequiredError } from "./provider-auth-error.js";
7
8
  import { getOAuthProviders } from "./storage.js";
8
- import { TripWire } from "@mastra/core/agent";
9
9
  import { classifyProviderError } from "@mastra/core/error";
10
10
  // src/auth/account-rotation-processor.ts
11
11
  /**
@@ -29,6 +29,10 @@ import { classifyProviderError } from "@mastra/core/error";
29
29
  * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements
30
30
  * `processInput` only and is registered in `inputProcessors`.
31
31
  */
32
+ /** @deprecated Parse the whole part with `parseModelFallbackPart` from `@mastra/code-sdk/model-fallback`. */
33
+ function isModelFallbackReason(value) {
34
+ return pendingModelFallbackSchema.shape.reason.safeParse(value).success;
35
+ }
32
36
  const ACCOUNT_SWITCH_PART_TYPE = "data-mastracode-account-switch";
33
37
  /** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */
34
38
  const KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map((provider) => provider.id));
@@ -54,10 +58,6 @@ const NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
54
58
  ]);
55
59
  const NETWORK_MESSAGE_PATTERN = /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;
56
60
  const MAX_CAUSE_DEPTH = 4;
57
- /** Persisted data-part type for a model-route hop. */
58
- const MODEL_FALLBACK_PART_TYPE = "data-mastracode-model-fallback";
59
- /** Session-state key set when account rotation advances the model route. */
60
- const MODEL_FALLBACK_STATE_KEY = "mastracodePendingModelFallback";
61
61
  /**
62
62
  * Same-account retries for a stream the provider cut after accepting the
63
63
  * request. Each one can cost a full stream (900 s on the ChatGPT Codex route),
@@ -276,21 +276,6 @@ function accountSwitchNoticeText(data) {
276
276
  }
277
277
  return `Switched ${provider} account: ${data.from?.label ?? "unknown"} → ${data.to.label} (${reason})`;
278
278
  }
279
- /** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */
280
- function modelFallbackNoticeText(data) {
281
- const reason = REASON_TEXT[data.reason] ?? data.reason;
282
- return `Switched model route: ${data.from.label} → ${data.to.label} (${reason})`;
283
- }
284
- /**
285
- * Whether a persisted model-fallback reason is one this build understands.
286
- * `REASON_TEXT` also covers the account-switch reasons, so the notice text
287
- * alone would happily render a foreign value such as `rate-limit` as a
288
- * model-fallback reason; history parsed from another build's part must be
289
- * rejected instead.
290
- */
291
- function isModelFallbackReason(value) {
292
- return value === "pool-exhausted" || value === "persistent-outage";
293
- }
294
279
  async function emitAccountSwitchPart(args, data) {
295
280
  await args.writer?.custom({
296
281
  type: ACCOUNT_SWITCH_PART_TYPE,
@@ -308,8 +293,8 @@ async function emitAccountSwitchPart(args, data) {
308
293
  * before any HTTP request exists).
309
294
  */
310
295
  function providerFromSession(args) {
311
- const modelId = (args.requestContext?.get("controller"))?.session?.modelId;
312
- return typeof modelId === "string" ? providerFromModelId(modelId) : void 0;
296
+ const { modelId } = requestModelRoute(args.requestContext, getRoutingController(args));
297
+ return modelId ? providerFromModelId(modelId) : void 0;
313
298
  }
314
299
  function getRoutingController(args) {
315
300
  return args.requestContext?.get("controller");
@@ -325,12 +310,7 @@ function getRequestActiveAccount(args, store, providerId) {
325
310
  return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find((account) => account.active);
326
311
  }
327
312
  function resolveAccountRoute(args, explicit) {
328
- const controller = getRoutingController(args);
329
- const state = controller?.getState?.();
330
- const pending = state?.mastracodePendingModelFallback;
331
- const pendingMatchesThread = pending && typeof pending.toEntryId === "string" && typeof pending.toModelId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId);
332
- const routeEntries = Array.isArray((state?.modelRoute)?.entries) ? (state?.modelRoute).entries ?? [] : [];
333
- const entry = explicit ? explicit : pendingMatchesThread ? routeEntries.find((candidate) => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId) : routeEntries[findRouteModelIndex(routeEntries, controller?.session?.modelId)];
313
+ const entry = explicit ?? requestModelRoute(args.requestContext, getRoutingController(args)).entries[0];
334
314
  if (!entry || typeof entry.id !== "string" || typeof entry.modelId !== "string") return null;
335
315
  const providerId = providerFromModelId(entry.modelId);
336
316
  if (!providerId) return null;
@@ -401,22 +381,13 @@ var AccountRotationProcessor = class {
401
381
  }
402
382
  async processAPIError(args) {
403
383
  const { error, state } = args;
404
- if (args.retryCount >= this.options.maxProcessorRetries) {
405
- await this.gateChainHop(args, error);
406
- return { retry: false };
407
- }
384
+ if (args.retryCount >= this.options.maxProcessorRetries) return this.hopToNextModel(args);
408
385
  const classification = classifyRotationError(error);
409
- if (classification.kind === "never") {
410
- await this.gateChainHop(args, error);
411
- return { retry: false };
412
- }
386
+ if (classification.kind === "never") return this.hopToNextModel(args);
413
387
  if (classification.kind === "stream-cut") {
414
388
  const budget = state.streamCutRetries;
415
389
  const cuts = budget?.step === args.stepNumber ? budget.count : 0;
416
- if (cuts >= 2) {
417
- await this.gateChainHop(args, error);
418
- return { retry: false };
419
- }
390
+ if (cuts >= 2) return this.hopToNextModel(args);
420
391
  state.streamCutRetries = {
421
392
  step: args.stepNumber,
422
393
  count: cuts + 1
@@ -485,10 +456,8 @@ var AccountRotationProcessor = class {
485
456
  if (args.state.modelRouteCascade !== void 0) return args.state.modelRouteCascade ?? null;
486
457
  const controller = getRoutingController(args);
487
458
  const state = controller?.getState?.();
488
- const route = (state?.modelRoute)?.entries;
489
- const pending = state?.mastracodePendingModelFallback;
490
- const startIndex = pending && typeof pending.toEntryId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId) ? route?.findIndex((entry) => entry.id === pending.toEntryId) : route && findRouteModelIndex(route, controller?.session?.modelId);
491
- if (!route || startIndex === void 0 || startIndex < 0 || route.length - startIndex < 2) {
459
+ const { entries: route } = requestModelRoute(args.requestContext, controller);
460
+ if (route.length < 2) {
492
461
  args.state.modelRouteCascade = null;
493
462
  return null;
494
463
  }
@@ -497,7 +466,7 @@ var AccountRotationProcessor = class {
497
466
  ...!this.options.modeless && { session: { modeId: typeof controller?.session?.modeId === "string" ? controller.session.modeId : "build" } }
498
467
  }, this.options.settingsPath, args.requestContext && !isThinkingLevelSetting(state?.thinkingLevel) ? await this.options.resolveDefaultThinkingLevel?.({ requestContext: args.requestContext }) : void 0);
499
468
  const entries = [];
500
- for (const entry of route.slice(startIndex)) {
469
+ for (const entry of route) {
501
470
  if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.modelId !== "string" || entry.modelId.length === 0) break;
502
471
  if (entries.length > 0) try {
503
472
  resolveModel(entry.modelId, {
@@ -526,24 +495,10 @@ var AccountRotationProcessor = class {
526
495
  args.state.modelRouteCascade = cascade;
527
496
  return cascade;
528
497
  }
529
- /**
530
- * Q14 gate: 400/unknown/unattributable errors never advance routes. Core's
531
- * fallback array advances on ANY thrown error except TripWire
532
- * (llm-execution-step.ts), so when the session route has another entry and the
533
- * current entry is non-last, a bare `retry: false` would silently hop on an
534
- * error class the user excluded from hop triggers. TripWire is the only
535
- * no-advance escape: the runner rethrows it and the fallback loop declines
536
- * to advance. No chain (or already on the last entry) → return and let the
537
- * plain `retry: false` surface the error exactly as before.
538
- */
539
- async gateChainHop(args, error) {
540
- const cascade = await this.getModelRouteCascade(args);
541
- if (!cascade) return;
542
- if (cascade.position >= cascade.entries.length - 1) return;
543
- const reason = error instanceof Error ? error.message : String(error);
544
- throw new TripWire(reason, {}, this.id);
498
+ async hopToNextModel(args) {
499
+ await this.emitModelFallbackPart(args, "pool-exhausted");
500
+ return { retry: false };
545
501
  }
546
- /** Announce and persist the next model-route hop before core advances. */
547
502
  async emitModelFallbackPart(args, reason) {
548
503
  const cascade = await this.getModelRouteCascade(args);
549
504
  if (!cascade) return;
@@ -552,6 +507,7 @@ var AccountRotationProcessor = class {
552
507
  if (!from || !to) return;
553
508
  const controller = args.requestContext?.get("controller");
554
509
  const at = (/* @__PURE__ */ new Date()).toISOString();
510
+ const failure = { kind: isProviderAuthRequiredError(args.error) ? "auth" : classifyProviderError(args.error) };
555
511
  const threadId = typeof controller?.threadId === "string" ? controller.threadId : void 0;
556
512
  const pending = {
557
513
  fromEntryId: from.id,
@@ -561,7 +517,8 @@ var AccountRotationProcessor = class {
561
517
  reason,
562
518
  at
563
519
  };
564
- await controller?.setThreadSetting?.({
520
+ const sticky = !requestModelRoute(args.requestContext, getRoutingController(args)).host;
521
+ if (sticky) await controller?.setThreadSetting?.({
565
522
  key: MODEL_FALLBACK_STATE_KEY,
566
523
  value: pending
567
524
  });
@@ -575,7 +532,8 @@ var AccountRotationProcessor = class {
575
532
  label: to.label
576
533
  },
577
534
  reason,
578
- at
535
+ at,
536
+ failure
579
537
  };
580
538
  try {
581
539
  await args.writer?.custom({
@@ -583,21 +541,22 @@ var AccountRotationProcessor = class {
583
541
  data
584
542
  });
585
543
  } catch (error) {
586
- await controller?.setThreadSetting?.({
544
+ if (sticky) await controller?.setThreadSetting?.({
587
545
  key: MODEL_FALLBACK_STATE_KEY,
588
546
  value: void 0
589
547
  });
590
548
  throw error;
591
549
  }
592
- await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });
550
+ if (sticky) await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });
593
551
  args.state.startNoticeEmitted = false;
594
552
  const targetRoute = resolveAccountRoute(args, to);
595
553
  if (targetRoute) await applyPreferredAccountRoute(args, resolveCredentialStore(args.requestContext) ?? this.options.credentialStore, targetRoute).catch(() => void 0);
596
- controller?.emitEvent?.({
554
+ if (sticky) controller?.emitEvent?.({
597
555
  type: "info",
598
556
  message: modelFallbackNoticeText(data)
599
557
  });
600
558
  cascade.position++;
559
+ if (!sticky && args.requestContext) advanceHostModelRoute(args.requestContext);
601
560
  }
602
561
  /**
603
562
  * Pool done for this request: every instance recorded in the tried-set and
@@ -1,9 +1,10 @@
1
1
  import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError, rejectUnauthorizedResponse } from "./provider-auth-error.js";
2
2
  import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
3
- import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, modelFallbackNoticeText, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
3
+ import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
4
4
  import { anthropicOAuthProvider } from "./providers/anthropic.js";
5
5
  import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
6
6
  import { kimiCodingOAuthProvider } from "./providers/kimi-coding.js";
7
7
  import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
8
+ import { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText } from "../model-fallback.js";
8
9
  import { xaiOAuthProvider } from "./providers/xai.js";
9
10
  export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, AuthStorage, MAX_STREAM_CUT_RETRIES, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, PROVIDER_DISPLAY_NAMES, ProviderAuthRequiredError, accountSwitchNoticeText, anthropicOAuthProvider, classifyRotationError, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, kimiCodingOAuthProvider, modelFallbackNoticeText, openaiCodexOAuthProvider, providerFromError, providerFromModelId, rejectUnauthorizedResponse, xaiOAuthProvider };
@@ -1,6 +1,6 @@
1
- import { MODEL_FALLBACK_STATE_KEY } from "../auth/account-rotation-processor.js";
2
1
  import { GoalManager } from "../goal-manager.js";
3
2
  import { createGoalReminderSignal } from "../goal-signal.js";
3
+ import { MODEL_FALLBACK_STATE_KEY } from "../model-fallback.js";
4
4
  import { THREAD_ACTIVE_MODEL_PACK_ID_KEY } from "../onboarding/settings.js";
5
5
  import { parseCodexModelSelection } from "../providers/model-ids.js";
6
6
  import { autoApprovePolicy } from "./policy.js";
package/dist/index.d.ts CHANGED
@@ -19,6 +19,7 @@ import type { PostToolObserver, ToolLike } from './agents/tools.js';
19
19
  import { AuthStorage } from './auth/storage.js';
20
20
  import { HookManager } from './hooks/index.js';
21
21
  import type { McpServerConfig } from './mcp/index.js';
22
+ import type { ModelFallback } from './model-fallback.js';
22
23
  import { loadSettings } from './onboarding/settings.js';
23
24
  import { PluginManager } from './plugins/manager.js';
24
25
  import { ThreadScheduler } from './schedules/index.js';
@@ -136,6 +137,10 @@ export interface MastraCodeConfig {
136
137
  resolveDefaultThinkingLevel?: (ctx: {
137
138
  requestContext: RequestContext;
138
139
  }) => ThinkingLevelSetting | Promise<ThinkingLevelSetting>;
140
+ /** Host-owned model route for the current request, called on every model resolution. */
141
+ resolveModelRoute?: (ctx: {
142
+ requestContext: RequestContext;
143
+ }) => readonly ModelFallback[] | Promise<readonly ModelFallback[]>;
139
144
  /** Create a thread during local boot when no existing thread matches. Default: true */
140
145
  createInitialThread?: boolean;
141
146
  /** Trusted host instructions resolved outside mutable session state. */
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { createBackgroundCompletionCallbacks } from "./agents/background-complet
5
5
  import { hasCredentialStoreProvider, setCredentialLogger, withCredentialTenantPreparation } from "./agents/credential-resolver.js";
6
6
  import { getDynamicInstructions } from "./agents/instructions.js";
7
7
  import { getDynamicMemory } from "./agents/memory.js";
8
- import { canUseProvider, createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from "./agents/model.js";
8
+ import { canUseProvider, createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel, setHostModelRoute } from "./agents/model.js";
9
9
  import { buildMode } from "./agents/modes/build.js";
10
10
  import { fastMode } from "./agents/modes/explore.js";
11
11
  import { createPlanMode } from "./agents/modes/plan.js";
@@ -14,30 +14,32 @@ import { builtinSubagents, resolveSubagentsSetting } from "./agents/subagents/in
14
14
  import { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from "./agents/thread-caveman-state.js";
15
15
  import { createDynamicTools, createToolHooks } from "./agents/tools.js";
16
16
  import { getDynamicWorkspace, getGoalJudgeTools } from "./agents/workspace.js";
17
- import { AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_STATE_KEY, isStreamCutAfterResponse } from "./auth/account-rotation-processor.js";
17
+ import { AccountRotationProcessor, AccountStartNoticeProcessor, isStreamCutAfterResponse } from "./auth/account-rotation-processor.js";
18
18
  import { isKimiCodingDeviceId } from "./auth/providers/kimi-coding.js";
19
19
  import { AuthStorage } from "./auth/storage.js";
20
20
  import { CODE_AGENT_ID, DEFAULT_OM_MODEL_ID, validateConfigDirName } from "./constants.js";
21
21
  import { resolveAgentStreamsOff, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent } from "./experimental-agent.js";
22
22
  import "./hooks/index.js";
23
23
  import { KnowledgeInspectorError, createKnowledgeInspector } from "./knowledge-inspector.js";
24
- import { createSubmitPlanTool } from "./tools/submit-plan.js";
25
24
  import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeSessionScopes } from "./knowledge-scope.js";
25
+ import { createSubmitPlanTool } from "./tools/submit-plan.js";
26
26
  import "./mcp/index.js";
27
+ import { MODEL_FALLBACK_STATE_KEY } from "./model-fallback.js";
27
28
  import { getAvailableOmPacks, resolveAutoOMModelId } from "./onboarding/packs.js";
28
29
  import { MASTRA_GATEWAY_PROVIDER, OBSERVABILITY_AUTH_PREFIX, loadSettings, resolveOmRoleModel, saveSettings } from "./onboarding/settings.js";
29
30
  import { getToolCategory } from "./permissions.js";
30
31
  import { PluginManager } from "./plugins/manager.js";
31
32
  import { PluginSignalLane } from "./plugins/signal-lane.js";
32
33
  import { PlanRejectionAbortProcessor } from "./processors/plan-rejection-abort.js";
34
+ import { RouteAwareStreamErrorRetryProcessor } from "./processors/route-aware-stream-error-retry.js";
33
35
  import { createAmazonBedrockGateway } from "./providers/amazon-bedrock-gateway.js";
34
36
  import { setAuthStorage } from "./providers/claude-max.js";
35
37
  import { createGitHubCopilotGateway } from "./providers/github-copilot-gateway.js";
36
- import { setAuthStorage as setAuthStorage$1 } from "./providers/github-copilot.js";
37
38
  import { HookManager } from "./hooks/manager.js";
39
+ import { setAuthStorage as setAuthStorage$1 } from "./providers/github-copilot.js";
38
40
  import { createGoogleVertexGateway } from "./providers/google-vertex-gateway.js";
39
- import { setAuthStorage as setAuthStorage$2 } from "./providers/kimi-coding.js";
40
41
  import { createMcpManager } from "./mcp/manager.js";
42
+ import { setAuthStorage as setAuthStorage$2 } from "./providers/kimi-coding.js";
41
43
  import { parseCodexModelSelection } from "./providers/model-ids.js";
42
44
  import { setAuthStorage as setAuthStorage$3 } from "./providers/openai-codex.js";
43
45
  import { setAuthStorage as setAuthStorage$4 } from "./providers/xai.js";
@@ -79,7 +81,7 @@ import { classifyProviderError, getErrorFromUnknown } from "@mastra/core/error";
79
81
  import { Knowledge, knowledgeMemoryScopes } from "@mastra/core/knowledge";
80
82
  import { Mastra } from "@mastra/core/mastra";
81
83
  import { defaultNotificationDeliveryDecision, readNotificationRoutingRequirement } from "@mastra/core/notifications";
82
- import { AgentsMDInjector, CyberRefusalHandler, ProviderHistoryCompat, StreamErrorRetryProcessor, createBackgroundWorkSignalProcessor, isBadRequestError } from "@mastra/core/processors";
84
+ import { AgentsMDInjector, CyberRefusalHandler, ProviderHistoryCompat, createBackgroundWorkSignalProcessor, isBadRequestError } from "@mastra/core/processors";
83
85
  import { RequestContext } from "@mastra/core/request-context";
84
86
  import { TaskSignalProvider } from "@mastra/core/signals";
85
87
  import { MastraCompositeStore } from "@mastra/core/storage";
@@ -721,6 +723,7 @@ async function createMastraCodeAgentController(config) {
721
723
  const resolveTenantSessionModel = withCredentialTenantPreparation(async (ctx) => {
722
724
  const controller = ctx.requestContext.get("controller");
723
725
  const hasSessionLevel = isThinkingLevelSetting(controller?.state?.thinkingLevel);
726
+ setHostModelRoute(ctx.requestContext, await config?.resolveModelRoute?.(ctx));
724
727
  return getDynamicModel(ctx, config?.settingsPath, {
725
728
  modeless,
726
729
  defaultThinkingLevel: hasSessionLevel ? void 0 : await config?.resolveDefaultThinkingLevel?.(ctx)
@@ -837,7 +840,7 @@ async function createMastraCodeAgentController(config) {
837
840
  errorProcessors: [
838
841
  new ProviderHistoryCompat(),
839
842
  new CyberRefusalHandler(),
840
- new StreamErrorRetryProcessor({ matchers: [
843
+ new RouteAwareStreamErrorRetryProcessor({ matchers: [
841
844
  {
842
845
  match: isStreamCutAfterResponse,
843
846
  maxRetries: 0
@@ -0,0 +1,75 @@
1
+ import { z } from 'zod';
2
+ import type { ThinkingLevelSetting } from './thinking.js';
3
+ export declare const MODEL_FALLBACK_PART_TYPE: 'data-mastracode-model-fallback';
4
+ export declare const MODEL_FALLBACK_STATE_KEY: 'mastracodePendingModelFallback';
5
+ declare const modelFallbackReasonSchema: z.ZodEnum<{
6
+ "persistent-outage": "persistent-outage";
7
+ "pool-exhausted": "pool-exhausted";
8
+ }>;
9
+ export type ModelFallbackReason = z.infer<typeof modelFallbackReasonSchema>;
10
+ declare const modelRouteFailureSchema: z.ZodObject<{
11
+ kind: z.ZodEnum<{
12
+ auth: "auth";
13
+ context_overflow: "context_overflow";
14
+ invalid_request: "invalid_request";
15
+ model_rejected: "model_rejected";
16
+ quota: "quota";
17
+ rate_limited: "rate_limited";
18
+ timeout: "timeout";
19
+ tool_history_rejected: "tool_history_rejected";
20
+ unavailable: "unavailable";
21
+ unknown: "unknown";
22
+ }>;
23
+ }, z.core.$strip>;
24
+ export type ModelRouteFailure = z.infer<typeof modelRouteFailureSchema>;
25
+ export declare const pendingModelFallbackSchema: z.ZodObject<{
26
+ fromEntryId: z.ZodString;
27
+ toEntryId: z.ZodString;
28
+ toModelId: z.ZodString;
29
+ threadId: z.ZodOptional<z.ZodString>;
30
+ reason: z.ZodEnum<{
31
+ "persistent-outage": "persistent-outage";
32
+ "pool-exhausted": "pool-exhausted";
33
+ }>;
34
+ at: z.ZodString;
35
+ }, z.core.$strip>;
36
+ export type PendingModelFallback = z.infer<typeof pendingModelFallbackSchema>;
37
+ export declare function parsePendingModelFallback(value: unknown): PendingModelFallback | null;
38
+ declare const modelFallbackPartSchema: z.ZodObject<{
39
+ from: z.ZodObject<{
40
+ entryId: z.ZodString;
41
+ label: z.ZodString;
42
+ }, z.core.$strip>;
43
+ to: z.ZodObject<{
44
+ entryId: z.ZodString;
45
+ label: z.ZodString;
46
+ }, z.core.$strip>;
47
+ reason: z.ZodEnum<{
48
+ "persistent-outage": "persistent-outage";
49
+ "pool-exhausted": "pool-exhausted";
50
+ }>;
51
+ at: z.ZodCatch<z.ZodString>;
52
+ failure: z.ZodCatch<z.ZodOptional<z.ZodObject<{
53
+ kind: z.ZodEnum<{
54
+ auth: "auth";
55
+ context_overflow: "context_overflow";
56
+ invalid_request: "invalid_request";
57
+ model_rejected: "model_rejected";
58
+ quota: "quota";
59
+ rate_limited: "rate_limited";
60
+ timeout: "timeout";
61
+ tool_history_rejected: "tool_history_rejected";
62
+ unavailable: "unavailable";
63
+ unknown: "unknown";
64
+ }>;
65
+ }, z.core.$strip>>>;
66
+ }, z.core.$strip>;
67
+ export type ModelFallbackPartData = z.infer<typeof modelFallbackPartSchema>;
68
+ export declare function modelFallbackNoticeText(data: ModelFallbackPartData, modelName?: (label: string) => string): string;
69
+ export interface ModelFallback {
70
+ modelId: string;
71
+ thinkingLevel?: ThinkingLevelSetting;
72
+ }
73
+ export declare function parseModelFallbackPart(data: unknown): ModelFallbackPartData | null;
74
+ export {};
75
+ //# sourceMappingURL=model-fallback.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { PROVIDER_FAILURE_KINDS } from "@mastra/core/error";
2
+ import { z } from "zod";
3
+ // src/model-fallback.ts
4
+ const MODEL_FALLBACK_PART_TYPE = "data-mastracode-model-fallback";
5
+ const MODEL_FALLBACK_STATE_KEY = "mastracodePendingModelFallback";
6
+ const modelFallbackReasonSchema = z.enum(["pool-exhausted", "persistent-outage"]);
7
+ const REASON_CLAUSE = {
8
+ "pool-exhausted": (model) => `${model} failed`,
9
+ "persistent-outage": (model) => `${model} keeps failing`
10
+ };
11
+ const modelRouteFailureSchema = z.object({ kind: z.enum(PROVIDER_FAILURE_KINDS) });
12
+ const pendingModelFallbackSchema = z.object({
13
+ fromEntryId: z.string().min(1),
14
+ toEntryId: z.string().min(1),
15
+ toModelId: z.string().min(1),
16
+ threadId: z.string().optional(),
17
+ reason: modelFallbackReasonSchema,
18
+ at: z.string()
19
+ });
20
+ function parsePendingModelFallback(value) {
21
+ return pendingModelFallbackSchema.safeParse(value).data ?? null;
22
+ }
23
+ const routeEndpointSchema = z.object({
24
+ entryId: z.string(),
25
+ label: z.string()
26
+ });
27
+ const modelFallbackPartSchema = z.object({
28
+ from: routeEndpointSchema,
29
+ to: routeEndpointSchema,
30
+ reason: modelFallbackReasonSchema,
31
+ at: z.string().catch(""),
32
+ failure: modelRouteFailureSchema.optional().catch(void 0)
33
+ });
34
+ const FAILURE_CLAUSE = {
35
+ rate_limited: (model) => `${model} is rate-limited`,
36
+ quota: (model) => `${model} is out of credits or quota`,
37
+ auth: (model) => `${model} has missing or invalid credentials`,
38
+ unavailable: (model) => `${model} is unavailable`,
39
+ timeout: (model) => `${model} timed out`,
40
+ model_rejected: (model) => `${model} was not found by its provider`
41
+ };
42
+ function modelFallbackNoticeText(data, modelName = (label) => label) {
43
+ return `${((data.failure && FAILURE_CLAUSE[data.failure.kind]) ?? REASON_CLAUSE[data.reason])(modelName(data.from.label))}, switched to ${modelName(data.to.label)}`;
44
+ }
45
+ function parseModelFallbackPart(data) {
46
+ return modelFallbackPartSchema.safeParse(data).data ?? null;
47
+ }
48
+ export { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText, parseModelFallbackPart, parsePendingModelFallback, pendingModelFallbackSchema };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Rules for the extra headers a custom OpenAI-compatible provider sends.
3
+ *
4
+ * This module imports nothing at runtime, so settings parsing, the TUI and the
5
+ * Factory routes can validate headers without loading the AI SDK.
6
+ */
7
+ import type { CustomProviderAuthScheme } from './settings.js';
8
+ /** The most custom headers one provider may send. */
9
+ export declare const MAX_CUSTOM_PROVIDER_HEADERS = 20;
10
+ /** The longest custom header value accepted, in characters. */
11
+ export declare const MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH = 4096;
12
+ /**
13
+ * Header names a custom header may never use, in lower case. The HTTP client
14
+ * owns these, and a wrong value breaks or smuggles the request. The header the
15
+ * auth scheme writes is refused as well, see {@link customProviderAuthHeaderName}.
16
+ */
17
+ export declare const REFUSED_CUSTOM_PROVIDER_HEADER_NAMES: readonly string[];
18
+ /**
19
+ * A C0 or C1 control character, including the ESC and CSI that start terminal
20
+ * escape sequences. Text from an endpoint or a request body is printed in the
21
+ * TUI, so every place that shows it uses this one definition. Not global, so
22
+ * `test` keeps no state; derive a global copy for `replace`.
23
+ */
24
+ export declare const CONTROL_CHARACTER_PATTERN: RegExp;
25
+ /**
26
+ * The header the auth scheme writes the key into. A missing scheme means
27
+ * `bearer`, which is how providers saved before schemes existed authenticate.
28
+ */
29
+ export declare function customProviderAuthHeaderName(authScheme: CustomProviderAuthScheme | undefined): string;
30
+ /** Whether a value read from settings or a request body is a known auth scheme. */
31
+ export declare function isCustomProviderAuthScheme(value: unknown): value is CustomProviderAuthScheme;
32
+ /**
33
+ * Why `headers` cannot be saved with `authScheme`, or undefined when they can.
34
+ *
35
+ * An entry without `value` is accepted, because an edit may keep a saved value
36
+ * by naming the header only. The caller decides whether a value is required.
37
+ * Entries are typed loosely because they often come straight from a request
38
+ * body, where a name or value may not be a string.
39
+ */
40
+ export declare function customProviderHeaderProblem(headers: ReadonlyArray<{
41
+ name: unknown;
42
+ value?: unknown;
43
+ }>, authScheme: CustomProviderAuthScheme | undefined): string | undefined;
44
+ /**
45
+ * Merge header maps in order. Names are compared ignoring case and a later
46
+ * entry replaces an earlier one, keeping the later spelling. `fetch` would
47
+ * otherwise join `X-Foo` and `x-foo` into one comma-separated value.
48
+ */
49
+ export declare function mergeHeadersIgnoringCase(...sources: Array<Record<string, string> | undefined>): Record<string, string>;
50
+ //# sourceMappingURL=custom-provider-headers.d.ts.map
@@ -0,0 +1,112 @@
1
+ // src/onboarding/custom-provider-headers.ts
2
+ /** The most custom headers one provider may send. */
3
+ const MAX_CUSTOM_PROVIDER_HEADERS = 20;
4
+ /** The longest custom header value accepted, in characters. */
5
+ const MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH = 4096;
6
+ /**
7
+ * Header names a custom header may never use, in lower case. The HTTP client
8
+ * owns these, and a wrong value breaks or smuggles the request. The header the
9
+ * auth scheme writes is refused as well, see {@link customProviderAuthHeaderName}.
10
+ */
11
+ const REFUSED_CUSTOM_PROVIDER_HEADER_NAMES = [
12
+ "host",
13
+ "content-length",
14
+ "content-type",
15
+ "transfer-encoding",
16
+ "connection",
17
+ "keep-alive",
18
+ "upgrade",
19
+ "expect",
20
+ "te",
21
+ "trailer",
22
+ "proxy-connection"
23
+ ];
24
+ /** The `token` grammar of RFC 9110, which every header name must match. */
25
+ const HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
26
+ /**
27
+ * Characters outside tab, printable ASCII and printable Latin-1. The HTTP
28
+ * client refuses ASCII control characters and anything above 0xFF at call
29
+ * time, so such a value would fail every request instead of failing when it
30
+ * is saved. The C1 controls (0x80 to 0x9F) are refused too: a plain value is
31
+ * shown in lists, and U+009B starts an escape sequence on terminals that act
32
+ * on 8-bit controls.
33
+ */
34
+ const INVALID_HEADER_VALUE_CHARACTER = /[^\t\x20-\x7e\xa0-\xff]/;
35
+ /** The longest part of a refused header name repeated in the problem text. */
36
+ const MAX_QUOTED_NAME_LENGTH = 100;
37
+ /**
38
+ * A C0 or C1 control character, including the ESC and CSI that start terminal
39
+ * escape sequences. Text from an endpoint or a request body is printed in the
40
+ * TUI, so every place that shows it uses this one definition. Not global, so
41
+ * `test` keeps no state; derive a global copy for `replace`.
42
+ */
43
+ const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f-\u009f]/;
44
+ /**
45
+ * A refused header name made safe to show. The name may come from a request
46
+ * body and end up in a terminal, so it is cut short and its control
47
+ * characters become spaces.
48
+ */
49
+ function quotableName(name) {
50
+ const shown = name.slice(0, MAX_QUOTED_NAME_LENGTH).replace(new RegExp(CONTROL_CHARACTER_PATTERN.source, "g"), " ");
51
+ return name.length > MAX_QUOTED_NAME_LENGTH ? `${shown}...` : shown;
52
+ }
53
+ /**
54
+ * The header the auth scheme writes the key into. A missing scheme means
55
+ * `bearer`, which is how providers saved before schemes existed authenticate.
56
+ */
57
+ function customProviderAuthHeaderName(authScheme) {
58
+ return authScheme === "x-api-key" ? "x-api-key" : "Authorization";
59
+ }
60
+ /** Whether a value read from settings or a request body is a known auth scheme. */
61
+ function isCustomProviderAuthScheme(value) {
62
+ return value === "bearer" || value === "x-api-key";
63
+ }
64
+ /**
65
+ * Why `headers` cannot be saved with `authScheme`, or undefined when they can.
66
+ *
67
+ * An entry without `value` is accepted, because an edit may keep a saved value
68
+ * by naming the header only. The caller decides whether a value is required.
69
+ * Entries are typed loosely because they often come straight from a request
70
+ * body, where a name or value may not be a string.
71
+ */
72
+ function customProviderHeaderProblem(headers, authScheme) {
73
+ if (!Array.isArray(headers)) return "Custom headers must be a list.";
74
+ if (headers.length > 20) return `A provider can send at most 20 custom headers.`;
75
+ const authHeader = customProviderAuthHeaderName(authScheme).toLowerCase();
76
+ const seen = /* @__PURE__ */ new Set();
77
+ for (const header of headers) {
78
+ if (typeof header !== "object" || header === null) return "Each custom header needs a name and a value.";
79
+ const { name, value } = header;
80
+ if (typeof name !== "string") return "Each custom header name must be text.";
81
+ if (!HEADER_NAME_PATTERN.test(name)) return `"${quotableName(name)}" is not a valid header name.`;
82
+ const lowerName = name.toLowerCase();
83
+ if (REFUSED_CUSTOM_PROVIDER_HEADER_NAMES.includes(lowerName)) return `The ${name} header is set by the HTTP client and cannot be sent as a custom header.`;
84
+ if (lowerName === authHeader) return `The ${name} header carries the API key for this auth scheme and cannot be sent as a custom header.`;
85
+ if (seen.has(lowerName)) return `The ${name} header is listed more than once.`;
86
+ seen.add(lowerName);
87
+ if (value === void 0) continue;
88
+ if (typeof value !== "string") return `The ${name} header value must be text.`;
89
+ if (value.trim().length === 0) return `The ${name} header has no value.`;
90
+ if (value.length > 4096) return `The ${name} header value is longer than ${MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH} characters.`;
91
+ if (/[\r\n]/.test(value)) return `The ${name} header value cannot contain a line break.`;
92
+ if (INVALID_HEADER_VALUE_CHARACTER.test(value)) return `The ${name} header value can only hold printable characters up to U+00FF.`;
93
+ }
94
+ }
95
+ /**
96
+ * Merge header maps in order. Names are compared ignoring case and a later
97
+ * entry replaces an earlier one, keeping the later spelling. `fetch` would
98
+ * otherwise join `X-Foo` and `x-foo` into one comma-separated value.
99
+ */
100
+ function mergeHeadersIgnoringCase(...sources) {
101
+ const merged = /* @__PURE__ */ new Map();
102
+ for (const source of sources) {
103
+ if (!source) continue;
104
+ for (const [name, value] of Object.entries(source)) {
105
+ const key = name.toLowerCase();
106
+ merged.delete(key);
107
+ merged.set(key, [name, value]);
108
+ }
109
+ }
110
+ return Object.fromEntries(merged.values());
111
+ }
112
+ export { CONTROL_CHARACTER_PATTERN, MAX_CUSTOM_PROVIDER_HEADERS, MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH, REFUSED_CUSTOM_PROVIDER_HEADER_NAMES, customProviderAuthHeaderName, customProviderHeaderProblem, isCustomProviderAuthScheme, mergeHeadersIgnoringCase };
@@ -5,11 +5,22 @@ import { getCustomProviderId } from "./settings.js";
5
5
  * providers. Shared by the TUI `/custom-providers` command and the web
6
6
  * settings routes — no UI dependencies.
7
7
  */
8
+ /**
9
+ * Trim the fields a user typed, header names and values included, the way
10
+ * `parseCustomProviders` reads them back. Callers validate headers first.
11
+ */
8
12
  function normalizeProvider(input) {
13
+ const headers = input.headers?.map((header) => ({
14
+ ...header,
15
+ name: header.name.trim(),
16
+ value: header.value.trim()
17
+ }));
9
18
  return {
10
19
  name: input.name.trim(),
11
20
  url: input.url.trim(),
12
21
  apiKey: input.apiKey?.trim() || void 0,
22
+ ...input.authScheme ? { authScheme: input.authScheme } : {},
23
+ ...headers?.length ? { headers } : {},
13
24
  models: [...new Set(input.models.map((model) => model.trim()).filter(Boolean))]
14
25
  };
15
26
  }