@mastra/code-sdk 1.9.0 → 1.10.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.
Files changed (53) hide show
  1. package/README.md +23 -0
  2. package/dist/agent-connections/tools.d.ts.map +1 -1
  3. package/dist/agent-connections/tools.js +5 -5
  4. package/dist/agent-connections/tools.js.map +1 -1
  5. package/dist/analytics.d.ts.map +1 -1
  6. package/dist/analytics.js +2 -3
  7. package/dist/analytics.js.map +1 -1
  8. package/dist/auth/account-rotation-processor.d.ts.map +1 -1
  9. package/dist/auth/account-rotation-processor.js +17 -10
  10. package/dist/auth/account-rotation-processor.js.map +1 -1
  11. package/dist/auth/providers/kimi-coding.d.ts.map +1 -1
  12. package/dist/auth/providers/kimi-coding.js +1 -2
  13. package/dist/auth/providers/kimi-coding.js.map +1 -1
  14. package/dist/auth/providers/openai-codex.d.ts +1 -1
  15. package/dist/auth/providers/openai-codex.d.ts.map +1 -1
  16. package/dist/auth/providers/openai-codex.js +7 -19
  17. package/dist/auth/providers/openai-codex.js.map +1 -1
  18. package/dist/auth/storage.js +3 -3
  19. package/dist/auth/storage.js.map +1 -1
  20. package/dist/experimental-agent.d.ts +11 -0
  21. package/dist/experimental-agent.d.ts.map +1 -0
  22. package/dist/experimental-agent.js +36 -0
  23. package/dist/experimental-agent.js.map +1 -0
  24. package/dist/goal-manager.d.ts.map +1 -1
  25. package/dist/goal-manager.js +3 -4
  26. package/dist/goal-manager.js.map +1 -1
  27. package/dist/headless/run-mc.d.ts.map +1 -1
  28. package/dist/headless/run-mc.js +1 -1
  29. package/dist/headless/run-mc.js.map +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +23 -7
  32. package/dist/index.js.map +1 -1
  33. package/dist/knowledge-inspector.d.ts.map +1 -1
  34. package/dist/knowledge-inspector.js +1 -2
  35. package/dist/knowledge-inspector.js.map +1 -1
  36. package/dist/onboarding/settings.d.ts +9 -0
  37. package/dist/onboarding/settings.d.ts.map +1 -1
  38. package/dist/onboarding/settings.js +36 -4
  39. package/dist/onboarding/settings.js.map +1 -1
  40. package/dist/plugins/loader.d.ts.map +1 -1
  41. package/dist/plugins/loader.js +1 -2
  42. package/dist/plugins/loader.js.map +1 -1
  43. package/dist/process-memory-diagnostics.d.ts.map +1 -1
  44. package/dist/process-memory-diagnostics.js +1 -2
  45. package/dist/process-memory-diagnostics.js.map +1 -1
  46. package/dist/tools/workflows/ephemeral-memory.d.ts +21 -0
  47. package/dist/tools/workflows/ephemeral-memory.d.ts.map +1 -1
  48. package/dist/tools/workflows/ephemeral-memory.js +1 -2
  49. package/dist/tools/workflows/ephemeral-memory.js.map +1 -1
  50. package/dist/utils/signals-pubsub.d.ts.map +1 -1
  51. package/dist/utils/signals-pubsub.js +1 -2
  52. package/dist/utils/signals-pubsub.js.map +1 -1
  53. package/package.json +11 -11
@@ -1 +1 @@
1
- {"version":3,"file":"account-rotation-processor.js","names":[],"sources":["../../src/auth/account-rotation-processor.ts"],"sourcesContent":["/**\n * Error-driven rotation across a provider's OAuth account registry.\n *\n * When the active account cannot serve a request (rate limit, quota\n * exhaustion, dead token, persistent outage), the next account in insertion\n * order is selected for the request and the request retried. OAuth fetch\n * wrappers read that request-scoped selection on every HTTP attempt, so\n * concurrent runs can't swap each other's credentials. Every switch is\n * persisted as a non-transient `data-mastracode-account-switch` part so it\n * shows in the transcript and survives history reload.\n *\n * Two classes, two lanes — the split is load-bearing. The processor runner\n * walks `[...inputProcessors, ...outputProcessors, ...errorProcessors]` when\n * running `processAPIError`, so a processor registered in the input lane that\n * also implemented `processAPIError` would run BEFORE\n * `StreamErrorRetryProcessor` and hop on 5xx errors before transient retries\n * had a chance. `AccountRotationProcessor` therefore implements\n * `processAPIError` only and is registered in `errorProcessors` after\n * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements\n * `processInput` only and is registered in `inputProcessors`.\n */\nimport { TripWire } from '@mastra/core/agent';\nimport type { ProcessAPIErrorArgs, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';\n\nimport { resolveCredentialStore } from '../agents/credential-resolver.js';\nimport { listResolvableModePacks, resolveModel, resolveRequestThinkingLevel } from '../agents/model.js';\nimport { resolveModePackFallbackChain } from '../onboarding/packs.js';\nimport { findModePackForModel, loadSettings, resolveModePackModels } from '../onboarding/settings.js';\nimport {\n getRequestAccountSelection,\n markRequestAccountRoutingExhausted,\n setRequestAccountSelection,\n} from './account-routing-context.js';\nimport { ProviderAuthRequiredError, PROVIDER_AUTH_REQUIRED_ERROR } from './provider-auth-error.js';\nimport { getOAuthProviders } from './storage.js';\nimport type { CredentialStore, OAuthAccountRecord } from './types.js';\n\nexport const ACCOUNT_SWITCH_PART_TYPE = 'data-mastracode-account-switch';\n\n/** Labels and instance ids only — never token material (do-not list). */\nexport interface AccountSwitchPartData {\n provider: string;\n from: { id: string; label: string } | null;\n to: { id: string; label: string } | null;\n reason:\n | 'rate-limit'\n | 'quota-exhausted'\n | 'auth-failed'\n | 'pool-exhausted'\n | 'persistent-outage'\n | 'preferred-routing'\n | 'starting-on-account';\n at: string;\n /**\n * Set on a `to: null` part when a route pinned to a single account reported\n * that account unusable. The provider's other subscriptions were never\n * consulted (A12), so \"all accounts unavailable\" would misreport what\n * happened.\n */\n exclusive?: boolean;\n}\n\n/** The store surface rotation needs; `AuthStorage` satisfies it structurally. */\nexport type RotationCredentialStore = CredentialStore & {\n /**\n * Force one refresh of the active account's tokens regardless of expiry\n * (401/403 path — a rejected-but-unexpired token usually means clock skew\n * or a refresh race). `AuthStorage` provides it; deployed per-tenant stores\n * don't, and the auth path degrades to plain rotation (which itself no-ops\n * without registry methods).\n */\n forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;\n};\n\n/** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */\nconst KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map(provider => provider.id));\n\n/** Hostname suffixes → provider ids, for `APICallError.url`. */\nconst PROVIDER_HOST_PATTERNS: Array<[RegExp, string]> = [\n [/(^|\\.)api\\.anthropic\\.com$/i, 'anthropic'],\n [/(^|\\.)api\\.kimi\\.com$/i, 'kimi-for-coding'],\n [/(^|\\.)api\\.x\\.ai$/i, 'xai'],\n [/(^|\\.)chatgpt\\.com$/i, 'openai-codex'],\n [/(^|\\.)backend-api\\.codex\\.ai$/i, 'openai-codex'],\n [/(^|\\.)githubcopilot\\.com$/i, 'github-copilot'],\n [/(^|\\.)api\\.github\\.com$/i, 'github-copilot'],\n];\n\n/**\n * Provider usage/quota-limit wording (locked Q7 bucket 1). Statuses 429/402\n * are matched before this; some providers deliver quota errors as plain 400s,\n * which only the message reveals. Deliberately restricted to unambiguous\n * quota phrases — a generic \"exceeded your … limit\" can appear on non-quota\n * client errors (request size, context length) that must never rotate.\n */\nconst USAGE_LIMIT_MESSAGE_PATTERN =\n /usage (?:limit|cap)|insufficient[_ ]quota|quota (?:exceeded|exhausted|reached)|exceeded (?:your )?current quota|insufficient (?:balance|credits?)|credits? exhausted|rate limit (?:exceeded|reached)|weekly limit|monthly limit/i;\n\nconst NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'EPIPE',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\n\nconst NETWORK_MESSAGE_PATTERN =\n /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;\n\nconst MAX_CAUSE_DEPTH = 4;\n\n/** Persisted data-part type for a fallback-pack hop. */\nexport const PACK_FALLBACK_PART_TYPE = 'data-mastracode-pack-fallback' as const;\n\n/**\n * Payload of a pack-fallback part: the pack the cascade is leaving, the pack\n * core's fallback array advances to, and why. Labels and pack ids only —\n * never credential material.\n */\nexport interface PackFallbackPartData {\n from: { packId: string; label: string };\n to: { packId: string; label: string };\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\n/**\n * Session-state key the processor sets when a pack hop happens. The TUI\n * listens for it on the typed `state_changed` controller event (data parts\n * never ride controller message events) and applies thread stickiness.\n */\nexport const PACK_FALLBACK_STATE_KEY = 'mastracodePendingPackFallback' as const;\n\n/** Payload written to session state under PACK_FALLBACK_STATE_KEY. */\nexport interface PendingPackFallback {\n fromPackId: string;\n toPackId: string;\n /** Landed pack's model for the mode the cascade is serving. */\n toModelId: string;\n /** Originating thread. Absent only on pending hops written by older clients. */\n threadId?: string;\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\nexport type RotationClassification =\n | { kind: 'rotate'; reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' }\n | { kind: 'hop' }\n | { kind: 'never' };\n\nfunction isErrorWithCode(error: unknown): error is { code?: unknown } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\nfunction readErrorStatus(error: unknown): number | undefined {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n const { statusCode, status } = current as { statusCode?: unknown; status?: unknown };\n if (typeof statusCode === 'number') return statusCode;\n if (typeof status === 'number') return status;\n current = (current as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\nfunction isProviderAuthRequiredError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n current instanceof ProviderAuthRequiredError ||\n (current instanceof Error && current.name === PROVIDER_AUTH_REQUIRED_ERROR)\n ) {\n return true;\n }\n if (typeof current !== 'object') break;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\n/** Concatenate the error's message with its cause chain (bounded). */\nfunction collectErrorText(error: unknown): string {\n const parts: string[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (current instanceof Error) {\n parts.push(current.message);\n current = current.cause;\n } else if (typeof current === 'object' && 'message' in current) {\n const message = (current as { message?: unknown }).message;\n if (typeof message === 'string') parts.push(message);\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return parts.join(' | ');\n}\n\nfunction isNetworkErrorLike(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n isErrorWithCode(current) &&\n typeof current.code === 'string' &&\n NETWORK_ERROR_CODES.has(current.code.toUpperCase())\n ) {\n return true;\n }\n if (current instanceof Error) {\n if (NETWORK_MESSAGE_PATTERN.test(current.message)) return true;\n current = current.cause;\n } else if (typeof current === 'object') {\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return false;\n}\n\n/**\n * The locked Q7 taxonomy. 429/402/usage-limit rotate immediately (429 is not\n * covered by any transient matcher, so it arrives here on first occurrence);\n * 401/403 and `ProviderAuthRequiredError` rotate after one forced refresh;\n * 5xx/network hop only when the transient retry budget is already spent (they\n * reach this processor because `StreamErrorRetryProcessor` declined); 400 and\n * everything unknown never touch the registry.\n */\nexport function classifyRotationError(error: unknown): RotationClassification {\n if (isProviderAuthRequiredError(error)) {\n return { kind: 'rotate', reason: 'auth-failed' };\n }\n\n const status = readErrorStatus(error);\n\n if (status === 429) return { kind: 'rotate', reason: 'rate-limit' };\n if (status === 402) return { kind: 'rotate', reason: 'quota-exhausted' };\n if (status === 401 || status === 403) return { kind: 'rotate', reason: 'auth-failed' };\n if (status !== undefined && status >= 500 && status < 600) return { kind: 'hop' };\n\n // Quota wording only rotates when it co-occurs with a statusless or 400\n // error — the shapes providers actually use for message-only quota\n // failures. Any other status keeps its own classification above (401/403\n // auth, 5xx outage hop, 404/422 never), so limit-ish text riding a\n // non-quota client error can no longer burn the whole pool.\n if (status === undefined || status === 400) {\n if (USAGE_LIMIT_MESSAGE_PATTERN.test(collectErrorText(error))) {\n return { kind: 'rotate', reason: 'quota-exhausted' };\n }\n }\n if (isNetworkErrorLike(error)) return { kind: 'hop' };\n\n return { kind: 'never' };\n}\n\n/** Provider id off a router model id: `mastracode/<provider>/<model>` or `<provider>/<model>`. */\nexport function providerFromModelId(modelId: string): string | undefined {\n const segments = modelId.replace(/^mastracode\\//, '').split('/');\n const providerId = segments[0];\n if (providerId === 'openai') return 'openai-codex';\n return providerId && KNOWN_PROVIDER_IDS.has(providerId) ? providerId : undefined;\n}\n\nfunction providerFromHost(hostname: string): string | undefined {\n for (const [pattern, providerId] of PROVIDER_HOST_PATTERNS) {\n if (pattern.test(hostname)) return providerId;\n }\n return undefined;\n}\n\n/**\n * Identify the provider an error came from: the request URL's hostname\n * (`APICallError.url`, cause chain included), falling back to the router\n * model id. Unknown → undefined (caller treats as never-rotate).\n */\nexport function providerFromError(error: unknown): string | undefined {\n const causeChain: object[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n causeChain.push(current);\n current = (current as { cause?: unknown }).cause;\n }\n\n // A request URL identifies the provider that actually handled the failed\n // call. Check every supported URL field throughout the cause chain before\n // falling back to router model metadata, which may describe the original\n // session model rather than the active cascade entry.\n for (const item of causeChain) {\n const urls = [\n (item as { url?: unknown }).url,\n (item as { requestURL?: unknown }).requestURL,\n (item as { requestUrl?: unknown }).requestUrl,\n ];\n for (const url of urls) {\n if (typeof url !== 'string') continue;\n try {\n const providerId = providerFromHost(new URL(url).hostname);\n if (providerId) return providerId;\n } catch {\n // Not a parseable URL — try the other fields and causes.\n }\n }\n }\n\n for (const item of causeChain) {\n const modelId = (item as { modelId?: unknown }).modelId;\n if (typeof modelId !== 'string') continue;\n const providerId = providerFromModelId(modelId);\n if (providerId) return providerId;\n }\n return undefined;\n}\n\nfunction getTriedInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.triedInstances;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.triedInstances = created;\n return created;\n}\n\nfunction getForcedRefreshInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.forcedAuthRefresh;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.forcedAuthRefresh = created;\n return created;\n}\n\n/** Friendly names for the part/notice copy (display only — never auth data). */\nexport const PROVIDER_DISPLAY_NAMES: Record<string, string> = {\n anthropic: 'Anthropic',\n 'kimi-for-coding': 'Kimi',\n 'openai-codex': 'Codex',\n 'github-copilot': 'GitHub Copilot',\n xai: 'xAI',\n};\n\nconst REASON_TEXT: Record<Exclude<AccountSwitchPartData['reason'], 'starting-on-account'>, string> = {\n 'rate-limit': 'rate limit',\n 'quota-exhausted': 'quota exhausted',\n 'auth-failed': 'auth failed',\n 'pool-exhausted': 'pool exhausted',\n 'persistent-outage': 'persistent outage',\n 'preferred-routing': 'subscription routing',\n};\n\n/** Validates untrusted `reason` values (e.g. persisted message parts). */\nexport function isAccountSwitchReason(value: unknown): value is AccountSwitchPartData['reason'] {\n return (\n value === 'starting-on-account' ||\n // Own-property check: `in` would accept prototype names like 'toString',\n // which would then interpolate the inherited function into the notice text.\n (typeof value === 'string' && Object.prototype.hasOwnProperty.call(REASON_TEXT, value))\n );\n}\n\n/**\n * One-line transcript copy for a switch part. Shared by the live `info`\n * controller event (the TUI shows controller `info` events as transcript\n * lines, and no message event carries data parts mid-run) and by the TUI's\n * history rendering of the persisted part — one formatter, identical text.\n */\nexport function accountSwitchNoticeText(data: AccountSwitchPartData): string {\n const provider = PROVIDER_DISPLAY_NAMES[data.provider] ?? data.provider;\n if (data.reason === 'starting-on-account' && data.to) {\n return `Starting on ${provider} account: ${data.to.label}`;\n }\n const reason = data.reason === 'starting-on-account' ? data.reason : REASON_TEXT[data.reason];\n if (data.to === null) {\n // A12: a targeted route reports *its* account, not the pool — the other\n // subscriptions were never tried, so \"all accounts unavailable\" would be\n // wrong and would read as if the pool had been walked.\n if (data.exclusive) {\n return `Pinned ${provider} account unavailable (${reason})`;\n }\n return `All ${provider} accounts unavailable (${reason})`;\n }\n const from = data.from?.label ?? 'unknown';\n return `Switched ${provider} account: ${from} → ${data.to.label} (${reason})`;\n}\n\n/** Transcript line for a pack-fallback hop; shared by the live info event and the TUI's history render. */\nexport function packFallbackNoticeText(data: PackFallbackPartData): string {\n const reason = REASON_TEXT[data.reason] ?? data.reason;\n return `Switched model pack: ${data.from.label} → ${data.to.label} (${reason})`;\n}\n\n/**\n * Whether a persisted pack-fallback reason is one this build understands.\n * `REASON_TEXT` also covers the account-switch reasons, so the notice text\n * alone would happily render a foreign value such as `rate-limit` as a\n * pack-fallback reason; history parsed from another build's part must be\n * rejected instead.\n */\nexport function isPackFallbackReason(value: unknown): value is PackFallbackPartData['reason'] {\n return value === 'pool-exhausted' || value === 'persistent-outage';\n}\n\nasync function emitAccountSwitchPart(\n args: Pick<ProcessAPIErrorArgs, 'writer' | 'requestContext'> | Pick<ProcessInputArgs, 'writer' | 'requestContext'>,\n data: AccountSwitchPartData,\n): Promise<void> {\n // Non-transient on purpose (contrast the transient tool-progress parts):\n // switches must persist into the assistant message and render from history.\n await args.writer?.custom({\n type: ACCOUNT_SWITCH_PART_TYPE,\n data,\n });\n // Data parts surface in the TUI only on history reload; emit the same line\n // as a controller `info` event so the switch is visible live (precedent:\n // emitTransientRetry emits controller events from the retry matcher).\n const controllerContext = args.requestContext?.get('controller') as\n | { emitEvent?: (event: { type: 'info'; message: string }) => void }\n | undefined;\n controllerContext?.emitEvent?.({ type: 'info', message: accountSwitchNoticeText(data) });\n}\n\n/**\n * Provider of the model the controller session is currently running — the\n * fallback identification path for errors that carry neither a request URL\n * nor a model id (e.g. `ProviderAuthRequiredError` thrown by a fetch wrapper\n * before any HTTP request exists).\n */\nfunction providerFromSession(\n args: Pick<ProcessAPIErrorArgs, 'requestContext'> | Pick<ProcessInputArgs, 'requestContext'>,\n): string | undefined {\n const controller = args.requestContext?.get('controller') as { session?: { modelId?: unknown } } | undefined;\n const modelId = controller?.session?.modelId;\n return typeof modelId === 'string' ? providerFromModelId(modelId) : undefined;\n}\n\n/**\n * Rotates the active OAuth account on classified API errors.\n *\n * Registered in `errorProcessors` AFTER `StreamErrorRetryProcessor` — a\n * transient error reaching this processor means the transient budget is\n * spent, which is exactly the hop condition. Implements `processAPIError`\n * ONLY (see the file header for the runner-order rationale).\n */\n/** Cached per-request pack cascade (state.packCascade). */\ninterface PackCascade {\n packs: Array<{ packId: string; label: string }>;\n models: Record<string, Record<string, string>>;\n modeId: string;\n position: number;\n}\n\ninterface AccountRoute {\n packId: string;\n modelId: string;\n providerId: string;\n}\n\ntype RoutingProcessorArgs = Pick<ProcessAPIErrorArgs, 'requestContext' | 'state' | 'writer'> | ProcessInputArgs;\n\n/**\n * Controller-shaped accessors for a thread's routing metadata. Core supplies this\n * via `requestContext.get('controller')`; the TUI builds the same shape from its\n * session so both writers share one serialization key and one read source.\n */\nexport type RoutingControllerContext = {\n session?: { modelId?: unknown; modeId?: unknown };\n threadId?: unknown;\n getState?: () => Record<string, unknown>;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n getThreadSetting?: (key: string) => Promise<unknown>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n isThreadActive?: () => boolean;\n};\n\nfunction getRoutingController(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n): RoutingControllerContext | undefined {\n return args.requestContext?.get('controller') as RoutingControllerContext | undefined;\n}\n\n/**\n * A12: the account a pack/model route targets, or `undefined` when the route\n * is `Automatic` (no entry — insertion order, full pool rotation).\n *\n * A targeted route is *exclusive*: only that account may serve the route, so\n * rotation must never spill the request onto a sibling subscription's quota.\n * A heavy model on one subscription can burn that subscription's quota in\n * hours; spilling it into a second subscription defeats the point of having\n * one.\n */\nfunction getRouteTargetAccountId(settingsPath: string | undefined, route: AccountRoute | null): string | undefined {\n if (!route) return undefined;\n return loadSettings(settingsPath).models.packAccountPreferences?.[route.packId]?.[route.modelId];\n}\n\nfunction getRequestActiveAccount(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n store: CredentialStore,\n providerId: string,\n) {\n const selectedId = getRequestAccountSelection(args.requestContext, providerId);\n return (\n (selectedId ? store.listAccounts?.(providerId).find(account => account.id === selectedId) : undefined) ??\n store.getActiveAccount?.(providerId) ??\n store.listAccounts?.(providerId).find(account => account.active)\n );\n}\n\nfunction resolveAccountRoute(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n settingsPath?: string,\n explicit?: { packId: string; modelId: string },\n): AccountRoute | null {\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const pending = state?.mastracodePendingPackFallback as\n | { toPackId?: unknown; toModelId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toPackId === 'string' &&\n typeof pending.toModelId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const resolvedModelId =\n explicit?.modelId ??\n (pendingMatchesThread ? pending.toModelId : undefined) ??\n (typeof controller?.session?.modelId === 'string' ? controller.session.modelId : undefined);\n if (typeof resolvedModelId !== 'string' || resolvedModelId.length === 0) return null;\n const modelId = resolvedModelId;\n\n const settings = loadSettings(settingsPath);\n const packs = listResolvableModePacks(settings);\n const modeId =\n typeof controller?.session?.modeId === 'string' && controller.session.modeId.length > 0\n ? controller.session.modeId\n : 'build';\n const explicitPackId =\n explicit?.packId ??\n (pendingMatchesThread ? pending.toPackId : undefined) ??\n (typeof state?.activeModelPackId === 'string' ? state.activeModelPackId : settings.models.activeModelPackId);\n const pack = explicitPackId\n ? packs.find(candidate => candidate.id === explicitPackId)\n : findModePackForModel(settings, packs, modelId, modeId, undefined);\n if (!pack || resolveModePackModels(settings, pack)[modeId] !== modelId) return null;\n\n const providerId = providerFromModelId(modelId);\n return providerId ? { packId: pack.id, modelId, providerId } : null;\n}\n\n/**\n * A14: `Automatic` rotation starts *at* the persisted active account and walks\n * insertion order from there, wrapping once. The active account is the cursor\n * rotation last left at, so a turn that starts at index 0 regardless would\n * re-activate and re-try an account the previous turn already moved past —\n * which is the whole job the removed sticky-exclusion set was doing badly.\n * With no persisted active account the order is plain insertion order.\n */\nfunction orderAccountsFromActive(accounts: OAuthAccountRecord[], activeId: string | undefined) {\n const index = activeId === undefined ? -1 : accounts.findIndex(account => account.id === activeId);\n if (index <= 0) return accounts;\n return [...accounts.slice(index), ...accounts.slice(0, index)];\n}\n\nasync function applyPreferredAccountRoute(\n args: RoutingProcessorArgs,\n store: CredentialStore,\n settingsPath: string | undefined,\n route: AccountRoute,\n): Promise<boolean> {\n const preferredId = getRouteTargetAccountId(settingsPath, route);\n const accounts = store.listAccounts?.(route.providerId) ?? [];\n if (accounts.length === 0) return false;\n const tried = getTriedInstances(args.state);\n const unavailable = new Set(accounts.filter(account => tried.has(account.id)).map(account => account.id));\n const active = getRequestActiveAccount(args, store, route.providerId);\n const selected = // A12: a targeted route may use only the account it names. `Automatic`\n // keeps insertion order with full pool rotation (A10), starting from the\n // account the cursor already points at (A14).\n (\n preferredId\n ? accounts.filter(account => account.id === preferredId)\n : orderAccountsFromActive(accounts, active?.id)\n ).find(account => !unavailable.has(account.id));\n\n for (const accountId of unavailable) tried.add(accountId);\n if (!selected) {\n markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n\n if (active?.id === selected.id) {\n setRequestAccountSelection(args.requestContext, route.providerId, selected.id);\n return false;\n }\n // Activate before recording the request-scoped selection: a failed\n // activation must not leave the selection claiming an account that never\n // became the provider's active credential.\n const activated = store.activateAccount?.(route.providerId, selected.id) ?? selected;\n setRequestAccountSelection(args.requestContext, route.providerId, activated.id);\n\n await emitAccountSwitchPart(args, {\n provider: route.providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: activated.id, label: activated.label },\n reason: 'preferred-routing',\n at: new Date().toISOString(),\n });\n return true;\n}\n\nexport class AccountRotationProcessor implements Processor {\n readonly id = 'mastracode-account-rotation' as const;\n\n constructor(\n private readonly options: {\n credentialStore: RotationCredentialStore;\n maxProcessorRetries: number;\n settingsPath?: string;\n },\n ) {}\n\n async processAPIError(args: ProcessAPIErrorArgs): Promise<{ retry: boolean }> {\n const { error, state } = args;\n\n // Core runs error processors even after the shared retry budget is spent\n // and silently discards `retry: true` then (llm-execution-step.ts\n // canRetryError) — rotating the cursor or emitting a switch part for a\n // retry that will never run would lie to both auth.json and the\n // transcript. With a fallback chain configured, a bare `retry: false`\n // here would silently hop packs for an error we never classified, so the\n // chain gate surfaces the error instead.\n if (args.retryCount >= this.options.maxProcessorRetries) {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n // Classify before attributing: an error from a provider outside the OAuth\n // registry (API-key/router providers are valid pack members) still hops on\n // rotate/hop classes — there is just no account cursor to advance.\n const classification = classifyRotationError(error);\n // Q14: 400/unknown errors never rotate and never hop packs. With a chain\n // active, core's fallback array would still advance on a bare\n // `retry: false` (it advances on any thrown non-TripWire error), so the\n // gate converts that into a surfaced error instead of a silent hop.\n if (classification.kind === 'never') {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n const cascade = await this.getPackCascade(args);\n const currentPack = cascade?.packs[cascade.position];\n const cascadeModelId = currentPack ? cascade.models[currentPack.packId]?.[cascade.modeId] : undefined;\n const providerId =\n providerFromError(error) ??\n (typeof cascadeModelId === 'string' ? providerFromModelId(cascadeModelId) : undefined) ??\n (cascade ? undefined : providerFromSession(args));\n if (!providerId) {\n await this.emitPackFallbackPart(args, classification.kind === 'hop' ? 'persistent-outage' : 'pool-exhausted');\n return { retry: false };\n }\n\n // Deployed requests resolve the tenant-scoped store; local mode keeps the\n // host storage. Reading the host registry here would rotate or announce\n // host accounts for a tenant request. Annotated as the rotation surface:\n // `resolveCredentialStore` returns a plain CredentialStore, and the 401\n // path below uses the optional `forceRefreshActiveAccount` when the host\n // provides it.\n const store: RotationCredentialStore = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n const accounts = store.listAccounts?.(providerId) ?? [];\n const active = getRequestActiveAccount(args, store, providerId);\n const route =\n currentPack && typeof cascadeModelId === 'string'\n ? resolveAccountRoute(args, this.options.settingsPath, { packId: currentPack.packId, modelId: cascadeModelId })\n : resolveAccountRoute(args, this.options.settingsPath);\n\n // Q7 bucket 2: force one refresh of the active instance before rotating.\n // A 401 usually means a fresh-but-rejected token; the forced refresh\n // covers server-side clock skew and refresh-token races. Success retries\n // the same account — no rotation, no part. With no active account (e.g.\n // `ProviderAuthRequiredError` from an empty registry) a refresh can never\n // succeed, so skip it and fall through to the retry:false surface below,\n // which rethrows the original auth error instead of a generic pool\n // exhaustion message.\n if (classification.kind === 'rotate' && classification.reason === 'auth-failed' && active) {\n const forced = getForcedRefreshInstances(state);\n const refreshKey = `${providerId}:${active?.id ?? 'active'}`;\n if (!forced.has(refreshKey) && typeof store.forceRefreshActiveAccount === 'function') {\n forced.add(refreshKey);\n const token = await store.forceRefreshActiveAccount(providerId, active?.id);\n if (token !== undefined) {\n return { retry: true };\n }\n }\n }\n\n // A12: only a pin on the provider that actually failed makes this failure\n // exclusive. `route.providerId` is derived from the route's model while\n // `providerId` comes from the failed request's URL, which during a cascade\n // can still describe the session model rather than the entry being retried;\n // when they differ the pin belongs to an unrelated route, so the provider\n // that failed keeps its normal pool handling.\n const targetAccountId =\n route?.providerId === providerId ? getRouteTargetAccountId(this.options.settingsPath, route) : undefined;\n\n if (classification.kind === 'hop') {\n return this.declarePoolUnavailable(args, providerId, 'persistent-outage', targetAccountId !== undefined);\n }\n\n // A12: a targeted route never activates a sibling subscription. A\n // rotate-classified failure on the account the route selected proceeds to\n // the pack's fallback chain instead — the request hops, it does not spill\n // onto another subscription's quota. `Automatic` keeps rotating, so this\n // check sits above the pool-size test: a targeted route has nothing to\n // rotate to at any pool size. A stale id for an account the user removed\n // reads the same way: fail closed rather than silently land on a sibling.\n if (targetAccountId !== undefined) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted', true);\n }\n\n // A pool smaller than 2 has nothing to rotate to — it is exhausted by\n // definition once a rotate-classified error arrives. Route through the\n // pool-exhausted path so the notices (and any pack hop) still fire; with\n // no registry at all this announces only a configured pack hop.\n if (accounts.length < 2) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n\n // Count only this provider's instances: `tried` spans the whole request\n // (a cascade can visit several providers), so comparing its raw size to\n // this provider's account count would falsely report exhaustion when an\n // earlier provider in the same request already used up accounts.\n const tried = getTriedInstances(state);\n if (active) tried.add(active.id);\n // The tried-set is request-global and shared across providers after a\n // pack hop, so exhaustion must count only this provider's ids.\n const triedForProvider = accounts.filter(account => tried.has(account.id)).length;\n if (triedForProvider >= accounts.length) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n\n const nextCandidate = accounts.find(account => !tried.has(account.id));\n\n const next = nextCandidate ? store.activateAccount?.(providerId, nextCandidate.id) : undefined;\n if (!next) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n setRequestAccountSelection(args.requestContext, providerId, next.id);\n tried.add(next.id);\n\n // The retry replays the request from scratch (Q10): rotate the assistant\n // message id so the retried response starts a fresh message instead of\n // appending to the partially streamed one.\n args.rotateResponseMessageId?.();\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: next.id, label: next.label },\n reason: classification.reason,\n at: new Date().toISOString(),\n });\n\n return { retry: true };\n }\n\n /**\n * The request's pack cascade, computed once from the session's pack and\n * cached in processor state. Truncated at the first pack that lacks the\n * session mode's model — mirroring getDynamicModel's truncation — so the\n * cascade never promises a hop core's fallback array cannot make. The\n * position advances per hop, so a second hop in the same turn reports B→C\n * even though the session modelId still points at pack A (stickiness lands\n * TUI-side only after the part renders). Returns null when the session has\n * no active pack or the pack has no fallback chain.\n */\n private async getPackCascade(args: ProcessAPIErrorArgs): Promise<PackCascade | null> {\n if (args.state.packCascade !== undefined) {\n return (args.state.packCascade as PackCascade | null) ?? null;\n }\n const controller = args.requestContext?.get('controller') as\n | {\n session?: { modelId?: unknown; modeId?: unknown };\n getState?: () => { activeModelPackId?: unknown; thinkingLevel?: unknown };\n }\n | undefined;\n const modelId = controller?.session?.modelId;\n if (typeof modelId !== 'string' || modelId.length === 0) {\n args.state.packCascade = null;\n return null;\n }\n const modeId =\n typeof controller?.session?.modeId === 'string' && controller.session.modeId.length > 0\n ? controller.session.modeId\n : 'build';\n const settings = loadSettings(this.options.settingsPath);\n const packs = listResolvableModePacks(settings);\n const controllerState = controller?.getState?.();\n const statePackId = controllerState?.activeModelPackId ?? settings.models.activeModelPackId;\n const activePack = findModePackForModel(\n settings,\n packs,\n modelId,\n modeId,\n typeof statePackId === 'string' ? statePackId : undefined,\n );\n const chain = activePack\n ? resolveModePackFallbackChain(settings.models.packFallbacks ?? {}, activePack.id, settings.customModelPacks)\n : [];\n if (chain.length < 2) {\n args.state.packCascade = null;\n return null;\n }\n const resolvedPacks: Array<{ packId: string; label: string }> = [];\n const models: Record<string, Record<string, string>> = {};\n for (const packId of chain) {\n const pack = packs.find(candidate => candidate.id === packId);\n const packModels = pack ? resolveModePackModels(settings, pack) : {};\n if (resolvedPacks.length > 0) {\n const entryModelId = packModels[modeId];\n if (!entryModelId) break;\n // Mirror getDynamicModel's truncation: an entry whose model cannot\n // resolve (e.g. unconnected provider in deployed fail-closed mode)\n // ends the cascade here so a later hop is never announced for a pack\n // core's fallback array cannot reach. Resolved with the exact options\n // getDynamicModel uses (agents/model.ts) — including thinkingLevel —\n // so the probe can't pass where the chain builder fails.\n try {\n resolveModel(entryModelId, {\n thinkingLevel: resolveRequestThinkingLevel(\n {\n state: { thinkingLevel: controllerState?.thinkingLevel },\n session: { modeId },\n },\n this.options.settingsPath,\n ),\n remapForCodexOAuth: true,\n requestContext: args.requestContext,\n });\n } catch {\n break;\n }\n }\n resolvedPacks.push({ packId, label: pack?.name ?? packId });\n models[packId] = packModels;\n }\n if (resolvedPacks.length < 2) {\n args.state.packCascade = null;\n return null;\n }\n const cascade: PackCascade = { packs: resolvedPacks, models, modeId, position: 0 };\n args.state.packCascade = cascade;\n return cascade;\n }\n\n /**\n * Q14 gate: 400/unknown/unattributable errors never hop packs. Core's\n * fallback array advances on ANY thrown error except TripWire\n * (llm-execution-step.ts), so when the session's pack has a chain and the\n * current entry is non-last, a bare `retry: false` would silently hop on an\n * error class the user excluded from hop triggers. TripWire is the only\n * no-advance escape: the runner rethrows it and the fallback loop declines\n * to advance. No chain (or already on the last entry) → return and let the\n * plain `retry: false` surface the error exactly as before.\n */\n private async gateChainHop(args: ProcessAPIErrorArgs, error: unknown): Promise<void> {\n const cascade = await this.getPackCascade(args);\n if (!cascade) return;\n if (cascade.position >= cascade.packs.length - 1) return;\n const reason = error instanceof Error ? error.message : String(error);\n throw new TripWire(reason, {}, this.id);\n }\n\n /**\n * Emit the pack-fallback part when a configured chain has a next pack and\n * queue the thread stickiness trigger. Core's fallback array does the hop\n * itself on `retry: false`; this only announces it. The cascade is\n * truncated exactly like getDynamicModel's chain (missing mode model or\n * unresolvable model), so an announced hop is always one core can make;\n * the toModelId guard stays as defense against a stale cache.\n */\n private async emitPackFallbackPart(\n args: ProcessAPIErrorArgs,\n reason: 'pool-exhausted' | 'persistent-outage',\n ): Promise<void> {\n const cascade = await this.getPackCascade(args);\n if (!cascade) return;\n\n const from = cascade.packs[cascade.position];\n const to = cascade.packs[cascade.position + 1];\n if (!from || !to) return;\n const toModelId = cascade.models[to.packId]?.[cascade.modeId];\n if (!toModelId) return;\n\n const controller = args.requestContext?.get('controller') as\n | {\n session?: { modeId?: unknown };\n threadId?: unknown;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n emitEvent?: (event: { type: 'info'; message: string }) => void;\n }\n | undefined;\n const at = new Date().toISOString();\n const threadId = typeof controller?.threadId === 'string' ? controller.threadId : undefined;\n const pending = {\n fromPackId: from.packId,\n toPackId: to.packId,\n toModelId,\n ...(threadId ? { threadId } : {}),\n reason,\n at,\n } satisfies PendingPackFallback;\n // Persist the pending hop before announcing it. The TUI clears this marker\n // only after applying every model/pack write, so a crash or immediate\n // retrigger resumes on the landed fallback instead of the failed pack.\n await controller?.setThreadSetting?.({ key: PACK_FALLBACK_STATE_KEY, value: pending });\n const data: PackFallbackPartData = { from, to, reason, at };\n try {\n // Persist the transcript notice before notifying live state listeners.\n // Session events do not await async handlers, so reversing these writes\n // can apply a pack hop that never receives its required transcript part.\n await args.writer?.custom({ type: PACK_FALLBACK_PART_TYPE, data });\n } catch (error) {\n await controller?.setThreadSetting?.({ key: PACK_FALLBACK_STATE_KEY, value: undefined });\n throw error;\n }\n // Keep the durable marker if live state persistence fails: the transcript\n // already records the hop and thread hydration can safely resume it.\n await controller?.setState?.({ [PACK_FALLBACK_STATE_KEY]: pending });\n // Re-arm the start notice so the retried attempt on the target pack\n // re-applies its preferred routing even if the attempt below fails —\n // the flag may already be set by a switch on the original pack.\n args.state.startNoticeEmitted = false;\n // Activate the target pack's preferred account only after the hop is\n // durable. A failure here must not strand a provider-global account\n // switch with no durable fallback state — the start-notice processor\n // re-applies routing when the retried request begins on the target pack.\n const targetRoute = resolveAccountRoute(args, this.options.settingsPath, { packId: to.packId, modelId: toModelId });\n if (targetRoute) {\n // Deployed requests must hop on the tenant store: activating the target\n // pack's preferred account on the host registry would mutate a local\n // account to serve a tenant request.\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n await applyPreferredAccountRoute(args, store, this.options.settingsPath, targetRoute).catch(() => undefined);\n }\n // Live visibility: data parts never ride controller message events, so\n // emit the same line as an info event (see emitAccountSwitchPart).\n controller?.emitEvent?.({ type: 'info', message: packFallbackNoticeText(data) });\n // Advance only after the part and stickiness landed — a throw mid-emit\n // must not desync the cascade from what the transcript shows.\n cascade.position++;\n }\n\n /**\n * Pool done for this request: every instance recorded in the tried-set and\n * a `to: null` part emitted. Returns `retry: false` so core's fallback\n * array can hop to the next pack (announced by `emitPackFallbackPart`).\n * Silent on the account part when the provider has no registry at all —\n * there are no accounts to declare unavailable, but the hop still applies.\n */\n private async declarePoolUnavailable(\n args: ProcessAPIErrorArgs,\n providerId: string,\n reason: 'pool-exhausted' | 'persistent-outage',\n exclusive = false,\n ): Promise<{ retry: boolean }> {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length === 0) {\n // No account registry (API-key-only provider): nothing rotated, but the\n // hop still happens — announce the pack fallback before core advances.\n await this.emitPackFallbackPart(args, reason);\n return { retry: false };\n }\n\n const tried = getTriedInstances(args.state);\n for (const account of accounts) tried.add(account.id);\n\n const active = getRequestActiveAccount(args, store, providerId);\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: null,\n reason,\n at: new Date().toISOString(),\n ...(exclusive ? { exclusive: true } : {}),\n });\n\n await this.emitPackFallbackPart(args, reason);\n\n return { retry: false };\n }\n}\n\n/**\n * Emits the \"starting on a non-default account\" notice (Q19) once per\n * request when the active registry account is not the first entry.\n *\n * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It\n * lives in `inputProcessors`; the runner walks input processors first when\n * running `processAPIError`, so adding the method here would classify and\n * rotate errors BEFORE `StreamErrorRetryProcessor`'s transient retries run.\n */\nexport class AccountStartNoticeProcessor implements Processor {\n readonly id = 'mastracode-account-start-notice' as const;\n\n constructor(private readonly options: { credentialStore: CredentialStore; settingsPath?: string }) {}\n\n async processInput(args: ProcessInputArgs): Promise<ProcessInputResult> {\n if (args.state.startNoticeEmitted) return args.messageList;\n\n // Deployed requests resolve the tenant-scoped store so host accounts are\n // never listed, activated, or announced for a tenant run. Local mode keeps\n // the constructor's storage.\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n\n const route = resolveAccountRoute(args, this.options.settingsPath);\n if (route) {\n const switched = await applyPreferredAccountRoute(args, store, this.options.settingsPath, route);\n if (switched) {\n args.state.startNoticeEmitted = true;\n return args.messageList;\n }\n }\n\n // A14: a route whose accounts are all unavailable is not a pre-emptive\n // abort. `applyPreferredAccountRoute` marks the provider on the request so\n // credential reads fail closed rather than falling through to the active\n // account, and the request then runs and fails at the provider — which is\n // what lets the error lane classify it and hand the turn to the pack's\n // configured fallback chain. The removed persisted set threw here instead,\n // before any socket opened, so the chain was never reached.\n const providerId = route?.providerId ?? providerFromSession(args);\n if (!providerId) return args.messageList;\n\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length < 2) return args.messageList;\n\n const active = store.getActiveAccount?.(providerId);\n const first = accounts[0];\n if (!active || !first || active.id === first.id) return args.messageList;\n\n args.state.startNoticeEmitted = true;\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: null,\n to: { id: active.id, label: active.label },\n reason: 'starting-on-account',\n at: new Date().toISOString(),\n });\n\n return args.messageList;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,2BAA2B;;AAsCxC,MAAM,qBAAqB,IAAI,IAAI,kBAAkB,CAAC,CAAC,KAAI,aAAY,SAAS,EAAE,CAAC;;AAGnF,MAAM,yBAAkD;CACtD,CAAC,+BAA+B,WAAW;CAC3C,CAAC,0BAA0B,iBAAiB;CAC5C,CAAC,sBAAsB,KAAK;CAC5B,CAAC,wBAAwB,cAAc;CACvC,CAAC,kCAAkC,cAAc;CACjD,CAAC,8BAA8B,gBAAgB;CAC/C,CAAC,4BAA4B,gBAAgB;AAC/C;;;;;;;;AASA,MAAM,8BACJ;AAEF,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,0BACJ;AAEF,MAAM,kBAAkB;;AAGxB,MAAa,0BAA0B;;;;;;AAmBvC,MAAa,0BAA0B;AAmBvC,SAAS,gBAAgB,OAA6C;CACpE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU;AAClE;AAEA,SAAS,gBAAgB,OAAoC;CAC3D,IAAI,UAAmB;CACvB,KAAK,IAAI,QAAQ,GAAG,WAAW,QAAQ,iBAAiB,SAAS;EAC/D,IAAI,OAAO,YAAY,UAAU;EACjC,MAAM,EAAE,YAAY,WAAW;EAC/B,IAAI,O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Error-driven rotation across a provider's OAuth account registry.\n *\n * When the active account cannot serve a request (rate limit, quota\n * exhaustion, dead token, persistent outage), the next account in insertion\n * order is selected for the request and the request retried. OAuth fetch\n * wrappers read that request-scoped selection on every HTTP attempt, so\n * concurrent runs can't swap each other's credentials. Every switch is\n * persisted as a non-transient `data-mastracode-account-switch` part so it\n * shows in the transcript and survives history reload.\n *\n * Two classes, two lanes — the split is load-bearing. The processor runner\n * walks `[...inputProcessors, ...outputProcessors, ...errorProcessors]` when\n * running `processAPIError`, so a processor registered in the input lane that\n * also implemented `processAPIError` would run BEFORE\n * `StreamErrorRetryProcessor` and hop on 5xx errors before transient retries\n * had a chance. `AccountRotationProcessor` therefore implements\n * `processAPIError` only and is registered in `errorProcessors` after\n * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements\n * `processInput` only and is registered in `inputProcessors`.\n */\nimport { TripWire } from '@mastra/core/agent';\nimport type { ProcessAPIErrorArgs, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';\n\nimport { resolveCredentialStore } from '../agents/credential-resolver.js';\nimport { listResolvableModePacks, resolveModel, resolveRequestThinkingLevel } from '../agents/model.js';\nimport { resolveModePackFallbackChain } from '../onboarding/packs.js';\nimport { findModePackForModel, loadSettings, resolveModePackModels } from '../onboarding/settings.js';\nimport {\n getRequestAccountSelection,\n isRequestAccountRoutingExhausted,\n markRequestAccountRoutingExhausted,\n setRequestAccountSelection,\n} from './account-routing-context.js';\nimport { ProviderAuthRequiredError, PROVIDER_AUTH_REQUIRED_ERROR } from './provider-auth-error.js';\nimport { getOAuthProviders } from './storage.js';\nimport type { CredentialStore, OAuthAccountRecord } from './types.js';\n\nexport const ACCOUNT_SWITCH_PART_TYPE = 'data-mastracode-account-switch';\n\n/** Labels and instance ids only — never token material (do-not list). */\nexport interface AccountSwitchPartData {\n provider: string;\n from: { id: string; label: string } | null;\n to: { id: string; label: string } | null;\n reason:\n | 'rate-limit'\n | 'quota-exhausted'\n | 'auth-failed'\n | 'pool-exhausted'\n | 'persistent-outage'\n | 'preferred-routing'\n | 'starting-on-account';\n at: string;\n /**\n * Set on a `to: null` part when a route pinned to a single account reported\n * that account unusable. The provider's other subscriptions were never\n * consulted (A12), so \"all accounts unavailable\" would misreport what\n * happened.\n */\n exclusive?: boolean;\n}\n\n/** The store surface rotation needs; `AuthStorage` satisfies it structurally. */\nexport type RotationCredentialStore = CredentialStore & {\n /**\n * Force one refresh of the active account's tokens regardless of expiry\n * (401/403 path — a rejected-but-unexpired token usually means clock skew\n * or a refresh race). `AuthStorage` provides it; deployed per-tenant stores\n * don't, and the auth path degrades to plain rotation (which itself no-ops\n * without registry methods).\n */\n forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;\n};\n\n/** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */\nconst KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map(provider => provider.id));\n\n/** Hostname suffixes → provider ids, for `APICallError.url`. */\nconst PROVIDER_HOST_PATTERNS: Array<[RegExp, string]> = [\n [/(^|\\.)api\\.anthropic\\.com$/i, 'anthropic'],\n [/(^|\\.)api\\.kimi\\.com$/i, 'kimi-for-coding'],\n [/(^|\\.)api\\.x\\.ai$/i, 'xai'],\n [/(^|\\.)chatgpt\\.com$/i, 'openai-codex'],\n [/(^|\\.)backend-api\\.codex\\.ai$/i, 'openai-codex'],\n [/(^|\\.)githubcopilot\\.com$/i, 'github-copilot'],\n [/(^|\\.)api\\.github\\.com$/i, 'github-copilot'],\n];\n\n/**\n * Provider usage/quota-limit wording (locked Q7 bucket 1). Statuses 429/402\n * are matched before this; some providers deliver quota errors as plain 400s,\n * which only the message reveals. Deliberately restricted to unambiguous\n * quota phrases — a generic \"exceeded your … limit\" can appear on non-quota\n * client errors (request size, context length) that must never rotate.\n */\nconst USAGE_LIMIT_MESSAGE_PATTERN =\n /usage (?:limit|cap)|insufficient[_ ]quota|quota (?:exceeded|exhausted|reached)|exceeded (?:your )?current quota|insufficient (?:balance|credits?)|credits? exhausted|rate limit (?:exceeded|reached)|weekly limit|monthly limit/i;\n\nconst NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'EPIPE',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\n\nconst NETWORK_MESSAGE_PATTERN =\n /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;\n\nconst MAX_CAUSE_DEPTH = 4;\n\n/** Persisted data-part type for a fallback-pack hop. */\nexport const PACK_FALLBACK_PART_TYPE = 'data-mastracode-pack-fallback' as const;\n\n/**\n * Payload of a pack-fallback part: the pack the cascade is leaving, the pack\n * core's fallback array advances to, and why. Labels and pack ids only —\n * never credential material.\n */\nexport interface PackFallbackPartData {\n from: { packId: string; label: string };\n to: { packId: string; label: string };\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\n/**\n * Session-state key the processor sets when a pack hop happens. The TUI\n * listens for it on the typed `state_changed` controller event (data parts\n * never ride controller message events) and applies thread stickiness.\n */\nexport const PACK_FALLBACK_STATE_KEY = 'mastracodePendingPackFallback' as const;\n\n/** Payload written to session state under PACK_FALLBACK_STATE_KEY. */\nexport interface PendingPackFallback {\n fromPackId: string;\n toPackId: string;\n /** Landed pack's model for the mode the cascade is serving. */\n toModelId: string;\n /** Originating thread. Absent only on pending hops written by older clients. */\n threadId?: string;\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\nexport type RotationClassification =\n | { kind: 'rotate'; reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' }\n | { kind: 'hop' }\n | { kind: 'never' };\n\nfunction isErrorWithCode(error: unknown): error is { code?: unknown } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\nfunction readErrorStatus(error: unknown): number | undefined {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n const { statusCode, status } = current as { statusCode?: unknown; status?: unknown };\n if (typeof statusCode === 'number') return statusCode;\n if (typeof status === 'number') return status;\n current = (current as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\nfunction isProviderAuthRequiredError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n current instanceof ProviderAuthRequiredError ||\n (current instanceof Error && current.name === PROVIDER_AUTH_REQUIRED_ERROR)\n ) {\n return true;\n }\n if (typeof current !== 'object') break;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\n/** Concatenate the error's message with its cause chain (bounded). */\nfunction collectErrorText(error: unknown): string {\n const parts: string[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (current instanceof Error) {\n parts.push(current.message);\n current = current.cause;\n } else if (typeof current === 'object' && 'message' in current) {\n const message = (current as { message?: unknown }).message;\n if (typeof message === 'string') parts.push(message);\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return parts.join(' | ');\n}\n\nfunction isNetworkErrorLike(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n isErrorWithCode(current) &&\n typeof current.code === 'string' &&\n NETWORK_ERROR_CODES.has(current.code.toUpperCase())\n ) {\n return true;\n }\n if (current instanceof Error) {\n if (NETWORK_MESSAGE_PATTERN.test(current.message)) return true;\n current = current.cause;\n } else if (typeof current === 'object') {\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return false;\n}\n\n/**\n * The locked Q7 taxonomy. 429/402/usage-limit rotate immediately (429 is not\n * covered by any transient matcher, so it arrives here on first occurrence);\n * 401/403 and `ProviderAuthRequiredError` rotate after one forced refresh;\n * 5xx/network hop only when the transient retry budget is already spent (they\n * reach this processor because `StreamErrorRetryProcessor` declined); 400 and\n * everything unknown never touch the registry.\n */\nexport function classifyRotationError(error: unknown): RotationClassification {\n if (isProviderAuthRequiredError(error)) {\n return { kind: 'rotate', reason: 'auth-failed' };\n }\n\n const status = readErrorStatus(error);\n\n if (status === 429) return { kind: 'rotate', reason: 'rate-limit' };\n if (status === 402) return { kind: 'rotate', reason: 'quota-exhausted' };\n if (status === 401 || status === 403) return { kind: 'rotate', reason: 'auth-failed' };\n if (status !== undefined && status >= 500 && status < 600) return { kind: 'hop' };\n\n // Quota wording only rotates when it co-occurs with a statusless or 400\n // error — the shapes providers actually use for message-only quota\n // failures. Any other status keeps its own classification above (401/403\n // auth, 5xx outage hop, 404/422 never), so limit-ish text riding a\n // non-quota client error can no longer burn the whole pool.\n if (status === undefined || status === 400) {\n if (USAGE_LIMIT_MESSAGE_PATTERN.test(collectErrorText(error))) {\n return { kind: 'rotate', reason: 'quota-exhausted' };\n }\n }\n if (isNetworkErrorLike(error)) return { kind: 'hop' };\n\n return { kind: 'never' };\n}\n\n/** Provider id off a router model id: `mastracode/<provider>/<model>` or `<provider>/<model>`. */\nexport function providerFromModelId(modelId: string): string | undefined {\n const segments = modelId.replace(/^mastracode\\//, '').split('/');\n const providerId = segments[0];\n if (providerId === 'openai') return 'openai-codex';\n return providerId && KNOWN_PROVIDER_IDS.has(providerId) ? providerId : undefined;\n}\n\nfunction providerFromHost(hostname: string): string | undefined {\n for (const [pattern, providerId] of PROVIDER_HOST_PATTERNS) {\n if (pattern.test(hostname)) return providerId;\n }\n return undefined;\n}\n\n/**\n * Identify the provider an error came from: the request URL's hostname\n * (`APICallError.url`, cause chain included), falling back to the router\n * model id. Unknown → undefined (caller treats as never-rotate).\n */\nexport function providerFromError(error: unknown): string | undefined {\n const causeChain: object[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n causeChain.push(current);\n current = (current as { cause?: unknown }).cause;\n }\n\n // A request URL identifies the provider that actually handled the failed\n // call. Check every supported URL field throughout the cause chain before\n // falling back to router model metadata, which may describe the original\n // session model rather than the active cascade entry.\n for (const item of causeChain) {\n const urls = [\n (item as { url?: unknown }).url,\n (item as { requestURL?: unknown }).requestURL,\n (item as { requestUrl?: unknown }).requestUrl,\n ];\n for (const url of urls) {\n if (typeof url !== 'string') continue;\n try {\n const providerId = providerFromHost(new URL(url).hostname);\n if (providerId) return providerId;\n } catch {\n // Not a parseable URL — try the other fields and causes.\n }\n }\n }\n\n for (const item of causeChain) {\n const modelId = (item as { modelId?: unknown }).modelId;\n if (typeof modelId !== 'string') continue;\n const providerId = providerFromModelId(modelId);\n if (providerId) return providerId;\n }\n return undefined;\n}\n\nfunction getTriedInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.triedInstances;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.triedInstances = created;\n return created;\n}\n\nfunction getForcedRefreshInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.forcedAuthRefresh;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.forcedAuthRefresh = created;\n return created;\n}\n\n/** Friendly names for the part/notice copy (display only — never auth data). */\nexport const PROVIDER_DISPLAY_NAMES: Record<string, string> = {\n anthropic: 'Anthropic',\n 'kimi-for-coding': 'Kimi',\n 'openai-codex': 'Codex',\n 'github-copilot': 'GitHub Copilot',\n xai: 'xAI',\n};\n\nconst REASON_TEXT: Record<Exclude<AccountSwitchPartData['reason'], 'starting-on-account'>, string> = {\n 'rate-limit': 'rate limit',\n 'quota-exhausted': 'quota exhausted',\n 'auth-failed': 'auth failed',\n 'pool-exhausted': 'pool exhausted',\n 'persistent-outage': 'persistent outage',\n 'preferred-routing': 'subscription routing',\n};\n\n/** Validates untrusted `reason` values (e.g. persisted message parts). */\nexport function isAccountSwitchReason(value: unknown): value is AccountSwitchPartData['reason'] {\n return (\n value === 'starting-on-account' ||\n // Own-property check: `in` would accept prototype names like 'toString',\n // which would then interpolate the inherited function into the notice text.\n (typeof value === 'string' && Object.prototype.hasOwnProperty.call(REASON_TEXT, value))\n );\n}\n\n/**\n * One-line transcript copy for a switch part. Shared by the live `info`\n * controller event (the TUI shows controller `info` events as transcript\n * lines, and no message event carries data parts mid-run) and by the TUI's\n * history rendering of the persisted part — one formatter, identical text.\n */\nexport function accountSwitchNoticeText(data: AccountSwitchPartData): string {\n const provider = PROVIDER_DISPLAY_NAMES[data.provider] ?? data.provider;\n if (data.reason === 'starting-on-account' && data.to) {\n return `Starting on ${provider} account: ${data.to.label}`;\n }\n const reason = data.reason === 'starting-on-account' ? data.reason : REASON_TEXT[data.reason];\n if (data.to === null) {\n // A12: a targeted route reports *its* account, not the pool — the other\n // subscriptions were never tried, so \"all accounts unavailable\" would be\n // wrong and would read as if the pool had been walked.\n if (data.exclusive) {\n return `Pinned ${provider} account unavailable (${reason})`;\n }\n return `All ${provider} accounts unavailable (${reason})`;\n }\n const from = data.from?.label ?? 'unknown';\n return `Switched ${provider} account: ${from} → ${data.to.label} (${reason})`;\n}\n\n/** Transcript line for a pack-fallback hop; shared by the live info event and the TUI's history render. */\nexport function packFallbackNoticeText(data: PackFallbackPartData): string {\n const reason = REASON_TEXT[data.reason] ?? data.reason;\n return `Switched model pack: ${data.from.label} → ${data.to.label} (${reason})`;\n}\n\n/**\n * Whether a persisted pack-fallback reason is one this build understands.\n * `REASON_TEXT` also covers the account-switch reasons, so the notice text\n * alone would happily render a foreign value such as `rate-limit` as a\n * pack-fallback reason; history parsed from another build's part must be\n * rejected instead.\n */\nexport function isPackFallbackReason(value: unknown): value is PackFallbackPartData['reason'] {\n return value === 'pool-exhausted' || value === 'persistent-outage';\n}\n\nasync function emitAccountSwitchPart(\n args: Pick<ProcessAPIErrorArgs, 'writer' | 'requestContext'> | Pick<ProcessInputArgs, 'writer' | 'requestContext'>,\n data: AccountSwitchPartData,\n): Promise<void> {\n // Non-transient on purpose (contrast the transient tool-progress parts):\n // switches must persist into the assistant message and render from history.\n await args.writer?.custom({\n type: ACCOUNT_SWITCH_PART_TYPE,\n data,\n });\n // Data parts surface in the TUI only on history reload; emit the same line\n // as a controller `info` event so the switch is visible live (precedent:\n // emitTransientRetry emits controller events from the retry matcher).\n const controllerContext = args.requestContext?.get('controller') as\n | { emitEvent?: (event: { type: 'info'; message: string }) => void }\n | undefined;\n controllerContext?.emitEvent?.({ type: 'info', message: accountSwitchNoticeText(data) });\n}\n\n/**\n * Provider of the model the controller session is currently running — the\n * fallback identification path for errors that carry neither a request URL\n * nor a model id (e.g. `ProviderAuthRequiredError` thrown by a fetch wrapper\n * before any HTTP request exists).\n */\nfunction providerFromSession(\n args: Pick<ProcessAPIErrorArgs, 'requestContext'> | Pick<ProcessInputArgs, 'requestContext'>,\n): string | undefined {\n const controller = args.requestContext?.get('controller') as { session?: { modelId?: unknown } } | undefined;\n const modelId = controller?.session?.modelId;\n return typeof modelId === 'string' ? providerFromModelId(modelId) : undefined;\n}\n\n/**\n * Rotates the active OAuth account on classified API errors.\n *\n * Registered in `errorProcessors` AFTER `StreamErrorRetryProcessor` — a\n * transient error reaching this processor means the transient budget is\n * spent, which is exactly the hop condition. Implements `processAPIError`\n * ONLY (see the file header for the runner-order rationale).\n */\n/** Cached per-request pack cascade (state.packCascade). */\ninterface PackCascade {\n packs: Array<{ packId: string; label: string }>;\n models: Record<string, Record<string, string>>;\n modeId: string;\n position: number;\n}\n\ninterface AccountRoute {\n packId: string;\n modelId: string;\n providerId: string;\n}\n\ntype RoutingProcessorArgs = Pick<ProcessAPIErrorArgs, 'requestContext' | 'state' | 'writer'> | ProcessInputArgs;\n\n/**\n * Controller-shaped accessors for a thread's routing metadata. Core supplies this\n * via `requestContext.get('controller')`; the TUI builds the same shape from its\n * session so both writers share one serialization key and one read source.\n */\nexport type RoutingControllerContext = {\n session?: { modelId?: unknown; modeId?: unknown };\n threadId?: unknown;\n getState?: () => Record<string, unknown>;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n getThreadSetting?: (key: string) => Promise<unknown>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n isThreadActive?: () => boolean;\n};\n\nfunction getRoutingController(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n): RoutingControllerContext | undefined {\n return args.requestContext?.get('controller') as RoutingControllerContext | undefined;\n}\n\n/**\n * A12: the account a pack/model route targets, or `undefined` when the route\n * is `Automatic` (no entry — insertion order, full pool rotation).\n *\n * A targeted route is *exclusive*: only that account may serve the route, so\n * rotation must never spill the request onto a sibling subscription's quota.\n * A heavy model on one subscription can burn that subscription's quota in\n * hours; spilling it into a second subscription defeats the point of having\n * one.\n */\nfunction getRouteTargetAccountId(settingsPath: string | undefined, route: AccountRoute | null): string | undefined {\n if (!route) return undefined;\n return loadSettings(settingsPath).models.packAccountPreferences?.[route.packId]?.[route.modelId];\n}\n\nfunction getRequestActiveAccount(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n store: CredentialStore,\n providerId: string,\n) {\n if (isRequestAccountRoutingExhausted(args.requestContext, providerId)) return undefined;\n const selectedId = getRequestAccountSelection(args.requestContext, providerId);\n // A deleted request selection is not a failure of the new global active account.\n if (selectedId) return store.listAccounts?.(providerId).find(account => account.id === selectedId);\n return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find(account => account.active);\n}\n\nfunction resolveAccountRoute(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n settingsPath?: string,\n explicit?: { packId: string; modelId: string },\n): AccountRoute | null {\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const pending = state?.mastracodePendingPackFallback as\n | { toPackId?: unknown; toModelId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toPackId === 'string' &&\n typeof pending.toModelId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const resolvedModelId =\n explicit?.modelId ??\n (pendingMatchesThread ? pending.toModelId : undefined) ??\n (typeof controller?.session?.modelId === 'string' ? controller.session.modelId : undefined);\n if (typeof resolvedModelId !== 'string' || resolvedModelId.length === 0) return null;\n const modelId = resolvedModelId;\n\n const settings = loadSettings(settingsPath);\n const packs = listResolvableModePacks(settings);\n const modeId =\n typeof controller?.session?.modeId === 'string' && controller.session.modeId.length > 0\n ? controller.session.modeId\n : 'build';\n const explicitPackId =\n explicit?.packId ??\n (pendingMatchesThread ? pending.toPackId : undefined) ??\n (typeof state?.activeModelPackId === 'string' ? state.activeModelPackId : settings.models.activeModelPackId);\n const pack = explicitPackId\n ? packs.find(candidate => candidate.id === explicitPackId)\n : findModePackForModel(settings, packs, modelId, modeId, undefined);\n if (!pack || resolveModePackModels(settings, pack)[modeId] !== modelId) return null;\n\n const providerId = providerFromModelId(modelId);\n return providerId ? { packId: pack.id, modelId, providerId } : null;\n}\n\n/**\n * A14: `Automatic` rotation starts *at* the persisted active account and walks\n * insertion order from there, wrapping once. The active account is the cursor\n * rotation last left at, so a turn that starts at index 0 regardless would\n * re-activate and re-try an account the previous turn already moved past —\n * which is the whole job the removed sticky-exclusion set was doing badly.\n * With no persisted active account the order is plain insertion order.\n */\nfunction orderAccountsFromActive(accounts: OAuthAccountRecord[], activeId: string | undefined) {\n const index = activeId === undefined ? -1 : accounts.findIndex(account => account.id === activeId);\n if (index <= 0) return accounts;\n return [...accounts.slice(index), ...accounts.slice(0, index)];\n}\n\nasync function applyPreferredAccountRoute(\n args: RoutingProcessorArgs,\n store: CredentialStore,\n settingsPath: string | undefined,\n route: AccountRoute,\n): Promise<boolean> {\n store.reload();\n const preferredId = getRouteTargetAccountId(settingsPath, route);\n const accounts = store.listAccounts?.(route.providerId) ?? [];\n if (accounts.length === 0 && preferredId === undefined) return false;\n const tried = getTriedInstances(args.state);\n const unavailable = new Set(accounts.filter(account => tried.has(account.id)).map(account => account.id));\n const active = getRequestActiveAccount(args, store, route.providerId) ?? store.getActiveAccount?.(route.providerId);\n const selected = // A12: a targeted route may use only the account it names. `Automatic`\n // keeps insertion order with full pool rotation (A10), starting from the\n // account the cursor already points at (A14).\n (\n preferredId\n ? accounts.filter(account => account.id === preferredId)\n : orderAccountsFromActive(accounts, active?.id)\n ).find(account => !unavailable.has(account.id));\n\n for (const accountId of unavailable) tried.add(accountId);\n if (!selected) {\n markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n\n if (active?.id === selected.id) {\n setRequestAccountSelection(args.requestContext, route.providerId, selected.id);\n return false;\n }\n // Activate before recording the request-scoped selection: a failed\n // activation must not leave the selection claiming an account that never\n // became the provider's active credential.\n const activated = store.activateAccount ? store.activateAccount(route.providerId, selected.id) : selected;\n if (!activated) {\n // Only a targeted route is out of options here. The exhausted marker is\n // request-wide and fails every credential read closed, so setting it for\n // `Automatic` would stop error recovery from retrying on a survivor.\n if (preferredId !== undefined) markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n setRequestAccountSelection(args.requestContext, route.providerId, activated.id);\n\n // Applying an explicit account choice is routine, not a failover notice.\n if (preferredId === undefined) {\n await emitAccountSwitchPart(args, {\n provider: route.providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: activated.id, label: activated.label },\n reason: 'preferred-routing',\n at: new Date().toISOString(),\n });\n }\n return true;\n}\n\nexport class AccountRotationProcessor implements Processor {\n readonly id = 'mastracode-account-rotation' as const;\n\n constructor(\n private readonly options: {\n credentialStore: RotationCredentialStore;\n maxProcessorRetries: number;\n settingsPath?: string;\n },\n ) {}\n\n async processAPIError(args: ProcessAPIErrorArgs): Promise<{ retry: boolean }> {\n const { error, state } = args;\n\n // Core runs error processors even after the shared retry budget is spent\n // and silently discards `retry: true` then (llm-execution-step.ts\n // canRetryError) — rotating the cursor or emitting a switch part for a\n // retry that will never run would lie to both auth.json and the\n // transcript. With a fallback chain configured, a bare `retry: false`\n // here would silently hop packs for an error we never classified, so the\n // chain gate surfaces the error instead.\n if (args.retryCount >= this.options.maxProcessorRetries) {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n // Classify before attributing: an error from a provider outside the OAuth\n // registry (API-key/router providers are valid pack members) still hops on\n // rotate/hop classes — there is just no account cursor to advance.\n const classification = classifyRotationError(error);\n // Q14: 400/unknown errors never rotate and never hop packs. With a chain\n // active, core's fallback array would still advance on a bare\n // `retry: false` (it advances on any thrown non-TripWire error), so the\n // gate converts that into a surfaced error instead of a silent hop.\n if (classification.kind === 'never') {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n const cascade = await this.getPackCascade(args);\n const currentPack = cascade?.packs[cascade.position];\n const cascadeModelId = currentPack ? cascade.models[currentPack.packId]?.[cascade.modeId] : undefined;\n const providerId =\n providerFromError(error) ??\n (typeof cascadeModelId === 'string' ? providerFromModelId(cascadeModelId) : undefined) ??\n (cascade ? undefined : providerFromSession(args));\n if (!providerId) {\n await this.emitPackFallbackPart(args, classification.kind === 'hop' ? 'persistent-outage' : 'pool-exhausted');\n return { retry: false };\n }\n\n // Deployed requests resolve the tenant-scoped store; local mode keeps the\n // host storage. Reading the host registry here would rotate or announce\n // host accounts for a tenant request. Annotated as the rotation surface:\n // `resolveCredentialStore` returns a plain CredentialStore, and the 401\n // path below uses the optional `forceRefreshActiveAccount` when the host\n // provides it.\n const store: RotationCredentialStore = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n store.reload();\n const accounts = store.listAccounts?.(providerId) ?? [];\n const active = getRequestActiveAccount(args, store, providerId);\n const route =\n currentPack && typeof cascadeModelId === 'string'\n ? resolveAccountRoute(args, this.options.settingsPath, { packId: currentPack.packId, modelId: cascadeModelId })\n : resolveAccountRoute(args, this.options.settingsPath);\n\n // Q7 bucket 2: force one refresh of the active instance before rotating.\n // A 401 usually means a fresh-but-rejected token; the forced refresh\n // covers server-side clock skew and refresh-token races. Success retries\n // the same account — no rotation, no part. With no active account (e.g.\n // `ProviderAuthRequiredError` from an empty registry) a refresh can never\n // succeed, so skip it and fall through to the retry:false surface below,\n // which rethrows the original auth error instead of a generic pool\n // exhaustion message.\n if (classification.kind === 'rotate' && classification.reason === 'auth-failed' && active) {\n const forced = getForcedRefreshInstances(state);\n const refreshKey = `${providerId}:${active?.id ?? 'active'}`;\n if (!forced.has(refreshKey) && typeof store.forceRefreshActiveAccount === 'function') {\n forced.add(refreshKey);\n const token = await store.forceRefreshActiveAccount(providerId, active?.id);\n if (token !== undefined) {\n return { retry: true };\n }\n }\n }\n\n // A12: only a pin on the provider that actually failed makes this failure\n // exclusive. `route.providerId` is derived from the route's model while\n // `providerId` comes from the failed request's URL, which during a cascade\n // can still describe the session model rather than the entry being retried;\n // when they differ the pin belongs to an unrelated route, so the provider\n // that failed keeps its normal pool handling.\n const targetAccountId =\n route?.providerId === providerId ? getRouteTargetAccountId(this.options.settingsPath, route) : undefined;\n\n if (classification.kind === 'hop') {\n return this.declarePoolUnavailable(args, providerId, 'persistent-outage', targetAccountId !== undefined);\n }\n\n // A12: a targeted route never activates a sibling subscription. A\n // rotate-classified failure on the account the route selected proceeds to\n // the pack's fallback chain instead — the request hops, it does not spill\n // onto another subscription's quota. A targeted route has nothing to\n // rotate to at any pool size. A stale id for an account the user removed\n // reads the same way: fail closed rather than silently land on a sibling.\n if (targetAccountId !== undefined) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted', true);\n }\n\n // Count only this provider's instances: `tried` spans the whole request\n // (a cascade can visit several providers), so comparing its raw size to\n // this provider's account count would falsely report exhaustion when an\n // earlier provider in the same request already used up accounts.\n const tried = getTriedInstances(state);\n if (active) tried.add(active.id);\n // The tried-set is request-global and shared across providers after a\n // pack hop, so exhaustion must count only this provider's ids.\n const triedForProvider = accounts.filter(account => tried.has(account.id)).length;\n if (triedForProvider >= accounts.length) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n\n // If the selected account was removed elsewhere, even a single survivor\n // is still untried. Resume from the freshly loaded global cursor.\n const candidates = active ? accounts : orderAccountsFromActive(accounts, store.getActiveAccount?.(providerId)?.id);\n const nextCandidate = candidates.find(account => !tried.has(account.id));\n\n const next = nextCandidate ? store.activateAccount?.(providerId, nextCandidate.id) : undefined;\n if (!next) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n setRequestAccountSelection(args.requestContext, providerId, next.id);\n tried.add(next.id);\n\n // The retry replays the request from scratch (Q10): rotate the assistant\n // message id so the retried response starts a fresh message instead of\n // appending to the partially streamed one.\n args.rotateResponseMessageId?.();\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: next.id, label: next.label },\n reason: classification.reason,\n at: new Date().toISOString(),\n });\n\n return { retry: true };\n }\n\n /**\n * The request's pack cascade, computed once from the session's pack and\n * cached in processor state. Truncated at the first pack that lacks the\n * session mode's model — mirroring getDynamicModel's truncation — so the\n * cascade never promises a hop core's fallback array cannot make. The\n * position advances per hop, so a second hop in the same turn reports B→C\n * even though the session modelId still points at pack A (stickiness lands\n * TUI-side only after the part renders). Returns null when the session has\n * no active pack or the pack has no fallback chain.\n */\n private async getPackCascade(args: ProcessAPIErrorArgs): Promise<PackCascade | null> {\n if (args.state.packCascade !== undefined) {\n return (args.state.packCascade as PackCascade | null) ?? null;\n }\n const controller = args.requestContext?.get('controller') as\n | {\n session?: { modelId?: unknown; modeId?: unknown };\n getState?: () => { activeModelPackId?: unknown; thinkingLevel?: unknown };\n }\n | undefined;\n const modelId = controller?.session?.modelId;\n if (typeof modelId !== 'string' || modelId.length === 0) {\n args.state.packCascade = null;\n return null;\n }\n const modeId =\n typeof controller?.session?.modeId === 'string' && controller.session.modeId.length > 0\n ? controller.session.modeId\n : 'build';\n const settings = loadSettings(this.options.settingsPath);\n const packs = listResolvableModePacks(settings);\n const controllerState = controller?.getState?.();\n const statePackId = controllerState?.activeModelPackId ?? settings.models.activeModelPackId;\n const activePack = findModePackForModel(\n settings,\n packs,\n modelId,\n modeId,\n typeof statePackId === 'string' ? statePackId : undefined,\n );\n const chain = activePack\n ? resolveModePackFallbackChain(settings.models.packFallbacks ?? {}, activePack.id, settings.customModelPacks)\n : [];\n if (chain.length < 2) {\n args.state.packCascade = null;\n return null;\n }\n const resolvedPacks: Array<{ packId: string; label: string }> = [];\n const models: Record<string, Record<string, string>> = {};\n for (const packId of chain) {\n const pack = packs.find(candidate => candidate.id === packId);\n const packModels = pack ? resolveModePackModels(settings, pack) : {};\n if (resolvedPacks.length > 0) {\n const entryModelId = packModels[modeId];\n if (!entryModelId) break;\n // Mirror getDynamicModel's truncation: an entry whose model cannot\n // resolve (e.g. unconnected provider in deployed fail-closed mode)\n // ends the cascade here so a later hop is never announced for a pack\n // core's fallback array cannot reach. Resolved with the exact options\n // getDynamicModel uses (agents/model.ts) — including thinkingLevel —\n // so the probe can't pass where the chain builder fails.\n try {\n resolveModel(entryModelId, {\n thinkingLevel: resolveRequestThinkingLevel(\n {\n state: { thinkingLevel: controllerState?.thinkingLevel },\n session: { modeId },\n },\n this.options.settingsPath,\n ),\n remapForCodexOAuth: true,\n requestContext: args.requestContext,\n });\n } catch {\n break;\n }\n }\n resolvedPacks.push({ packId, label: pack?.name ?? packId });\n models[packId] = packModels;\n }\n if (resolvedPacks.length < 2) {\n args.state.packCascade = null;\n return null;\n }\n const cascade: PackCascade = { packs: resolvedPacks, models, modeId, position: 0 };\n args.state.packCascade = cascade;\n return cascade;\n }\n\n /**\n * Q14 gate: 400/unknown/unattributable errors never hop packs. Core's\n * fallback array advances on ANY thrown error except TripWire\n * (llm-execution-step.ts), so when the session's pack has a chain and the\n * current entry is non-last, a bare `retry: false` would silently hop on an\n * error class the user excluded from hop triggers. TripWire is the only\n * no-advance escape: the runner rethrows it and the fallback loop declines\n * to advance. No chain (or already on the last entry) → return and let the\n * plain `retry: false` surface the error exactly as before.\n */\n private async gateChainHop(args: ProcessAPIErrorArgs, error: unknown): Promise<void> {\n const cascade = await this.getPackCascade(args);\n if (!cascade) return;\n if (cascade.position >= cascade.packs.length - 1) return;\n const reason = error instanceof Error ? error.message : String(error);\n throw new TripWire(reason, {}, this.id);\n }\n\n /**\n * Emit the pack-fallback part when a configured chain has a next pack and\n * queue the thread stickiness trigger. Core's fallback array does the hop\n * itself on `retry: false`; this only announces it. The cascade is\n * truncated exactly like getDynamicModel's chain (missing mode model or\n * unresolvable model), so an announced hop is always one core can make;\n * the toModelId guard stays as defense against a stale cache.\n */\n private async emitPackFallbackPart(\n args: ProcessAPIErrorArgs,\n reason: 'pool-exhausted' | 'persistent-outage',\n ): Promise<void> {\n const cascade = await this.getPackCascade(args);\n if (!cascade) return;\n\n const from = cascade.packs[cascade.position];\n const to = cascade.packs[cascade.position + 1];\n if (!from || !to) return;\n const toModelId = cascade.models[to.packId]?.[cascade.modeId];\n if (!toModelId) return;\n\n const controller = args.requestContext?.get('controller') as\n | {\n session?: { modeId?: unknown };\n threadId?: unknown;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n emitEvent?: (event: { type: 'info'; message: string }) => void;\n }\n | undefined;\n const at = new Date().toISOString();\n const threadId = typeof controller?.threadId === 'string' ? controller.threadId : undefined;\n const pending = {\n fromPackId: from.packId,\n toPackId: to.packId,\n toModelId,\n ...(threadId ? { threadId } : {}),\n reason,\n at,\n } satisfies PendingPackFallback;\n // Persist the pending hop before announcing it. The TUI clears this marker\n // only after applying every model/pack write, so a crash or immediate\n // retrigger resumes on the landed fallback instead of the failed pack.\n await controller?.setThreadSetting?.({ key: PACK_FALLBACK_STATE_KEY, value: pending });\n const data: PackFallbackPartData = { from, to, reason, at };\n try {\n // Persist the transcript notice before notifying live state listeners.\n // Session events do not await async handlers, so reversing these writes\n // can apply a pack hop that never receives its required transcript part.\n await args.writer?.custom({ type: PACK_FALLBACK_PART_TYPE, data });\n } catch (error) {\n await controller?.setThreadSetting?.({ key: PACK_FALLBACK_STATE_KEY, value: undefined });\n throw error;\n }\n // Keep the durable marker if live state persistence fails: the transcript\n // already records the hop and thread hydration can safely resume it.\n await controller?.setState?.({ [PACK_FALLBACK_STATE_KEY]: pending });\n // Re-arm the start notice so the retried attempt on the target pack\n // re-applies its preferred routing even if the attempt below fails —\n // the flag may already be set by a switch on the original pack.\n args.state.startNoticeEmitted = false;\n // Activate the target pack's preferred account only after the hop is\n // durable. A failure here must not strand a provider-global account\n // switch with no durable fallback state — the start-notice processor\n // re-applies routing when the retried request begins on the target pack.\n const targetRoute = resolveAccountRoute(args, this.options.settingsPath, { packId: to.packId, modelId: toModelId });\n if (targetRoute) {\n // Deployed requests must hop on the tenant store: activating the target\n // pack's preferred account on the host registry would mutate a local\n // account to serve a tenant request.\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n await applyPreferredAccountRoute(args, store, this.options.settingsPath, targetRoute).catch(() => undefined);\n }\n // Live visibility: data parts never ride controller message events, so\n // emit the same line as an info event (see emitAccountSwitchPart).\n controller?.emitEvent?.({ type: 'info', message: packFallbackNoticeText(data) });\n // Advance only after the part and stickiness landed — a throw mid-emit\n // must not desync the cascade from what the transcript shows.\n cascade.position++;\n }\n\n /**\n * Pool done for this request: every instance recorded in the tried-set and\n * a `to: null` part emitted. Returns `retry: false` so core's fallback\n * array can hop to the next pack (announced by `emitPackFallbackPart`).\n * Silent on the account part when the provider has no registry at all —\n * there are no accounts to declare unavailable, but the hop still applies.\n */\n private async declarePoolUnavailable(\n args: ProcessAPIErrorArgs,\n providerId: string,\n reason: 'pool-exhausted' | 'persistent-outage',\n exclusive = false,\n ): Promise<{ retry: boolean }> {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length === 0) {\n // No account registry (API-key-only provider): nothing rotated, but the\n // hop still happens — announce the pack fallback before core advances.\n await this.emitPackFallbackPart(args, reason);\n return { retry: false };\n }\n\n const tried = getTriedInstances(args.state);\n for (const account of accounts) tried.add(account.id);\n\n const active = getRequestActiveAccount(args, store, providerId);\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: null,\n reason,\n at: new Date().toISOString(),\n ...(exclusive ? { exclusive: true } : {}),\n });\n\n await this.emitPackFallbackPart(args, reason);\n\n return { retry: false };\n }\n}\n\n/**\n * Emits the \"starting on a non-default account\" notice (Q19) once per\n * request when the active registry account is not the first entry.\n *\n * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It\n * lives in `inputProcessors`; the runner walks input processors first when\n * running `processAPIError`, so adding the method here would classify and\n * rotate errors BEFORE `StreamErrorRetryProcessor`'s transient retries run.\n */\nexport class AccountStartNoticeProcessor implements Processor {\n readonly id = 'mastracode-account-start-notice' as const;\n\n constructor(private readonly options: { credentialStore: CredentialStore; settingsPath?: string }) {}\n\n async processInput(args: ProcessInputArgs): Promise<ProcessInputResult> {\n if (args.state.startNoticeEmitted) return args.messageList;\n\n // Deployed requests resolve the tenant-scoped store so host accounts are\n // never listed, activated, or announced for a tenant run. Local mode keeps\n // the constructor's storage.\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n\n const route = resolveAccountRoute(args, this.options.settingsPath);\n if (route) {\n const switched = await applyPreferredAccountRoute(args, store, this.options.settingsPath, route);\n if (switched || getRouteTargetAccountId(this.options.settingsPath, route) !== undefined) {\n args.state.startNoticeEmitted = true;\n return args.messageList;\n }\n } else {\n store.reload();\n }\n\n // A14: a route whose accounts are all unavailable is not a pre-emptive\n // abort. `applyPreferredAccountRoute` marks the provider on the request so\n // credential reads fail closed rather than falling through to the active\n // account, and the request then runs and fails at the provider — which is\n // what lets the error lane classify it and hand the turn to the pack's\n // configured fallback chain. The removed persisted set threw here instead,\n // before any socket opened, so the chain was never reached.\n const providerId = route?.providerId ?? providerFromSession(args);\n if (!providerId) return args.messageList;\n\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length < 2) return args.messageList;\n\n const active = store.getActiveAccount?.(providerId);\n const first = accounts[0];\n if (!active || !first || active.id === first.id) return args.messageList;\n\n args.state.startNoticeEmitted = true;\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: null,\n to: { id: active.id, label: active.label },\n reason: 'starting-on-account',\n at: new Date().toIS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C;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAExC,wBAAsB,0BAA0B,CAAC,OAAO,CAAC,EAAE;IACzD,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAqDxC;AA+CD,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,4BAA4B,EACrC,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GACjC,OAAO,CAAC,0BAA0B,CAAC,CASrC;AAED,wBAAsB,eAAe,CAAC,SAAS,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAS/F;AAED,wBAAsB,sBAAsB,CAC1C,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAClD,OAAO,CAAC,gBAAgB,CAAC,CAoC3B;AAED,eAAO,MAAM,uBAAuB,EAAE,sBASrC,CAAC"}
@@ -1,7 +1,6 @@
1
1
  import { getCurrentVersion } from "../../utils/update-check.js";
2
2
  import { abortableSleep, createDeviceCodePollState, pollDeviceCodeUntilComplete, stepDeviceCodePoll } from "../device-code.js";
3
3
  import { arch, hostname, platform, release } from "os";
4
- import { randomUUID } from "crypto";
5
4
  //#region src/auth/providers/kimi-coding.ts
6
5
  const CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098";
7
6
  const OAUTH_HOST = "https://auth.kimi.com";
@@ -21,7 +20,7 @@ const KIMI_DEVICE_DETAILS = {
21
20
  "X-Msh-Os-Version": asciiHeaderValue(release())
22
21
  };
23
22
  function createKimiCodingDeviceId() {
24
- return randomUUID().replaceAll("-", "");
23
+ return globalThis.crypto.randomUUID().replaceAll("-", "");
25
24
  }
26
25
  function isKimiCodingDeviceId(value) {
27
26
  return typeof value === "string" && DEVICE_ID_PATTERN.test(value);
@@ -1 +1 @@
1
- {"version":3,"file":"kimi-coding.js","names":[],"sources":["../../../src/auth/providers/kimi-coding.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { arch, hostname, platform, release } from 'node:os';\nimport { getCurrentVersion } from '../../utils/update-check.js';\nimport {\n abortableSleep,\n createDeviceCodePollState,\n pollDeviceCodeUntilComplete,\n stepDeviceCodePoll,\n} from '../device-code.js';\nimport type { DeviceCodePollOutcome, DeviceCodePollState } from '../device-code.js';\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';\n\nconst CLIENT_ID = '17e5f671-d194-4dfb-9706-5516cb48c098';\nconst OAUTH_HOST = 'https://auth.kimi.com';\nconst DEVICE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst DEFAULT_EXPIRES_IN_SECONDS = 15 * 60;\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\nconst REQUEST_TIMEOUT_MS = 30_000;\nconst REFRESH_MAX_RETRIES = 3;\n\nfunction asciiHeaderValue(value: string): string {\n const sanitized = value.replace(/[^\\x20-\\x7E]/g, '').trim();\n return sanitized || 'unknown';\n}\n\nconst KIMI_DEVICE_DETAILS = {\n 'X-Msh-Platform': 'mastracode',\n 'X-Msh-Version': asciiHeaderValue(getCurrentVersion()),\n 'X-Msh-Device-Name': asciiHeaderValue(hostname()),\n 'X-Msh-Device-Model': asciiHeaderValue(`${platform()} ${arch()}`),\n 'X-Msh-Os-Version': asciiHeaderValue(release()),\n};\n\nexport function createKimiCodingDeviceId(): string {\n return randomUUID().replaceAll('-', '');\n}\n\nexport function isKimiCodingDeviceId(value: unknown): value is string {\n return typeof value === 'string' && DEVICE_ID_PATTERN.test(value);\n}\n\nexport function getKimiCodingDeviceHeaders(deviceId: string): Record<string, string> {\n if (!isKimiCodingDeviceId(deviceId)) {\n throw new Error('Kimi For Coding credentials have an invalid device ID. Please reconnect the account.');\n }\n return { ...KIMI_DEVICE_DETAILS, 'X-Msh-Device-Id': deviceId };\n}\n\nfunction requestSignal(signal?: AbortSignal): AbortSignal {\n const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);\n return signal ? AbortSignal.any([timeout, signal]) : timeout;\n}\n\nfunction trustedHttpUrl(value: unknown): string | null {\n if (typeof value !== 'string' || !value) return null;\n try {\n const url = new URL(value);\n return url.protocol === 'https:' ? url.href : null;\n } catch {\n return null;\n }\n}\n\nasync function readJson(response: Response): Promise<Record<string, unknown> | null> {\n try {\n const value = (await response.json()) as unknown;\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\nfunction credentialsFromTokenResponse(value: unknown, operation: string, deviceId: string): OAuthCredentials {\n const data = (value ?? {}) as Record<string, unknown>;\n const access = data.access_token;\n const refresh = data.refresh_token;\n const expiresIn = data.expires_in;\n if (\n typeof access !== 'string' ||\n !access ||\n typeof refresh !== 'string' ||\n !refresh ||\n typeof expiresIn !== 'number' ||\n !Number.isFinite(expiresIn) ||\n expiresIn <= 0\n ) {\n throw new Error(`Kimi For Coding token ${operation} response missing fields`);\n }\n return { access, refresh, expires: Date.now() + expiresIn * 1000, deviceId };\n}\n\nexport interface KimiCodingDeviceLoginPending {\n clientId: string;\n deviceId: string;\n deviceCode: string;\n userCode: string;\n url: string;\n instructions: string;\n state: DeviceCodePollState;\n}\n\nexport type KimiCodingDevicePollResult =\n | { status: 'complete'; credentials: OAuthCredentials }\n | { status: 'pending'; nextPollMs: number; pending: KimiCodingDeviceLoginPending }\n | { status: 'failed'; error: string };\n\nexport async function startKimiCodingDeviceLogin(options?: {\n signal?: AbortSignal;\n}): Promise<KimiCodingDeviceLoginPending> {\n const clientId = CLIENT_ID;\n const deviceId = createKimiCodingDeviceId();\n const response = await fetch(`${OAUTH_HOST}/api/oauth/device_authorization`, {\n method: 'POST',\n headers: {\n ...getKimiCodingDeviceHeaders(deviceId),\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({ client_id: clientId }).toString(),\n signal: requestSignal(options?.signal),\n });\n if (!response.ok) {\n throw new Error(`Kimi For Coding device authorization failed: ${response.status}`);\n }\n\n const data = await readJson(response);\n const deviceCode = data?.device_code;\n const userCode = data?.user_code;\n const verificationUri = trustedHttpUrl(data?.verification_uri);\n const verificationUriComplete = trustedHttpUrl(data?.verification_uri_complete);\n if (\n typeof deviceCode !== 'string' ||\n !deviceCode ||\n typeof userCode !== 'string' ||\n !userCode ||\n !verificationUri ||\n !verificationUriComplete\n ) {\n throw new Error('Invalid Kimi For Coding device authorization response');\n }\n\n const interval = data?.interval;\n const expiresIn = data?.expires_in;\n return {\n clientId,\n deviceId,\n deviceCode,\n userCode,\n url: verificationUriComplete,\n instructions: `Enter code: ${userCode}`,\n state: createDeviceCodePollState({\n intervalSeconds:\n typeof interval === 'number' && Number.isFinite(interval) && interval > 0\n ? interval\n : DEFAULT_POLL_INTERVAL_SECONDS,\n expiresInSeconds:\n typeof expiresIn === 'number' && Number.isFinite(expiresIn) && expiresIn > 0\n ? expiresIn\n : DEFAULT_EXPIRES_IN_SECONDS,\n }),\n };\n}\n\nasync function pollKimiCodingTokenOnce(\n pending: KimiCodingDeviceLoginPending,\n signal?: AbortSignal,\n): Promise<DeviceCodePollOutcome<OAuthCredentials>> {\n const response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {\n method: 'POST',\n headers: {\n ...getKimiCodingDeviceHeaders(pending.deviceId),\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({\n client_id: pending.clientId,\n device_code: pending.deviceCode,\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n }).toString(),\n signal: requestSignal(signal),\n });\n const data = await readJson(response);\n if (response.ok && typeof data?.access_token === 'string') {\n try {\n return { status: 'complete', result: credentialsFromTokenResponse(data, 'poll', pending.deviceId) };\n } catch (error) {\n return { status: 'failed', error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n const error = data?.error;\n if (error === 'authorization_pending') return { status: 'pending' };\n if (error === 'slow_down') {\n return {\n status: 'slow_down',\n intervalSeconds: typeof data?.interval === 'number' && data.interval > 0 ? data.interval : undefined,\n };\n }\n if (error === 'expired_token') {\n return { status: 'failed', error: 'Kimi For Coding authorization expired. Please restart login.' };\n }\n if (error === 'access_denied') return { status: 'failed', error: 'Kimi For Coding login was denied.' };\n return {\n status: 'failed',\n error: `Kimi For Coding token request failed: ${response.status}`,\n };\n}\n\nexport async function pollKimiCodingDeviceLogin(\n pending: KimiCodingDeviceLoginPending,\n options?: { signal?: AbortSignal },\n): Promise<KimiCodingDevicePollResult> {\n const step = await stepDeviceCodePoll(pending.state, () => pollKimiCodingTokenOnce(pending, options?.signal));\n if (step.status === 'complete') return { status: 'complete', credentials: step.result };\n if (step.status === 'failed') return { status: 'failed', error: step.error };\n return {\n status: 'pending',\n nextPollMs: step.nextPollMs,\n pending: { ...pending, state: step.state },\n };\n}\n\nexport async function loginKimiCoding(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n const pending = await startKimiCodingDeviceLogin({ signal: callbacks.signal });\n callbacks.onAuth({ url: pending.url, instructions: pending.instructions });\n callbacks.onProgress?.('Waiting for Kimi For Coding device authorization...');\n return pollDeviceCodeUntilComplete({\n state: pending.state,\n pollOnce: () => pollKimiCodingTokenOnce(pending, callbacks.signal),\n signal: callbacks.signal,\n });\n}\n\nexport async function refreshKimiCodingToken(\n refreshToken: string,\n options: { signal?: AbortSignal; deviceId: string },\n): Promise<OAuthCredentials> {\n const clientId = CLIENT_ID;\n const deviceHeaders = getKimiCodingDeviceHeaders(options.deviceId);\n let lastError: Error | undefined;\n for (let attempt = 0; attempt <= REFRESH_MAX_RETRIES; attempt++) {\n if (attempt > 0) await abortableSleep(1000 * 2 ** (attempt - 1), options.signal);\n let response: Response;\n try {\n response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {\n method: 'POST',\n headers: {\n ...deviceHeaders,\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({\n client_id: clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }).toString(),\n signal: requestSignal(options.signal),\n });\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt === REFRESH_MAX_RETRIES) throw lastError;\n continue;\n }\n const data = await readJson(response);\n if (response.ok) return credentialsFromTokenResponse(data, 'refresh', options.deviceId);\n\n const error = typeof data?.error === 'string' ? ` ${data.error}` : '';\n lastError = new Error(`Kimi For Coding token refresh failed: ${response.status}${error}`);\n const retryable = response.status === 429 || response.status >= 500;\n if (!retryable || attempt === REFRESH_MAX_RETRIES) throw lastError;\n }\n throw lastError ?? new Error('Kimi For Coding token refresh failed');\n}\n\nexport const kimiCodingOAuthProvider: OAuthProviderInterface = {\n id: 'kimi-for-coding',\n name: 'Kimi For Coding',\n login: loginKimiCoding,\n refreshToken: credentials =>\n refreshKimiCodingToken(credentials.refresh, {\n deviceId: typeof credentials.deviceId === 'string' ? credentials.deviceId : '',\n }),\n getApiKey: credentials => credentials.access,\n};\n"],"mappings":";;;;;AAYA,MAAM,YAAY;AAClB,MAAM,aAAa;AACnB,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B;AACnC,MAAM,gCAAgC;AACtC,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAE5B,SAAS,iBAAiB,OAAuB;CAE/C,OADkB,MAAM,QAAQ,iBAAiB,EAAE,CAAC,CAAC,KACtC,KAAK;AACtB;AAEA,MAAM,sBAAsB;CAC1B,kBAAkB;CAClB,iBAAiB,iBAAiB,kBAAkB,CAAC;CACrD,qBAAqB,iBAAiB,SAAS,CAAC;CAChD,sBAAsB,iBAAiB,GAAG,SAAS,EAAE,GAAG,KAAK,GAAG;CAChE,oBAAoB,iBAAiB,QAAQ,CAAC;AAChD;AAEA,SAAgB,2BAAmC;CACjD,OAAO,WAAW,CAAC,CAAC,WAAW,KAAK,EAAE;AACxC;AAEA,SAAgB,qBAAqB,OAAiC;CACpE,OAAO,OAAO,UAAU,YAAY,kBAAkB,KAAK,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AC3B,MAAM,WAAW;CACjB,MAAM,gBAAgB,2BAA2B,QAAQ,QAAQ;CACjE,IAAI;CACJ,KAAK,IAAI,UAAU,GAAG,WAAW,qBAAqB,WAAW;EAC/D,IAAI,UAAU,GAAG,MAAM,eAAe,MAAO,MAAM,UAAU,IAAI,QAAQ,MAAM;EAC/E,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,MAAM,GAAG,WAAW,mBAAmB;IACtD,QAAQ;IACR,SAAS;KACP,GAAG;KACH,gBAAgB;KAChB,QAAQ;IACV;IACA,MAAM,IAAI,gBAAgB;KACxB,WAAW;KACX,YAAY;KACZ,eAAe;IACjB,CAAC,CAAC,CAAC,SAAS;IACZ,QAAQ,cAAc,QAAQ,MAAM;GACtC,CAAC;EACH,SAAS,OAAO;GACd,YAAY,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;GACpE,IAAI,YAAY,qBAAqB,MAAM;GAC3C;EACF;EACA,MAAM,OAAO,MAAM,SAAS,QAAQ;EACpC,IAAI,SAAS,IAAI,OAAO,6BAA6B,MAAM,WAAW,QAAQ,QAAQ;EAEtF,MAAM,QAAQ,OAAO,MAAM,UAAU,WAAW,IAAI,KAAK,UAAU;EACnE,4BAAY,IAAI,MAAM,yCAAyC,SAAS,SAAS,OAAO;EAExF,IAAI,EADc,SAAS,WAAW,OAAO,SAAS,UAAU,QAC9C,YAAY,qBAAqB,MAAM;CAC3D;CACA,MAAM,6BAAa,IAAI,MAAM,sCAAsC;AACrE;AAEA,MAAa,0BAAkD;CAC7D,IAAI;CACJ,MAAM;CACN,OAAO;CACP,eAAc,gBACZ,uBAAuB,YAAY,SAAS,EAC1C,UAAU,OAAO,YAAY,aAAa,WAAW,YAAY,WAAW,GAC9E,CAAC;CACH,YAAW,gBAAe,YAAY;AACxC"}
1
+ {"version":3,"file":"kimi-coding.js","names":[],"sources":["../../../src/auth/providers/kimi-coding.ts"],"sourcesContent":["import { arch, hostname, platform, release } from 'node:os';\nimport { getCurrentVersion } from '../../utils/update-check.js';\nimport {\n abortableSleep,\n createDeviceCodePollState,\n pollDeviceCodeUntilComplete,\n stepDeviceCodePoll,\n} from '../device-code.js';\nimport type { DeviceCodePollOutcome, DeviceCodePollState } from '../device-code.js';\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';\n\nconst CLIENT_ID = '17e5f671-d194-4dfb-9706-5516cb48c098';\nconst OAUTH_HOST = 'https://auth.kimi.com';\nconst DEVICE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst DEFAULT_EXPIRES_IN_SECONDS = 15 * 60;\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\nconst REQUEST_TIMEOUT_MS = 30_000;\nconst REFRESH_MAX_RETRIES = 3;\n\nfunction asciiHeaderValue(value: string): string {\n const sanitized = value.replace(/[^\\x20-\\x7E]/g, '').trim();\n return sanitized || 'unknown';\n}\n\nconst KIMI_DEVICE_DETAILS = {\n 'X-Msh-Platform': 'mastracode',\n 'X-Msh-Version': asciiHeaderValue(getCurrentVersion()),\n 'X-Msh-Device-Name': asciiHeaderValue(hostname()),\n 'X-Msh-Device-Model': asciiHeaderValue(`${platform()} ${arch()}`),\n 'X-Msh-Os-Version': asciiHeaderValue(release()),\n};\n\nexport function createKimiCodingDeviceId(): string {\n return globalThis.crypto.randomUUID().replaceAll('-', '');\n}\n\nexport function isKimiCodingDeviceId(value: unknown): value is string {\n return typeof value === 'string' && DEVICE_ID_PATTERN.test(value);\n}\n\nexport function getKimiCodingDeviceHeaders(deviceId: string): Record<string, string> {\n if (!isKimiCodingDeviceId(deviceId)) {\n throw new Error('Kimi For Coding credentials have an invalid device ID. Please reconnect the account.');\n }\n return { ...KIMI_DEVICE_DETAILS, 'X-Msh-Device-Id': deviceId };\n}\n\nfunction requestSignal(signal?: AbortSignal): AbortSignal {\n const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);\n return signal ? AbortSignal.any([timeout, signal]) : timeout;\n}\n\nfunction trustedHttpUrl(value: unknown): string | null {\n if (typeof value !== 'string' || !value) return null;\n try {\n const url = new URL(value);\n return url.protocol === 'https:' ? url.href : null;\n } catch {\n return null;\n }\n}\n\nasync function readJson(response: Response): Promise<Record<string, unknown> | null> {\n try {\n const value = (await response.json()) as unknown;\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\nfunction credentialsFromTokenResponse(value: unknown, operation: string, deviceId: string): OAuthCredentials {\n const data = (value ?? {}) as Record<string, unknown>;\n const access = data.access_token;\n const refresh = data.refresh_token;\n const expiresIn = data.expires_in;\n if (\n typeof access !== 'string' ||\n !access ||\n typeof refresh !== 'string' ||\n !refresh ||\n typeof expiresIn !== 'number' ||\n !Number.isFinite(expiresIn) ||\n expiresIn <= 0\n ) {\n throw new Error(`Kimi For Coding token ${operation} response missing fields`);\n }\n return { access, refresh, expires: Date.now() + expiresIn * 1000, deviceId };\n}\n\nexport interface KimiCodingDeviceLoginPending {\n clientId: string;\n deviceId: string;\n deviceCode: string;\n userCode: string;\n url: string;\n instructions: string;\n state: DeviceCodePollState;\n}\n\nexport type KimiCodingDevicePollResult =\n | { status: 'complete'; credentials: OAuthCredentials }\n | { status: 'pending'; nextPollMs: number; pending: KimiCodingDeviceLoginPending }\n | { status: 'failed'; error: string };\n\nexport async function startKimiCodingDeviceLogin(options?: {\n signal?: AbortSignal;\n}): Promise<KimiCodingDeviceLoginPending> {\n const clientId = CLIENT_ID;\n const deviceId = createKimiCodingDeviceId();\n const response = await fetch(`${OAUTH_HOST}/api/oauth/device_authorization`, {\n method: 'POST',\n headers: {\n ...getKimiCodingDeviceHeaders(deviceId),\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({ client_id: clientId }).toString(),\n signal: requestSignal(options?.signal),\n });\n if (!response.ok) {\n throw new Error(`Kimi For Coding device authorization failed: ${response.status}`);\n }\n\n const data = await readJson(response);\n const deviceCode = data?.device_code;\n const userCode = data?.user_code;\n const verificationUri = trustedHttpUrl(data?.verification_uri);\n const verificationUriComplete = trustedHttpUrl(data?.verification_uri_complete);\n if (\n typeof deviceCode !== 'string' ||\n !deviceCode ||\n typeof userCode !== 'string' ||\n !userCode ||\n !verificationUri ||\n !verificationUriComplete\n ) {\n throw new Error('Invalid Kimi For Coding device authorization response');\n }\n\n const interval = data?.interval;\n const expiresIn = data?.expires_in;\n return {\n clientId,\n deviceId,\n deviceCode,\n userCode,\n url: verificationUriComplete,\n instructions: `Enter code: ${userCode}`,\n state: createDeviceCodePollState({\n intervalSeconds:\n typeof interval === 'number' && Number.isFinite(interval) && interval > 0\n ? interval\n : DEFAULT_POLL_INTERVAL_SECONDS,\n expiresInSeconds:\n typeof expiresIn === 'number' && Number.isFinite(expiresIn) && expiresIn > 0\n ? expiresIn\n : DEFAULT_EXPIRES_IN_SECONDS,\n }),\n };\n}\n\nasync function pollKimiCodingTokenOnce(\n pending: KimiCodingDeviceLoginPending,\n signal?: AbortSignal,\n): Promise<DeviceCodePollOutcome<OAuthCredentials>> {\n const response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {\n method: 'POST',\n headers: {\n ...getKimiCodingDeviceHeaders(pending.deviceId),\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({\n client_id: pending.clientId,\n device_code: pending.deviceCode,\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n }).toString(),\n signal: requestSignal(signal),\n });\n const data = await readJson(response);\n if (response.ok && typeof data?.access_token === 'string') {\n try {\n return { status: 'complete', result: credentialsFromTokenResponse(data, 'poll', pending.deviceId) };\n } catch (error) {\n return { status: 'failed', error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n const error = data?.error;\n if (error === 'authorization_pending') return { status: 'pending' };\n if (error === 'slow_down') {\n return {\n status: 'slow_down',\n intervalSeconds: typeof data?.interval === 'number' && data.interval > 0 ? data.interval : undefined,\n };\n }\n if (error === 'expired_token') {\n return { status: 'failed', error: 'Kimi For Coding authorization expired. Please restart login.' };\n }\n if (error === 'access_denied') return { status: 'failed', error: 'Kimi For Coding login was denied.' };\n return {\n status: 'failed',\n error: `Kimi For Coding token request failed: ${response.status}`,\n };\n}\n\nexport async function pollKimiCodingDeviceLogin(\n pending: KimiCodingDeviceLoginPending,\n options?: { signal?: AbortSignal },\n): Promise<KimiCodingDevicePollResult> {\n const step = await stepDeviceCodePoll(pending.state, () => pollKimiCodingTokenOnce(pending, options?.signal));\n if (step.status === 'complete') return { status: 'complete', credentials: step.result };\n if (step.status === 'failed') return { status: 'failed', error: step.error };\n return {\n status: 'pending',\n nextPollMs: step.nextPollMs,\n pending: { ...pending, state: step.state },\n };\n}\n\nexport async function loginKimiCoding(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n const pending = await startKimiCodingDeviceLogin({ signal: callbacks.signal });\n callbacks.onAuth({ url: pending.url, instructions: pending.instructions });\n callbacks.onProgress?.('Waiting for Kimi For Coding device authorization...');\n return pollDeviceCodeUntilComplete({\n state: pending.state,\n pollOnce: () => pollKimiCodingTokenOnce(pending, callbacks.signal),\n signal: callbacks.signal,\n });\n}\n\nexport async function refreshKimiCodingToken(\n refreshToken: string,\n options: { signal?: AbortSignal; deviceId: string },\n): Promise<OAuthCredentials> {\n const clientId = CLIENT_ID;\n const deviceHeaders = getKimiCodingDeviceHeaders(options.deviceId);\n let lastError: Error | undefined;\n for (let attempt = 0; attempt <= REFRESH_MAX_RETRIES; attempt++) {\n if (attempt > 0) await abortableSleep(1000 * 2 ** (attempt - 1), options.signal);\n let response: Response;\n try {\n response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {\n method: 'POST',\n headers: {\n ...deviceHeaders,\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: new URLSearchParams({\n client_id: clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }).toString(),\n signal: requestSignal(options.signal),\n });\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt === REFRESH_MAX_RETRIES) throw lastError;\n continue;\n }\n const data = await readJson(response);\n if (response.ok) return credentialsFromTokenResponse(data, 'refresh', options.deviceId);\n\n const error = typeof data?.error === 'string' ? ` ${data.error}` : '';\n lastError = new Error(`Kimi For Coding token refresh failed: ${response.status}${error}`);\n const retryable = response.status === 429 || response.status >= 500;\n if (!retryable || attempt === REFRESH_MAX_RETRIES) throw lastError;\n }\n throw lastError ?? new Error('Kimi For Coding token refresh failed');\n}\n\nexport const kimiCodingOAuthProvider: OAuthProviderInterface = {\n id: 'kimi-for-coding',\n name: 'Kimi For Coding',\n login: loginKimiCoding,\n refreshToken: credentials =>\n refreshKimiCodingToken(credentials.refresh, {\n deviceId: typeof credentials.deviceId === 'string' ? credentials.deviceId : '',\n }),\n getApiKey: credentials => credentials.access,\n};\n"],"mappings":";;;;AAWA,MAAM,YAAY;AAClB,MAAM,aAAa;AACnB,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B;AACnC,MAAM,gCAAgC;AACtC,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAE5B,SAAS,iBAAiB,OAAuB;CAE/C,OADkB,MAAM,QAAQ,iBAAiB,EAAE,CAAC,CAAC,KACtC,KAAK;AACtB;AAEA,MAAM,sBAAsB;CAC1B,kBAAkB;CAClB,iBAAiB,iBAAiB,kBAAkB,CAAC;CACrD,qBAAqB,iBAAiB,SAAS,CAAC;CAChD,sBAAsB,iBAAiB,GAAG,SAAS,EAAE,GAAG,KAAK,GAAG;CAChE,oBAAoB,iBAAiB,QAAQ,CAAC;AAChD;AAEA,SAAgB,2BAAmC;CACjD,OAAO,WAAW,OAAO,WAAW,CAAC,CAAC,WAAW,KAAK,EAAE;AAC1D;AAEA,SAAgB,qBAAqB,OAAiC;CACpE,OAAO,OAAO,UAAU,YAAY,kBAAkB,KAAK,KAAK;AAClE;AAEA,SAAgB,2BAA2B,UAA0C;CACnF,IAAI,CAAC,qBAAqB,QAAQ,GAChC,MAAM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IAAI,UAAU,GAAG,WAAW,qBAAqB,WAAW;EAC/D,IAAI,UAAU,GAAG,MAAM,eAAe,MAAO,MAAM,UAAU,IAAI,QAAQ,MAAM;EAC/E,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,MAAM,GAAG,WAAW,mBAAmB;IACtD,QAAQ;IACR,SAAS;KACP,GAAG;KACH,gBAAgB;KAChB,QAAQ;IACV;IACA,MAAM,IAAI,gBAAgB;KACxB,WAAW;KACX,YAAY;KACZ,eAAe;IACjB,CAAC,CAAC,CAAC,SAAS;IACZ,QAAQ,cAAc,QAAQ,MAAM;GACtC,CAAC;EACH,SAAS,OAAO;GACd,YAAY,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;GACpE,IAAI,YAAY,qBAAqB,MAAM;GAC3C;EACF;EACA,MAAM,OAAO,MAAM,SAAS,QAAQ;EACpC,IAAI,SAAS,IAAI,OAAO,6BAA6B,MAAM,WAAW,QAAQ,QAAQ;EAEtF,MAAM,QAAQ,OAAO,MAAM,UAAU,WAAW,IAAI,KAAK,UAAU;EACnE,4BAAY,IAAI,MAAM,yCAAyC,SAAS,SAAS,OAAO;EAExF,IAAI,EADc,SAAS,WAAW,OAAO,SAAS,UAAU,QAC9C,YAAY,qBAAqB,MAAM;CAC3D;CACA,MAAM,6BAAa,IAAI,MAAM,sCAAsC;AACrE;AAEA,MAAa,0BAAkD;CAC7D,IAAI;CACJ,MAAM;CACN,OAAO;CACP,eAAc,gBACZ,uBAAuB,YAAY,SAAS,EAC1C,UAAU,OAAO,YAAY,aAAa,WAAW,YAAY,WAAW,GAC9E,CAAC;CACH,YAAW,gBAAe,YAAY;AACxC"}
@@ -4,7 +4,7 @@
4
4
  * Inspired by pi-mono's OAuth implementation:
5
5
  * https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/openai-codex.ts
6
6
  *
7
- * NOTE: This module uses Node.js crypto and http for the OAuth callback.
7
+ * NOTE: This module uses Node.js http for the OAuth callback.
8
8
  * It is only intended for CLI use, not browser environments.
9
9
  */
10
10
  import type { AuthMode, OAuthCredentials, OAuthPrompt, OAuthProviderInterface } from '../types.js';
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/auth/providers/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA6BH,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAuB,WAAW,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAExH,eAAO,MAAM,uBAAuB,EAAE,aAAa,CAAC,QAAQ,CAW3D,CAAC;AAgBF,QAAA,MAAM,cAAc,gCAAgC,CAAC;AAwBrD,KAAK,UAAU,GAAG;IAChB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,CAAC,cAAc,CAAC,CAAC,EAAE;QACjB,kBAAkB,CAAC,EAAE,MAAM,CAAC;QAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,CAAC;IACF,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAYF,iBAAS,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAcnD;AAED,iBAAS,0BAA0B,CAAC,OAAO,EAAE,UAAU,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAIzF;AAED,iBAAS,YAAY,CAAC,MAAM,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAQzG;AAED,iBAAS,gBAAgB,CAAC,MAAM,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAMjG;AAoGD,iBAAe,uBAA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,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;CAC7B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA2H5B;AAED,eAAO,MAAM,SAAS;;;;;;;;CAQrB,CAAC;AAEF;;GAEG;AACH,wBAAsB,uBAAuB,CAC3C,YAAY,EAAE,MAAM,EACpB,iBAAiB,CAAC,EAAE,MAAM,EAC1B,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,gBAAgB,CAAC,CAe3B;AAED,eAAO,MAAM,wBAAwB,EAAE,sBA2CtC,CAAC"}
@@ -7,23 +7,15 @@ import { generatePKCE } from "../pkce.js";
7
7
  * Inspired by pi-mono's OAuth implementation:
8
8
  * https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/openai-codex.ts
9
9
  *
10
- * NOTE: This module uses Node.js crypto and http for the OAuth callback.
10
+ * NOTE: This module uses Node.js http for the OAuth callback.
11
11
  * It is only intended for CLI use, not browser environments.
12
12
  */
13
- let _randomBytes = null;
14
- let _cryptoPromise = null;
15
13
  let _httpPromise = null;
16
14
  let _http = null;
17
- if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
18
- _cryptoPromise = import("crypto").then((m) => {
19
- _randomBytes = m.randomBytes;
20
- return m;
21
- });
22
- _httpPromise = import("http").then((m) => {
23
- _http = m;
24
- return m;
25
- });
26
- }
15
+ if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) _httpPromise = import("http").then((m) => {
16
+ _http = m;
17
+ return m;
18
+ });
27
19
  const OPENAI_CODEX_AUTH_MODES = [{
28
20
  id: "browser",
29
21
  name: "Browser (local callback)",
@@ -64,7 +56,8 @@ function requestSignal(signal) {
64
56
  return signal ? AbortSignal.any([timeout, signal]) : timeout;
65
57
  }
66
58
  async function createState() {
67
- return (await getRandomBytes())(16).toString("hex");
59
+ if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
60
+ return Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))).toString("hex");
68
61
  }
69
62
  function decodeJwt(token) {
70
63
  try {
@@ -158,11 +151,6 @@ async function refreshAccessToken(refreshToken) {
158
151
  return { type: "failed" };
159
152
  }
160
153
  }
161
- async function getRandomBytes() {
162
- if (!_randomBytes && _cryptoPromise) _randomBytes = (await _cryptoPromise).randomBytes;
163
- if (!_randomBytes) throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
164
- return _randomBytes;
165
- }
166
154
  async function createAuthorizationFlow(redirectUri, state, originator = "mastracode") {
167
155
  const { verifier, challenge } = await generatePKCE();
168
156
  const url = new URL(AUTHORIZE_URL);