@mastra/factory 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (72) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/capabilities/intake.d.ts +2 -0
  3. package/dist/capabilities/intake.d.ts.map +1 -1
  4. package/dist/capabilities/version-control.d.ts +6 -0
  5. package/dist/capabilities/version-control.d.ts.map +1 -1
  6. package/dist/factory.d.ts.map +1 -1
  7. package/dist/factory.js +912 -242
  8. package/dist/factory.js.map +1 -1
  9. package/dist/index.js +912 -242
  10. package/dist/index.js.map +1 -1
  11. package/dist/integrations/github/integration.d.ts +2 -2
  12. package/dist/integrations/github/integration.js +45 -12
  13. package/dist/integrations/github/integration.js.map +1 -1
  14. package/dist/integrations/github/provenance.js.map +1 -1
  15. package/dist/integrations/github/routes.js +12 -10
  16. package/dist/integrations/github/routes.js.map +1 -1
  17. package/dist/integrations/github/sandbox.d.ts +1 -0
  18. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  19. package/dist/integrations/github/sandbox.js +2 -2
  20. package/dist/integrations/github/sandbox.js.map +1 -1
  21. package/dist/integrations/github/session-subscriptions.d.ts +3 -0
  22. package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
  23. package/dist/integrations/github/session-subscriptions.js +30 -0
  24. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  25. package/dist/integrations/github/token-refresh.d.ts +6 -0
  26. package/dist/integrations/github/token-refresh.d.ts.map +1 -0
  27. package/dist/integrations/github/token-refresh.js +17 -0
  28. package/dist/integrations/github/token-refresh.js.map +1 -0
  29. package/dist/integrations/platform/api-client.d.ts +2 -0
  30. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  31. package/dist/integrations/platform/api-client.js +7 -0
  32. package/dist/integrations/platform/api-client.js.map +1 -1
  33. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  34. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  35. package/dist/integrations/platform/github/integration.js +173 -45
  36. package/dist/integrations/platform/github/integration.js.map +1 -1
  37. package/dist/integrations/platform/linear/integration.js +3 -0
  38. package/dist/integrations/platform/linear/integration.js.map +1 -1
  39. package/dist/routes/config.d.ts +16 -11
  40. package/dist/routes/config.d.ts.map +1 -1
  41. package/dist/routes/config.js +222 -109
  42. package/dist/routes/config.js.map +1 -1
  43. package/dist/routes/custom-provider-source.d.ts +52 -0
  44. package/dist/routes/custom-provider-source.d.ts.map +1 -0
  45. package/dist/routes/custom-provider-source.js +107 -0
  46. package/dist/routes/custom-provider-source.js.map +1 -0
  47. package/dist/routes/oauth.js +33 -1
  48. package/dist/routes/oauth.js.map +1 -1
  49. package/dist/routes/surface.d.ts +4 -0
  50. package/dist/routes/surface.d.ts.map +1 -1
  51. package/dist/routes/surface.js +266 -110
  52. package/dist/routes/surface.js.map +1 -1
  53. package/dist/sandbox/fleet.d.ts +3 -0
  54. package/dist/sandbox/fleet.d.ts.map +1 -1
  55. package/dist/sandbox/fleet.js +10 -3
  56. package/dist/sandbox/fleet.js.map +1 -1
  57. package/dist/spa-static.d.ts +4 -5
  58. package/dist/spa-static.d.ts.map +1 -1
  59. package/dist/spa-static.js +5 -2
  60. package/dist/spa-static.js.map +1 -1
  61. package/dist/storage/domains/custom-providers/base.d.ts +57 -0
  62. package/dist/storage/domains/custom-providers/base.d.ts.map +1 -0
  63. package/dist/storage/domains/custom-providers/base.js +150 -0
  64. package/dist/storage/domains/custom-providers/base.js.map +1 -0
  65. package/dist/storage/domains/memory-settings/base.d.ts +62 -0
  66. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -0
  67. package/dist/storage/domains/memory-settings/base.js +111 -0
  68. package/dist/storage/domains/memory-settings/base.js.map +1 -0
  69. package/dist/workspace.d.ts.map +1 -1
  70. package/dist/workspace.js +17 -0
  71. package/dist/workspace.js.map +1 -1
  72. package/package.json +8 -7
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/routes/config.ts","../../src/routes/provider-credentials.ts","../../src/routes/route.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport { removeCustomPackFromSettings } from '@mastra/code-sdk/onboarding/custom-packs';\nimport {\n removeCustomProviderFromSettings,\n upsertCustomProviderInSettings,\n} from '@mastra/code-sdk/onboarding/custom-providers';\nimport { applyOmRoleOverride, persistOmObserveAttachments } from '@mastra/code-sdk/onboarding/om-settings';\nimport { getAvailableModePacks } from '@mastra/code-sdk/onboarding/packs';\nimport type { ModePack, ProviderAccess, ProviderAccessLevel } from '@mastra/code-sdk/onboarding/packs';\nimport {\n getCustomProviderId,\n loadSettings,\n saveSettings,\n THREAD_ACTIVE_MODEL_PACK_ID_KEY,\n} from '@mastra/code-sdk/onboarding/settings';\nimport type { CustomProviderSetting } from '@mastra/code-sdk/onboarding/settings';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\n\nimport type { Context } from 'hono';\nimport type {\n CredentialRecord,\n LoginSessionKind,\n ModelCredentialsStorage,\n} from '../storage/domains/credentials/base.js';\nimport type { ModelPackRecord, ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport {\n getAuthProviderId,\n listTenantCredentialsForRequest,\n resolveCredentialContext,\n tenantOrgId,\n WEB_OAUTH_FLOW_KINDS,\n} from './provider-credentials.js';\nimport { Route } from './route.js';\nimport type { RouteAuth, RouteDependencies } from './route.js';\n\n/** Widen a route-local Hono context to the plain `Context` the auth helpers take. */\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\n/**\n * Server-side configuration routes for the web app.\n *\n * The browser has no access to the credential store or the model catalog, so\n * the web settings panel asks the server — which owns both — to list providers\n * and manage API keys. This mirrors the TUI's `/api-keys` command, exposing the\n * same `AuthStorage`-backed key management over HTTP.\n *\n * Keys are never returned to the client; only their presence and source.\n */\n\n/**\n * Where a provider's active credential comes from, as seen by the caller.\n * Local mode reports `oauth`/`stored` (server-global `auth.json`); tenant mode\n * reports the scoped variants (`oauth-user`/`stored-user`/`stored-org`).\n */\nexport type ProviderCredentialSource =\n 'oauth' | 'stored' | 'env' | 'none' | 'oauth-user' | 'stored-user' | 'stored-org';\n\n/** A model provider with the current source of its credentials. */\nexport interface ProviderInfo {\n provider: string;\n /** Env var the provider's key is read from, if any. */\n envVar?: string;\n /** Where the active credential comes from. */\n source: ProviderCredentialSource;\n /** Web OAuth sign-in capability, when the provider supports it. */\n oauth?: { supported: true; modes: LoginSessionKind[] };\n}\n\n/** Minimal session surface a pack activation touches. */\ninterface PackSession {\n mode: { get: () => string };\n model: { switch: (args: { modelId: string }) => Promise<void> };\n subagents: { model: { set: (args: { modelId: string; agentType: string }) => Promise<void> } };\n thread: {\n getId: () => string | null;\n setSetting: (args: { key: string; value: unknown }) => Promise<void>;\n list: () => Promise<Array<{ id: string; metadata?: Record<string, unknown> }>>;\n };\n}\n\n/** One observational-memory role's read/switch surface. */\ninterface OMRole {\n modelId: () => string | undefined;\n threshold: () => number | undefined;\n switchModel: (args: { modelId: string }) => Promise<void>;\n}\n\n/**\n * Session-state fields the OM config routes write. The index signatures mirror\n * `MastraCodeState` so the concrete `Session.state.set(Partial<MastraCodeState>)`\n * stays assignable to this minimal surface (contravariant parameter check).\n */\ninterface OMStateWrites {\n [key: string]: unknown;\n [key: `subagentModelId_${string}`]: string | undefined;\n observationThreshold?: number;\n reflectionThreshold?: number;\n observeAttachments?: 'auto' | boolean;\n}\n\n/** Minimal session surface the OM config routes touch. */\nexport interface OMSession extends PackSession {\n state: {\n get: () => Record<string, unknown> | undefined;\n set: (updates: OMStateWrites) => Promise<void> | void;\n };\n om: { observer: OMRole; reflector: OMRole };\n}\n\n/** Minimal controller surface this module needs (model catalog + modes + sessions). */\ninterface ModelCatalog {\n listAvailableModels: () => Promise<\n Array<{ id?: string; modelName?: string; provider: string; hasApiKey: boolean; apiKeyEnvVar?: string }>\n >;\n listModes?: () => Array<{ id: string; defaultModelId?: string }>;\n getSessionByResource?: (resourceId: string, scope?: string) => Promise<OMSession | undefined>;\n}\n\n/**\n * Build a deduplicated, sorted list of providers from the model catalog,\n * annotated with where each provider's credential currently comes from.\n * Mirrors the TUI's `/api-keys` provider list.\n *\n * When `tenantCredentials` is given (deployed mode), sources reflect the\n * *caller's* tenant rows with user > org precedence and the server-global\n * `authStorage` is ignored; otherwise the local `auth.json` view is reported.\n */\nexport async function listProviders({\n controller,\n authStorage,\n tenantCredentials,\n}: {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n tenantCredentials?: CredentialRecord[];\n}): Promise<ProviderInfo[]> {\n const models = await controller.listAvailableModels();\n const seen = new Map<string, ProviderInfo>();\n\n for (const model of models) {\n if (seen.has(model.provider)) continue;\n\n const authProviderId = getAuthProviderId(model.provider);\n let source: ProviderInfo['source'] = 'none';\n if (tenantCredentials) {\n const userRec = tenantCredentials.find(r => r.scope === 'user' && r.provider === authProviderId);\n const orgRec = tenantCredentials.find(r => r.scope === 'org' && r.provider === authProviderId);\n if (userRec?.credential.type === 'oauth') {\n source = 'oauth-user';\n } else if (userRec?.credential.type === 'api_key') {\n source = 'stored-user';\n } else if (orgRec?.credential.type === 'api_key') {\n source = 'stored-org';\n }\n } else if (authStorage?.isLoggedIn(authProviderId)) {\n source = 'oauth';\n } else if (authStorage?.hasStoredApiKey(model.provider)) {\n source = 'stored';\n } else if (model.apiKeyEnvVar && process.env[model.apiKeyEnvVar]) {\n source = 'env';\n } else if (model.hasApiKey) {\n source = 'env';\n }\n\n const flowKind = WEB_OAUTH_FLOW_KINDS[model.provider];\n seen.set(model.provider, {\n provider: model.provider,\n envVar: model.apiKeyEnvVar,\n source,\n ...(flowKind ? { oauth: { supported: true as const, modes: [flowKind] } } : {}),\n });\n }\n\n return Array.from(seen.values()).sort((a, b) => a.provider.localeCompare(b.provider));\n}\n\n/** A user-defined OpenAI-compatible provider, with key presence (never the key). */\nexport interface CustomProviderInfo {\n id: string;\n name: string;\n url: string;\n hasApiKey: boolean;\n models: string[];\n}\n\n/** Read the saved custom providers from global settings (keys redacted). */\nexport function listCustomProviders(): CustomProviderInfo[] {\n const settings = loadSettings();\n return settings.customProviders.map(p => ({\n id: getCustomProviderId(p.name),\n name: p.name,\n url: p.url,\n hasApiKey: Boolean(p.apiKey),\n models: p.models,\n }));\n}\n\n/** Validate + coerce a request body into a CustomProviderSetting. */\nfunction parseCustomProviderBody(body: unknown): CustomProviderSetting | { error: string } {\n if (!body || typeof body !== 'object') return { error: 'Invalid JSON body' };\n const b = body as Record<string, unknown>;\n const name = typeof b.name === 'string' ? b.name.trim() : '';\n if (!name) return { error: 'Missing required field: name' };\n const url = typeof b.url === 'string' ? b.url.trim() : '';\n if (!url) return { error: 'Missing required field: url' };\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return { error: 'url must be an http(s) URL' };\n }\n } catch {\n return { error: 'url must be a valid URL' };\n }\n const apiKey = typeof b.apiKey === 'string' && b.apiKey.trim() ? b.apiKey.trim() : undefined;\n const models = Array.isArray(b.models)\n ? b.models.filter((m): m is string => typeof m === 'string' && m.trim().length > 0).map(m => m.trim())\n : [];\n return { name, url, apiKey, models };\n}\n\n// ── Model packs ──────────────────────────────────────────────────────────\n\n/** A model pack as surfaced to the web client, with an `active` flag. */\nexport interface ModelPackInfo extends ModePack {\n custom: boolean;\n active: boolean;\n}\n\n/**\n * Compute which providers the user can reach, mirroring the TUI's\n * `/models-pack` access derivation: OAuth/api-key from the credential store for\n * the named providers, plus any other provider that has a usable key.\n */\nexport async function buildProviderAccess({\n controller,\n authStorage,\n tenantCredentials,\n}: {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n tenantCredentials?: CredentialRecord[];\n}): Promise<ProviderAccess> {\n const models = await controller.listAvailableModels();\n const hasModelKey = (provider: string) => models.some(m => m.provider === provider && m.hasApiKey);\n const accessLevel = (provider: string): ProviderAccessLevel => {\n const authProviderId = getAuthProviderId(provider);\n if (tenantCredentials) {\n const userRec = tenantCredentials.find(r => r.scope === 'user' && r.provider === authProviderId);\n const orgRec = tenantCredentials.find(r => r.scope === 'org' && r.provider === authProviderId);\n const credential = userRec?.credential ?? orgRec?.credential;\n if (credential?.type === 'oauth') return 'oauth';\n if (credential?.type === 'api_key' && credential.key.trim().length > 0) return 'apikey';\n return false;\n }\n\n const oauthCredential = authStorage?.get(authProviderId);\n if (oauthCredential?.type === 'oauth') return 'oauth';\n if (authStorage?.hasStoredApiKey(provider)) return 'apikey';\n const directCredential = authStorage?.get(provider);\n if (directCredential?.type === 'api_key' && directCredential.key.trim().length > 0) return 'apikey';\n return hasModelKey(provider) ? 'apikey' : false;\n };\n const access: ProviderAccess = {\n anthropic: accessLevel('anthropic'),\n openai: accessLevel('openai'),\n cerebras: accessLevel('cerebras'),\n google: accessLevel('google'),\n deepseek: accessLevel('deepseek'),\n 'github-copilot': accessLevel('github-copilot'),\n };\n const seen = new Set(Object.keys(access));\n for (const m of models) {\n if (!seen.has(m.provider)) {\n access[m.provider] = accessLevel(m.provider);\n seen.add(m.provider);\n }\n }\n return access;\n}\n\nfunction canUseModelProvider(access: ProviderAccess, provider: string): boolean {\n return Boolean(access[provider]);\n}\n\n/**\n * Where a request's custom model packs live. Local mode (no auth adapter)\n * keeps the file-backed `settings.json` store — unchanged TUI behavior. Tenant\n * mode (auth adapter active) uses the `model-packs` factory storage domain,\n * scoped per org. Mirrors `resolveCredentialContext`.\n */\nexport type PackContext =\n { mode: 'local' } | { mode: 'tenant'; storage: ModelPacksStorage; orgId: string; userId: string };\n\n/** The tenant model-packs domain, when registered and ready (fail-soft). */\nasync function getTenantModelPacksStorage(\n modelPacks: ModelPacksStorage | undefined,\n): Promise<ModelPacksStorage | undefined> {\n if (!modelPacks) return undefined;\n try {\n await modelPacks.ensureReady();\n } catch {\n return undefined;\n }\n return modelPacks;\n}\n\n/** Resolve the pack context for a request, or a ready-to-return error response. */\nasync function resolvePackContext({\n c,\n auth,\n modelPacks,\n}: {\n c: Context;\n auth: RouteAuth;\n modelPacks?: ModelPacksStorage;\n}): Promise<PackContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) {\n if (auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n return { mode: 'local' };\n }\n const storage = await getTenantModelPacksStorage(modelPacks);\n if (!storage) {\n return {\n response: c.json(\n {\n error: 'model_packs_unavailable',\n message: 'Model pack storage is unavailable — the app database is not configured or failed to start.',\n },\n 503,\n ),\n };\n }\n return { mode: 'tenant', storage, orgId: tenantOrgId(tenant), userId: tenant.userId };\n}\n\n/** DB row → the `ModePack` shape the packs list and activation flow consume. */\nfunction recordToModePack(record: ModelPackRecord): ModePack {\n return { id: `custom:${record.id}`, name: record.name, description: 'Saved custom pack', models: record.models };\n}\n\n/**\n * List available model packs (built-in, gated by provider access, plus saved\n * custom packs from the request's pack context). Drops the synthetic\n * \"New Custom\" placeholder — the web client has its own create flow. `active`\n * is set from the given session's thread when a resourceId is supplied.\n */\nexport async function listModelPacks({\n controller,\n authStorage,\n tenantCredentials,\n packContext,\n activePackId,\n}: {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n tenantCredentials?: CredentialRecord[];\n packContext: PackContext;\n activePackId?: string | null;\n}): Promise<ModelPackInfo[]> {\n const access = await buildProviderAccess({ controller, authStorage, tenantCredentials });\n const packs =\n packContext.mode === 'local'\n ? getAvailableModePacks(access, loadSettings().customModelPacks)\n : [\n ...getAvailableModePacks(access),\n ...(await packContext.storage.list({ orgId: packContext.orgId })).map(recordToModePack),\n ];\n return packs\n .filter(p => p.id !== 'custom') // synthetic \"choose each model\" placeholder\n .map(p => ({\n ...p,\n custom: p.id.startsWith('custom:'),\n active: activePackId != null && p.id === activePackId,\n }));\n}\n\n/** Resolve the active pack id for a session by reading its current thread. */\nasync function resolveActivePackId(session: PackSession | undefined): Promise<string | null> {\n if (!session) return null;\n const threadId = session.thread.getId();\n if (!threadId) return null;\n const thread = (await session.thread.list()).find(t => t.id === threadId);\n const value = thread?.metadata?.[THREAD_ACTIVE_MODEL_PACK_ID_KEY];\n return typeof value === 'string' ? value : null;\n}\n\n/**\n * Apply a pack to a session: seed each mode's default model, switch the current\n * mode's model, set per-subagent models, and tag the thread with the active\n * pack id. Mirrors the TUI `applyPack` orchestration.\n */\nasync function applyPackToSession({\n controller,\n session,\n pack,\n}: {\n controller: ModelCatalog;\n session: PackSession;\n pack: ModePack;\n}): Promise<void> {\n const modes = controller.listModes?.() ?? [];\n const packModels = pack.models as Record<string, string>;\n\n for (const mode of modes) {\n const modelId = packModels[mode.id];\n if (modelId) {\n mode.defaultModelId = modelId;\n await session.thread.setSetting({ key: `modeModelId_${mode.id}`, value: modelId });\n }\n }\n\n const currentModeModel = packModels[session.mode.get()];\n if (currentModeModel) {\n await session.model.switch({ modelId: currentModeModel });\n }\n\n const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n for (const [agentType, modeId] of Object.entries(subagentModeMap)) {\n const saModelId = packModels[modeId];\n if (saModelId) {\n await session.subagents.model.set({ modelId: saModelId, agentType });\n }\n }\n\n await session.thread.setSetting({ key: THREAD_ACTIVE_MODEL_PACK_ID_KEY, value: pack.id });\n}\n\n// ── Observational memory ────────────────────────────────────────────────────\n// Mirrors the TUI `/om` command. Observer/reflector model + threshold reads come\n// from the session (state, falling back to omConfig defaults); writes go to both\n// the session (state + thread setting, via the same session methods the TUI uses)\n// and GlobalSettings (settings.json), so the choice survives restarts and stays\n// in sync with the terminal.\n\n/** Default thresholds mirror the TUI `/om` fallbacks. */\nconst DEFAULT_OBSERVATION_THRESHOLD = 30_000;\nconst DEFAULT_REFLECTION_THRESHOLD = 40_000;\n\n/** Read the current OM config from a session. */\nexport interface OMConfigInfo {\n observerModelId: string;\n reflectorModelId: string;\n observationThreshold: number;\n reflectionThreshold: number;\n observeAttachments: 'auto' | boolean;\n}\n\nexport function readOMConfig(session: OMSession): OMConfigInfo {\n const state = session.state.get() ?? {};\n const observeAttachments = state.observeAttachments;\n return {\n observerModelId: session.om.observer.modelId() ?? '',\n reflectorModelId: session.om.reflector.modelId() ?? '',\n observationThreshold: session.om.observer.threshold() ?? DEFAULT_OBSERVATION_THRESHOLD,\n reflectionThreshold: session.om.reflector.threshold() ?? DEFAULT_REFLECTION_THRESHOLD,\n observeAttachments: observeAttachments === true || observeAttachments === false ? observeAttachments : 'auto',\n };\n}\n\n/** Persist an OM threshold to GlobalSettings (settings.json), mirroring `/om`. */\nfunction persistOmThreshold({ role, value }: { role: 'observation' | 'reflection'; value: number }): void {\n const settings = loadSettings();\n if (role === 'observation') settings.models.omObservationThreshold = value;\n else settings.models.omReflectionThreshold = value;\n saveSettings(settings);\n}\n\n/** Persist an OM role model override to GlobalSettings, snapshotting the other role. */\nfunction persistOmRoleOverride({\n role,\n modelId,\n otherRoleCurrentModelId,\n}: {\n role: 'observer' | 'reflector';\n modelId: string;\n otherRoleCurrentModelId: string | null;\n}): void {\n const settings = loadSettings();\n applyOmRoleOverride(settings, role, modelId, otherRoleCurrentModelId);\n saveSettings(settings);\n}\n\n/** Dependencies injected into {@link ConfigRoutes}. */\nexport interface ConfigRoutesDeps extends RouteDependencies {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n modelCredentials?: ModelCredentialsStorage;\n /** Tenant model-packs domain handle; absent in local (no-DB) mode. */\n modelPacks?: ModelPacksStorage;\n /** Notifies the host after tenant credentials change so caches can be dropped. */\n onCredentialsChanged?: (tenant: { orgId: string; userId?: string }) => void;\n}\n\n/**\n * The web config routes as Mastra `apiRoutes`:\n * - `GET /web/config/providers` — list providers + key source\n * - `PUT /web/config/providers/:provider/key` — set/update a provider's API key\n * - `DELETE /web/config/providers/:provider/key` — remove a stored API key\n * - `GET /web/config/models` — list available models (credentialed providers)\n * - `GET /web/config/custom-providers` — list custom OpenAI-compatible providers\n * - `POST /web/config/custom-providers` — create/update a custom provider\n * - `DELETE /web/config/custom-providers/:id` — remove a custom provider\n * - `GET /web/config/om` — read OM models/thresholds/observe-attachments\n * - `PUT /web/config/om/:role/model` — switch observer/reflector model\n * - `PUT /web/config/om/thresholds` — set observation/reflection thresholds\n * - `PUT /web/config/om/observe-attachments` — set observe-attachments (auto/on/off)\n */\nexport class ConfigRoutes extends Route<ConfigRoutesDeps> {\n routes(): ApiRoute[] {\n const options = this.deps;\n const { controller, authStorage, auth } = options;\n const onCredentialsChanged = options.onCredentialsChanged ?? (() => {});\n\n return [\n registerApiRoute('/web/config/providers', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n try {\n // Tenant mode lists the caller's rows and never exposes the\n // server-global auth.json; local mode is unchanged.\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n return c.json({\n providers: await listProviders({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n }),\n });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/key', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: options.modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n let body: { key?: unknown; envVar?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const key = typeof body.key === 'string' ? body.key.trim() : '';\n if (!key) return c.json({ error: 'Missing required field: key' }, 400);\n const envVar = typeof body.envVar === 'string' ? body.envVar : undefined;\n const scope = body.scope === 'org' ? 'org' : 'user';\n try {\n if (ctx.mode === 'tenant') {\n if (scope === 'org' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'organization_admin_required' }, 403);\n }\n const tenant = scope === 'org' ? { orgId: ctx.orgId } : { orgId: ctx.orgId, userId: ctx.userId };\n // envVar is intentionally ignored: tenant credentials are resolved\n // per-request, never written into process.env.\n await ctx.storage.setCredential(tenant, getAuthProviderId(provider), { type: 'api_key', key });\n onCredentialsChanged(tenant);\n const records = await ctx.storage.listCredentials(ctx.orgId, ctx.userId);\n const providers = await listProviders({ controller, tenantCredentials: records });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n }\n if (!authStorage) return c.json({ error: 'Credential storage is not available' }, 503);\n // Local mode is single-user: scope is meaningless and ignored.\n authStorage.setStoredApiKey(provider, key, envVar);\n const providers = await listProviders({ controller, authStorage });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/key', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: options.modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const scope = c.req.query('scope') === 'org' ? 'org' : 'user';\n try {\n if (ctx.mode === 'tenant') {\n if (scope === 'org' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'organization_admin_required' }, 403);\n }\n const tenant = scope === 'org' ? { orgId: ctx.orgId } : { orgId: ctx.orgId, userId: ctx.userId };\n await ctx.storage.removeCredential(tenant, getAuthProviderId(provider));\n onCredentialsChanged(tenant);\n const records = await ctx.storage.listCredentials(ctx.orgId, ctx.userId);\n const providers = await listProviders({ controller, tenantCredentials: records });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n }\n if (!authStorage) return c.json({ error: 'Credential storage is not available' }, 503);\n authStorage.remove(`apikey:${provider}`);\n const providers = await listProviders({ controller, authStorage });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Custom providers (OpenAI-compatible endpoints) ──────────────────────\n // Mirrors the TUI's /custom-providers command. Backed by GlobalSettings\n // (settings.json), not session state — these are user-global definitions.\n\n registerApiRoute('/web/config/custom-providers', {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n try {\n return c.json({ providers: listCustomProviders() });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/custom-providers', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const parsed = parseCustomProviderBody(body);\n if ('error' in parsed) return c.json({ error: parsed.error }, 400);\n // `previousId` lets a rename remove the old entry as well as any name clash.\n const previousId =\n body && typeof body === 'object' && typeof (body as Record<string, unknown>).previousId === 'string'\n ? ((body as Record<string, unknown>).previousId as string)\n : undefined;\n try {\n const settings = loadSettings();\n upsertCustomProviderInSettings(settings, parsed, previousId);\n saveSettings(settings);\n const id = getCustomProviderId(parsed.name);\n return c.json({ ok: true, provider: listCustomProviders().find(p => p.id === id) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/custom-providers/:id', {\n method: 'DELETE',\n requiresAuth: false,\n handler: c => {\n const id = c.req.param('id');\n try {\n const settings = loadSettings();\n removeCustomProviderFromSettings(settings, id);\n saveSettings(settings);\n return c.json({ ok: true });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Available models ────────────────────────────────────────────────────\n // Session-independent model catalog for settings pickers (Factory default\n // model, pack editors). Only models whose provider has a credential are\n // returned — the same filter the session-scoped hook applies client-side.\n\n registerApiRoute('/web/config/models', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n try {\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n const [models, access] = await Promise.all([\n controller.listAvailableModels(),\n buildProviderAccess({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n }),\n ]);\n return c.json({\n models: models\n .filter(m => canUseModelProvider(access, m.provider) && typeof m.id === 'string')\n .map(m => ({ id: m.id, provider: m.provider, modelName: m.modelName, hasApiKey: true }))\n .sort((a, b) =>\n a.provider === b.provider ? a.id!.localeCompare(b.id!) : a.provider.localeCompare(b.provider),\n ),\n });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Model packs ─────────────────────────────────────────────────────────\n // Mirrors the TUI's /models-pack command. Custom-pack CRUD is DB-backed in\n // tenant mode (model-packs storage domain, org-scoped) and settings.json in\n // local mode; activation is session-scoped and resolves the session from\n // the controller registry by resourceId.\n\n registerApiRoute('/web/config/model-packs', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n const resourceId = c.req.query('resourceId');\n const scope = c.req.query('scope') || undefined;\n try {\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n const activePackId = await resolveActivePackId(session);\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n return c.json({\n packs: await listModelPacks({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n packContext,\n activePackId,\n }),\n activePackId,\n });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/model-packs', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n let body: { name?: unknown; models?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const name = typeof body.name === 'string' ? body.name.trim() : '';\n if (!name) return c.json({ error: 'Missing required field: name' }, 400);\n const m = (body.models ?? {}) as Record<string, unknown>;\n const build = typeof m.build === 'string' ? m.build.trim() : '';\n const plan = typeof m.plan === 'string' ? m.plan.trim() : '';\n const fast = typeof m.fast === 'string' ? m.fast.trim() : '';\n if (!build || !plan || !fast) {\n return c.json({ error: 'models.build, models.plan and models.fast are required' }, 400);\n }\n try {\n if (packContext.mode === 'tenant') {\n const record = await packContext.storage.upsert({\n orgId: packContext.orgId,\n userId: packContext.userId,\n input: { name, models: { build, plan, fast } },\n });\n return c.json({ ok: true, pack: recordToModePack(record) });\n }\n const settings = loadSettings();\n const entry = { name, models: { build, plan, fast }, createdAt: new Date().toISOString() };\n const idx = settings.customModelPacks.findIndex(p => p.name === name);\n if (idx >= 0) settings.customModelPacks[idx] = entry;\n else settings.customModelPacks.push(entry);\n saveSettings(settings);\n return c.json({ ok: true, pack: { id: `custom:${name}`, name, models: { build, plan, fast } } });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/model-packs/:id', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n const id = decodeURIComponent(c.req.param('id'));\n try {\n if (packContext.mode === 'tenant') {\n const recordId = id.startsWith('custom:') ? id.slice('custom:'.length) : id;\n const deleted = await packContext.storage.delete({ orgId: packContext.orgId, id: recordId });\n return deleted ? c.json({ ok: true }) : c.json({ error: `Unknown pack \"${id}\"` }, 404);\n }\n const settings = loadSettings();\n removeCustomPackFromSettings(settings, id);\n saveSettings(settings);\n return c.json({ ok: true });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/model-packs/:id/activate', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n const id = decodeURIComponent(c.req.param('id'));\n let body: { resourceId?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n const packs = await listModelPacks({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n packContext,\n });\n const pack = packs.find(p => p.id === id);\n if (!pack) return c.json({ error: `Unknown pack \"${id}\"` }, 404);\n await applyPackToSession({ controller, session, pack });\n return c.json({ ok: true, activePackId: pack.id });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Observational memory ──────────────────────────────────────────────────\n // Mirrors the TUI's /om command. All five knobs are session-scoped (resolved\n // from the session, persisted to its state + thread setting) plus written to\n // GlobalSettings so the choice survives restarts and stays in sync with the TUI.\n\n registerApiRoute('/web/config/om', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resourceId = c.req.query('resourceId');\n const scope = c.req.query('scope') || undefined;\n if (!resourceId) return c.json({ error: 'Missing required query param: resourceId' }, 400);\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n return c.json({ config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/om/:role/model', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const role = c.req.param('role');\n if (role !== 'observer' && role !== 'reflector') {\n return c.json({ error: `Unknown OM role \"${role}\"` }, 400);\n }\n let body: { resourceId?: unknown; modelId?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n const modelId = typeof body.modelId === 'string' ? body.modelId.trim() : '';\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n if (!modelId) return c.json({ error: 'Missing required field: modelId' }, 400);\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n const otherRole = role === 'observer' ? session.om.reflector : session.om.observer;\n const otherRoleCurrentModelId = otherRole.modelId() ?? null;\n await session.om[role].switchModel({ modelId });\n persistOmRoleOverride({ role, modelId, otherRoleCurrentModelId });\n return c.json({ ok: true, config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/om/thresholds', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n let body: {\n resourceId?: unknown;\n observationThreshold?: unknown;\n reflectionThreshold?: unknown;\n scope?: unknown;\n };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n const observation =\n typeof body.observationThreshold === 'number' && body.observationThreshold > 0\n ? Math.round(body.observationThreshold)\n : undefined;\n const reflection =\n typeof body.reflectionThreshold === 'number' && body.reflectionThreshold > 0\n ? Math.round(body.reflectionThreshold)\n : undefined;\n if (observation === undefined && reflection === undefined) {\n return c.json({ error: 'Provide observationThreshold and/or reflectionThreshold (positive numbers)' }, 400);\n }\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n if (observation !== undefined) {\n await session.state.set({ observationThreshold: observation });\n await session.thread.setSetting({ key: 'observationThreshold', value: observation });\n persistOmThreshold({ role: 'observation', value: observation });\n }\n if (reflection !== undefined) {\n await session.state.set({ reflectionThreshold: reflection });\n await session.thread.setSetting({ key: 'reflectionThreshold', value: reflection });\n persistOmThreshold({ role: 'reflection', value: reflection });\n }\n return c.json({ ok: true, config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/om/observe-attachments', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n let body: { resourceId?: unknown; value?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n const raw = body.value;\n const value: 'auto' | boolean = raw === 'auto' || raw === true || raw === false ? raw : 'auto';\n if (raw !== 'auto' && raw !== true && raw !== false) {\n return c.json({ error: \"value must be 'auto', true, or false\" }, 400);\n }\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n await session.state.set({ observeAttachments: value });\n await session.thread.setSetting({ key: 'observeAttachments', value });\n persistOmObserveAttachments(value);\n return c.json({ ok: true, config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n ];\n }\n}\n","/**\n * Per-request model-provider credential context.\n *\n * The provider config/OAuth routes serve two deployment shapes:\n *\n * - **Local** (no web auth adapter): credentials live in the server-global\n * file-backed `AuthStorage` (`auth.json`) — unchanged TUI behavior.\n * - **Tenant** (auth adapter active): credentials live in the\n * `model-credentials` factory storage domain, scoped per `(orgId, userId)`\n * with optional org-wide rows (`userId` absent).\n *\n * `resolveCredentialContext` decides which shape a request is in: an\n * authenticated user always gets the tenant path; an unauthenticated request\n * is rejected when auth is enabled and falls back to local otherwise.\n */\n\nimport type { Context } from 'hono';\n\nimport type {\n CredentialRecord,\n LoginSessionKind,\n ModelCredentialsStorage,\n} from '../storage/domains/credentials/base.js';\nimport type { RouteAuth } from './route.js';\n\n/**\n * OAuth credentials are stored under the auth provider id, which differs from\n * the catalog provider id for OpenAI (stored as `openai-codex`). Tenant rows\n * use the same keying so one lookup serves both OAuth tokens and API keys.\n */\nexport function getAuthProviderId(provider: string): string {\n return provider === 'openai' ? 'openai-codex' : provider;\n}\n\n/**\n * Providers that support a browser-driven OAuth sign-in flow, keyed by\n * *catalog* provider id (what the routes and settings UI use). All flows need\n * no inbound connection to the server: Anthropic uses paste-code PKCE, the\n * rest use RFC 8628-style device codes.\n */\nexport const WEB_OAUTH_FLOW_KINDS: Readonly<Record<string, LoginSessionKind>> = {\n anthropic: 'paste-code',\n openai: 'device-code',\n 'github-copilot': 'device-code',\n xai: 'device-code',\n};\n\nexport type CredentialContext =\n { mode: 'local' } | { mode: 'tenant'; storage: ModelCredentialsStorage; orgId: string; userId: string };\n\n/**\n * The tenant credentials domain, when registered and ready. `undefined` means\n * the factory never ran (no handle threaded in) or the domain's init failed\n * (fail-soft — callers report the feature unavailable instead of crashing).\n */\nexport async function getTenantCredentialsStorage(\n credentials: ModelCredentialsStorage | undefined,\n): Promise<ModelCredentialsStorage | undefined> {\n if (!credentials) return undefined;\n try {\n await credentials.ensureReady();\n } catch {\n return undefined;\n }\n return credentials;\n}\n\n/**\n * Org key for tenant rows. Personal accounts get an org bootstrapped by the\n * auth adapter (`ensureOrg`); if one still isn't present, scope rows under a\n * per-user synthetic org so credentials never become server-global.\n */\nexport function tenantOrgId(tenant: { orgId?: string; userId: string }): string {\n return tenant.orgId ?? `user:${tenant.userId}`;\n}\n\n/**\n * Resolve the credential context for a request, or a ready-to-return error\n * response. Mutating credential routes call this and hard-fail (401/503)\n * when the tenant path is required but unavailable.\n */\nexport async function resolveCredentialContext({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) {\n // When an auth provider is active, credential operations always require a\n // signed-in caller — otherwise one anonymous request could write keys for\n // everyone. Without a provider this is a single-user local server.\n if (auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n return { mode: 'local' };\n }\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) {\n return {\n response: c.json(\n {\n error: 'credentials_unavailable',\n message: 'Tenant credential storage is unavailable — the app database is not configured or failed to start.',\n },\n 503,\n ),\n };\n }\n return { mode: 'tenant', storage, orgId: tenantOrgId(tenant), userId: tenant.userId };\n}\n\n/**\n * List the caller's tenant credential records for provider listing, or\n * `undefined` in local mode (caller should fall back to `AuthStorage`).\n * Read-only and degradation-friendly: an authenticated caller with the domain\n * unavailable gets an empty list (sources show `env`/`none`) instead of a 503\n * so the settings page still renders.\n */\nexport async function listTenantCredentialsForRequest({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialRecord[] | undefined> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return auth.enabled() ? [] : undefined;\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) return [];\n return storage.listCredentials(tenantOrgId(tenant), tenant.userId);\n}\n","/**\n * Base class for factory route modules.\n *\n * Route modules build Mastra `apiRoutes` from injected dependencies instead of\n * reaching into host globals. The host server (e.g. `mastracode/web`) supplies\n * the auth seam and storage domain handles at construction time, so the routes\n * stay portable and testable with fakes.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\n/**\n * The auth surface factory routes need, implemented by the host server.\n *\n * Local (no-auth) deployments implement this with a stub where `enabled()`\n * returns `false` and `tenant()` returns `undefined` — routes then take their\n * single-user local paths.\n */\nexport interface RouteAuth {\n /** Whether an auth provider is active (tenant mode). */\n enabled(): boolean;\n /**\n * Resolve (and cache) the signed-in user for the request, if any. Must be\n * called before `tenant()` so the request context is populated.\n */\n ensureUser(c: Context): Promise<unknown>;\n /** Tenant identity for the request, when signed in. */\n tenant(c: Context): { orgId?: string; userId: string } | undefined;\n /** Fail-closed check that the caller administers the given organization. */\n isOrganizationAdmin(c: Context, organizationId: string): Promise<boolean>;\n}\n\n/** Dependencies shared by every factory route module. */\nexport interface RouteDependencies {\n auth: RouteAuth;\n}\n\n/**\n * A route module: constructed once at boot with its dependencies, then asked\n * for the `ApiRoute[]` it serves.\n */\nexport abstract class Route<TDeps extends RouteDependencies = RouteDependencies> {\n protected readonly deps: TDeps;\n\n constructor(deps: TDeps) {\n this.deps = deps;\n }\n\n /** Build the Mastra `apiRoutes` served by this module. */\n abstract routes(): ApiRoute[];\n}\n"],"mappings":";AACA,SAAS,oCAAoC;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,mCAAmC;AACjE,SAAS,6BAA6B;AAEtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,wBAAwB;;;ACa1B,SAAS,kBAAkB,UAA0B;AAC1D,SAAO,aAAa,WAAW,iBAAiB;AAClD;AAQO,IAAM,uBAAmE;AAAA,EAC9E,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,KAAK;AACP;AAUA,eAAsB,4BACpB,aAC8C;AAC9C,MAAI,CAAC,YAAa,QAAO;AACzB,MAAI;AACF,UAAM,YAAY,YAAY;AAAA,EAChC,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,SAAS,YAAY,QAAoD;AAC9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route.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport { DEFAULT_OM_MODEL_ID } from '@mastra/code-sdk/constants';\nimport { getAvailableModePacks } from '@mastra/code-sdk/onboarding/packs';\nimport type { ModePack, ProviderAccess, ProviderAccessLevel } from '@mastra/code-sdk/onboarding/packs';\nimport { getCustomProviderId, THREAD_ACTIVE_MODEL_PACK_ID_KEY } from '@mastra/code-sdk/onboarding/settings';\nimport type { CustomProviderSetting } from '@mastra/code-sdk/onboarding/settings';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\n\nimport type { Context } from 'hono';\nimport type {\n CredentialRecord,\n LoginSessionKind,\n ModelCredentialsStorage,\n} from '../storage/domains/credentials/base.js';\nimport type { CustomProviderRecord, CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type {\n MemorySettingsFillIfUnset,\n MemorySettingsPatch,\n MemorySettingsRecord,\n MemorySettingsStorage,\n} from '../storage/domains/memory-settings/base.js';\nimport type { ModelPackRecord, ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport {\n getAuthProviderId,\n listTenantCredentialsForRequest,\n resolveCredentialContext,\n tenantOrgId,\n WEB_OAUTH_FLOW_KINDS,\n} from './provider-credentials.js';\nimport { Route } from './route.js';\nimport type { RouteAuth, RouteDependencies } from './route.js';\n\n/** Widen a route-local Hono context to the plain `Context` the auth helpers take. */\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\n/**\n * Server-side configuration routes for the web app.\n *\n * The browser has no access to the credential store or the model catalog, so\n * the web settings panel asks the server — which owns both — to list providers\n * and manage API keys. This mirrors the TUI's `/api-keys` command, exposing the\n * same `AuthStorage`-backed key management over HTTP.\n *\n * Keys are never returned to the client; only their presence and source.\n */\n\n/**\n * Where a provider's active credential comes from, as seen by the caller.\n * Local mode reports `oauth`/`stored` (server-global `auth.json`); tenant mode\n * reports the scoped variants (`oauth-user`/`stored-user`/`stored-org`).\n */\nexport type ProviderCredentialSource =\n 'oauth' | 'stored' | 'env' | 'none' | 'oauth-user' | 'stored-user' | 'stored-org';\n\n/** A model provider with the current source of its credentials. */\nexport interface ProviderInfo {\n provider: string;\n /** Env var the provider's key is read from, if any. */\n envVar?: string;\n /** Where the active credential comes from. */\n source: ProviderCredentialSource;\n /** Web OAuth sign-in capability, when the provider supports it. */\n oauth?: { supported: true; modes: LoginSessionKind[] };\n}\n\n/** Minimal session surface a pack activation touches. */\ninterface PackSession {\n mode: { get: () => string };\n model: { switch: (args: { modelId: string }) => Promise<void> };\n subagents: { model: { set: (args: { modelId: string; agentType: string }) => Promise<void> } };\n thread: {\n getId: () => string | null;\n setSetting: (args: { key: string; value: unknown }) => Promise<void>;\n list: () => Promise<Array<{ id: string; metadata?: Record<string, unknown> }>>;\n };\n}\n\n/** One observational-memory role's read/switch surface. */\ninterface OMRole {\n modelId: () => string | undefined;\n threshold: () => number | undefined;\n switchModel: (args: { modelId: string }) => Promise<void>;\n}\n\n/**\n * Session-state fields the OM config routes write. The index signatures mirror\n * `MastraCodeState` so the concrete `Session.state.set(Partial<MastraCodeState>)`\n * stays assignable to this minimal surface (contravariant parameter check).\n */\ninterface OMStateWrites {\n [key: string]: unknown;\n [key: `subagentModelId_${string}`]: string | undefined;\n observationThreshold?: number;\n reflectionThreshold?: number;\n observeAttachments?: 'auto' | boolean;\n}\n\n/** Minimal session surface the OM config routes touch. */\nexport interface OMSession extends PackSession {\n state: {\n get: () => Record<string, unknown> | undefined;\n set: (updates: OMStateWrites) => Promise<void> | void;\n };\n om: { observer: OMRole; reflector: OMRole };\n}\n\n/** Minimal controller surface this module needs (model catalog + modes + sessions). */\ninterface ModelCatalog {\n listAvailableModels: () => Promise<\n Array<{ id?: string; modelName?: string; provider: string; hasApiKey: boolean; apiKeyEnvVar?: string }>\n >;\n listModes?: () => Array<{ id: string; defaultModelId?: string }>;\n getSessionByResource?: (resourceId: string, scope?: string) => Promise<OMSession | undefined>;\n}\n\n/**\n * Build a deduplicated, sorted list of providers from the model catalog,\n * annotated with where each provider's credential currently comes from.\n * Mirrors the TUI's `/api-keys` provider list.\n *\n * When `tenantCredentials` is given (deployed mode), sources reflect the\n * *caller's* tenant rows with user > org precedence and the server-global\n * `authStorage` is ignored; otherwise the local `auth.json` view is reported.\n */\nexport async function listProviders({\n controller,\n authStorage,\n tenantCredentials,\n}: {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n tenantCredentials?: CredentialRecord[];\n}): Promise<ProviderInfo[]> {\n const models = await controller.listAvailableModels();\n const seen = new Map<string, ProviderInfo>();\n\n for (const model of models) {\n if (seen.has(model.provider)) continue;\n\n const authProviderId = getAuthProviderId(model.provider);\n let source: ProviderInfo['source'] = 'none';\n if (tenantCredentials) {\n const userRec = tenantCredentials.find(r => r.scope === 'user' && r.provider === authProviderId);\n const orgRec = tenantCredentials.find(r => r.scope === 'org' && r.provider === authProviderId);\n if (userRec?.credential.type === 'oauth') {\n source = 'oauth-user';\n } else if (userRec?.credential.type === 'api_key') {\n source = 'stored-user';\n } else if (orgRec?.credential.type === 'api_key') {\n source = 'stored-org';\n }\n } else if (authStorage?.isLoggedIn(authProviderId)) {\n source = 'oauth';\n } else if (authStorage?.hasStoredApiKey(model.provider)) {\n source = 'stored';\n } else if (model.apiKeyEnvVar && process.env[model.apiKeyEnvVar]) {\n source = 'env';\n } else if (model.hasApiKey) {\n source = 'env';\n }\n\n const flowKind = WEB_OAUTH_FLOW_KINDS[model.provider];\n seen.set(model.provider, {\n provider: model.provider,\n envVar: model.apiKeyEnvVar,\n source,\n ...(flowKind ? { oauth: { supported: true as const, modes: [flowKind] } } : {}),\n });\n }\n\n return Array.from(seen.values()).sort((a, b) => a.provider.localeCompare(b.provider));\n}\n\n/** A user-defined OpenAI-compatible provider, with key presence (never the key). */\nexport interface CustomProviderInfo {\n id: string;\n name: string;\n url: string;\n hasApiKey: boolean;\n models: string[];\n}\n\n/** Redact a stored custom-provider row for the client (key presence only). */\nfunction toCustomProviderInfo(record: CustomProviderRecord): CustomProviderInfo {\n return {\n id: record.providerId,\n name: record.name,\n url: record.url,\n hasApiKey: Boolean(record.apiKey),\n models: record.models,\n };\n}\n\n/** The resolved custom-providers storage scope for a request. */\ninterface CustomProvidersContext {\n storage: CustomProvidersStorage;\n orgId: string;\n userId: string;\n}\n\n/**\n * Resolve the custom-providers context for a request, or a ready-to-return\n * error response. Same posture as memory settings: tenant rows in deployed\n * mode, a sentinel `local` org in no-auth mode — never settings.json.\n */\nasync function resolveCustomProvidersContext({\n c,\n auth,\n customProviders,\n}: {\n c: Context;\n auth: RouteAuth;\n customProviders?: CustomProvidersStorage;\n}): Promise<CustomProvidersContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant && auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (customProviders) {\n try {\n await customProviders.ensureReady();\n return tenant\n ? { storage: customProviders, orgId: tenantOrgId(tenant), userId: tenant.userId }\n : { storage: customProviders, orgId: 'local', userId: 'local' };\n } catch {\n // fall through to the unavailable response\n }\n }\n return {\n response: c.json(\n {\n error: 'custom_providers_unavailable',\n message: 'Custom provider storage is unavailable — the app database is not configured or failed to start.',\n },\n 503,\n ),\n };\n}\n\n/** Validate + coerce a request body into a CustomProviderSetting. */\nfunction parseCustomProviderBody(body: unknown): CustomProviderSetting | { error: string } {\n if (!body || typeof body !== 'object') return { error: 'Invalid JSON body' };\n const b = body as Record<string, unknown>;\n const name = typeof b.name === 'string' ? b.name.trim() : '';\n if (!name) return { error: 'Missing required field: name' };\n const url = typeof b.url === 'string' ? b.url.trim() : '';\n if (!url) return { error: 'Missing required field: url' };\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return { error: 'url must be an http(s) URL' };\n }\n } catch {\n return { error: 'url must be a valid URL' };\n }\n const apiKey = typeof b.apiKey === 'string' && b.apiKey.trim() ? b.apiKey.trim() : undefined;\n const models = Array.isArray(b.models)\n ? b.models.filter((m): m is string => typeof m === 'string' && m.trim().length > 0).map(m => m.trim())\n : [];\n return { name, url, apiKey, models };\n}\n\n// ── Model packs ──────────────────────────────────────────────────────────\n\n/** A model pack as surfaced to the web client, with an `active` flag. */\nexport interface ModelPackInfo extends ModePack {\n custom: boolean;\n active: boolean;\n}\n\n/**\n * Compute which providers the user can reach, mirroring the TUI's\n * `/models-pack` access derivation: OAuth/api-key from the credential store for\n * the named providers, plus any other provider that has a usable key.\n */\nexport async function buildProviderAccess({\n controller,\n authStorage,\n tenantCredentials,\n}: {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n tenantCredentials?: CredentialRecord[];\n}): Promise<ProviderAccess> {\n const models = await controller.listAvailableModels();\n const hasModelKey = (provider: string) => models.some(m => m.provider === provider && m.hasApiKey);\n const accessLevel = (provider: string): ProviderAccessLevel => {\n const authProviderId = getAuthProviderId(provider);\n if (tenantCredentials) {\n const userRec = tenantCredentials.find(r => r.scope === 'user' && r.provider === authProviderId);\n const orgRec = tenantCredentials.find(r => r.scope === 'org' && r.provider === authProviderId);\n const credential = userRec?.credential ?? orgRec?.credential;\n if (credential?.type === 'oauth') return 'oauth';\n if (credential?.type === 'api_key' && credential.key.trim().length > 0) return 'apikey';\n return false;\n }\n\n const oauthCredential = authStorage?.get(authProviderId);\n if (oauthCredential?.type === 'oauth') return 'oauth';\n if (authStorage?.hasStoredApiKey(provider)) return 'apikey';\n const directCredential = authStorage?.get(provider);\n if (directCredential?.type === 'api_key' && directCredential.key.trim().length > 0) return 'apikey';\n return hasModelKey(provider) ? 'apikey' : false;\n };\n const access: ProviderAccess = {\n anthropic: accessLevel('anthropic'),\n openai: accessLevel('openai'),\n cerebras: accessLevel('cerebras'),\n google: accessLevel('google'),\n deepseek: accessLevel('deepseek'),\n 'github-copilot': accessLevel('github-copilot'),\n };\n const seen = new Set(Object.keys(access));\n for (const m of models) {\n if (!seen.has(m.provider)) {\n access[m.provider] = accessLevel(m.provider);\n seen.add(m.provider);\n }\n }\n return access;\n}\n\nfunction canUseModelProvider(access: ProviderAccess, provider: string): boolean {\n return Boolean(access[provider]);\n}\n\n/**\n * Where a request's custom model packs live. Same posture as memory settings\n * and custom providers: the `model-packs` factory storage domain, scoped per\n * org in deployed mode and to a sentinel `local` org in no-auth mode — never\n * settings.json.\n */\nexport interface PackContext {\n storage: ModelPacksStorage;\n orgId: string;\n userId: string;\n}\n\n/** Resolve the pack context for a request, or a ready-to-return error response. */\nasync function resolvePackContext({\n c,\n auth,\n modelPacks,\n}: {\n c: Context;\n auth: RouteAuth;\n modelPacks?: ModelPacksStorage;\n}): Promise<PackContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant && auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (modelPacks) {\n try {\n await modelPacks.ensureReady();\n return tenant\n ? { storage: modelPacks, orgId: tenantOrgId(tenant), userId: tenant.userId }\n : { storage: modelPacks, orgId: 'local', userId: 'local' };\n } catch {\n // fall through to the unavailable response\n }\n }\n return {\n response: c.json(\n {\n error: 'model_packs_unavailable',\n message: 'Model pack storage is unavailable — the app database is not configured or failed to start.',\n },\n 503,\n ),\n };\n}\n\n/** DB row → the `ModePack` shape the packs list and activation flow consume. */\nfunction recordToModePack(record: ModelPackRecord): ModePack {\n return { id: `custom:${record.id}`, name: record.name, description: 'Saved custom pack', models: record.models };\n}\n\n/**\n * List available model packs (built-in, gated by provider access, plus saved\n * custom packs from the request's pack context). Drops the synthetic\n * \"New Custom\" placeholder — the web client has its own create flow. `active`\n * is set from the given session's thread when a resourceId is supplied.\n */\nexport async function listModelPacks({\n controller,\n authStorage,\n tenantCredentials,\n packContext,\n activePackId,\n}: {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n tenantCredentials?: CredentialRecord[];\n packContext: PackContext;\n activePackId?: string | null;\n}): Promise<ModelPackInfo[]> {\n const access = await buildProviderAccess({ controller, authStorage, tenantCredentials });\n const packs = [\n ...getAvailableModePacks(access),\n ...(await packContext.storage.list({ orgId: packContext.orgId })).map(recordToModePack),\n ];\n return packs\n .filter(p => p.id !== 'custom') // synthetic \"choose each model\" placeholder\n .map(p => ({\n ...p,\n custom: p.id.startsWith('custom:'),\n active: activePackId != null && p.id === activePackId,\n }));\n}\n\n/** Resolve the active pack id for a session by reading its current thread. */\nasync function resolveActivePackId(session: PackSession | undefined): Promise<string | null> {\n if (!session) return null;\n const threadId = session.thread.getId();\n if (!threadId) return null;\n const thread = (await session.thread.list()).find(t => t.id === threadId);\n const value = thread?.metadata?.[THREAD_ACTIVE_MODEL_PACK_ID_KEY];\n return typeof value === 'string' ? value : null;\n}\n\n/**\n * Apply a pack to a session: seed each mode's default model, switch the current\n * mode's model, set per-subagent models, and tag the thread with the active\n * pack id. Mirrors the TUI `applyPack` orchestration.\n */\nasync function applyPackToSession({\n controller,\n session,\n pack,\n}: {\n controller: ModelCatalog;\n session: PackSession;\n pack: ModePack;\n}): Promise<void> {\n const modes = controller.listModes?.() ?? [];\n const packModels = pack.models as Record<string, string>;\n\n for (const mode of modes) {\n const modelId = packModels[mode.id];\n if (modelId) {\n mode.defaultModelId = modelId;\n await session.thread.setSetting({ key: `modeModelId_${mode.id}`, value: modelId });\n }\n }\n\n const currentModeModel = packModels[session.mode.get()];\n if (currentModeModel) {\n await session.model.switch({ modelId: currentModeModel });\n }\n\n const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n for (const [agentType, modeId] of Object.entries(subagentModeMap)) {\n const saModelId = packModels[modeId];\n if (saModelId) {\n await session.subagents.model.set({ modelId: saModelId, agentType });\n }\n }\n\n await session.thread.setSetting({ key: THREAD_ACTIVE_MODEL_PACK_ID_KEY, value: pack.id });\n}\n\n// ── Observational memory ────────────────────────────────────────────────────\n// Mirrors the TUI `/om` command. Observer/reflector model + threshold reads come\n// from the session (state, falling back to omConfig defaults); writes go to both\n// the session (state + thread setting, via the same session methods the TUI uses)\n// and GlobalSettings (settings.json), so the choice survives restarts and stays\n// in sync with the terminal.\n\n/** Default thresholds mirror the TUI `/om` fallbacks. */\nconst DEFAULT_OBSERVATION_THRESHOLD = 30_000;\nconst DEFAULT_REFLECTION_THRESHOLD = 40_000;\n\n/** Read the current OM config from a session. */\nexport interface OMConfigInfo {\n observerModelId: string;\n reflectorModelId: string;\n observationThreshold: number;\n reflectionThreshold: number;\n observeAttachments: 'auto' | boolean;\n}\n\nexport function readOMConfig(session: OMSession): OMConfigInfo {\n const state = session.state.get() ?? {};\n const observeAttachments = state.observeAttachments;\n return {\n observerModelId: session.om.observer.modelId() ?? '',\n reflectorModelId: session.om.reflector.modelId() ?? '',\n observationThreshold: session.om.observer.threshold() ?? DEFAULT_OBSERVATION_THRESHOLD,\n reflectionThreshold: session.om.reflector.threshold() ?? DEFAULT_REFLECTION_THRESHOLD,\n observeAttachments: observeAttachments === true || observeAttachments === false ? observeAttachments : 'auto',\n };\n}\n\n/**\n * Where a request's OM settings live: the `memory-settings` factory storage\n * domain, one row per (org, user). Without a tenant (auth disabled), settings\n * land on a sentinel `(local, local)` row in the same table — the web surface\n * never reads or writes `settings.json` for memory settings.\n */\ninterface MemorySettingsContext {\n storage: MemorySettingsStorage;\n orgId: string;\n userId: string;\n}\n\n/** Resolve the memory-settings context for a request, or a ready-to-return error response. */\nasync function resolveMemorySettingsContext({\n c,\n auth,\n memorySettings,\n}: {\n c: Context;\n auth: RouteAuth;\n memorySettings?: MemorySettingsStorage;\n}): Promise<MemorySettingsContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant && auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (memorySettings) {\n try {\n await memorySettings.ensureReady();\n return tenant\n ? { storage: memorySettings, orgId: tenantOrgId(tenant), userId: tenant.userId }\n : { storage: memorySettings, orgId: 'local', userId: 'local' };\n } catch {\n // fall through to the unavailable response\n }\n }\n return {\n response: c.json(\n {\n error: 'memory_settings_unavailable',\n message: 'Memory settings storage is unavailable — the app database is not configured or failed to start.',\n },\n 503,\n ),\n };\n}\n\n/** Persist an OM knob change to the caller's memory-settings row. */\nasync function persistMemorySettings(\n context: MemorySettingsContext,\n patch: MemorySettingsPatch,\n fillIfUnset?: MemorySettingsFillIfUnset,\n): Promise<void> {\n await context.storage.patch({ orgId: context.orgId, userId: context.userId, patch, fillIfUnset });\n}\n\n/**\n * Apply the stored memory-settings row onto the session, so the DB — not\n * whatever happens to sit in persisted session state (e.g. a stale boot-time\n * seed from before memory settings moved to the DB) — is what the web surface\n * reads and what the session's OM actually runs with. The row is authoritative:\n * knobs without a stored value reset to the built-in defaults.\n */\nasync function hydrateSessionMemorySettings(session: OMSession, record: MemorySettingsRecord | null): Promise<void> {\n for (const role of ['observer', 'reflector'] as const) {\n const stored = role === 'observer' ? record?.observerModelId : record?.reflectorModelId;\n const target = stored ?? DEFAULT_OM_MODEL_ID;\n if (session.om[role].modelId() !== target) {\n await session.om[role].switchModel({ modelId: target });\n }\n }\n const state = session.state.get() ?? {};\n const updates: OMStateWrites = {};\n const observationThreshold = record?.observationThreshold ?? DEFAULT_OBSERVATION_THRESHOLD;\n if (state.observationThreshold !== observationThreshold) {\n updates.observationThreshold = observationThreshold;\n }\n const reflectionThreshold = record?.reflectionThreshold ?? DEFAULT_REFLECTION_THRESHOLD;\n if (state.reflectionThreshold !== reflectionThreshold) {\n updates.reflectionThreshold = reflectionThreshold;\n }\n const observeAttachments = record?.observeAttachments ?? 'auto';\n if ((state.observeAttachments ?? 'auto') !== observeAttachments) {\n updates.observeAttachments = observeAttachments;\n }\n if (Object.keys(updates).length > 0) await session.state.set(updates);\n}\n\n/** Dependencies injected into {@link ConfigRoutes}. */\nexport interface ConfigRoutesDeps extends RouteDependencies {\n controller: ModelCatalog;\n authStorage?: AuthStorage;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n modelCredentials?: ModelCredentialsStorage;\n /** Tenant model-packs domain handle; absent in local (no-DB) mode. */\n modelPacks?: ModelPacksStorage;\n /** Tenant memory-settings domain handle; absent in local (no-DB) mode. */\n memorySettings?: MemorySettingsStorage;\n /** Custom-providers domain handle; absent when the app database is missing. */\n customProviders?: CustomProvidersStorage;\n /** Notifies the host after tenant credentials change so caches can be dropped. */\n onCredentialsChanged?: (tenant: { orgId: string; userId?: string }) => void;\n /** Notifies the host after custom providers change so model-router caches can be dropped. */\n onCustomProvidersChanged?: (tenant: { orgId: string }) => void;\n}\n\n/**\n * The web config routes as Mastra `apiRoutes`:\n * - `GET /web/config/providers` — list providers + key source\n * - `PUT /web/config/providers/:provider/key` — set/update a provider's API key\n * - `DELETE /web/config/providers/:provider/key` — remove a stored API key\n * - `GET /web/config/models` — list available models (credentialed providers)\n * - `GET /web/config/custom-providers` — list custom OpenAI-compatible providers\n * - `POST /web/config/custom-providers` — create/update a custom provider\n * - `DELETE /web/config/custom-providers/:id` — remove a custom provider\n * - `GET /web/config/om` — read OM models/thresholds/observe-attachments\n * - `PUT /web/config/om/:role/model` — switch observer/reflector model\n * - `PUT /web/config/om/thresholds` — set observation/reflection thresholds\n * - `PUT /web/config/om/observe-attachments` — set observe-attachments (auto/on/off)\n */\nexport class ConfigRoutes extends Route<ConfigRoutesDeps> {\n routes(): ApiRoute[] {\n const options = this.deps;\n const { controller, authStorage, auth } = options;\n const onCredentialsChanged = options.onCredentialsChanged ?? (() => {});\n const onCustomProvidersChanged = options.onCustomProvidersChanged ?? (() => {});\n\n return [\n registerApiRoute('/web/config/providers', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n try {\n // Tenant mode lists the caller's rows and never exposes the\n // server-global auth.json; local mode is unchanged.\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n return c.json({\n providers: await listProviders({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n }),\n });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/key', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: options.modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n let body: { key?: unknown; envVar?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const key = typeof body.key === 'string' ? body.key.trim() : '';\n if (!key) return c.json({ error: 'Missing required field: key' }, 400);\n const envVar = typeof body.envVar === 'string' ? body.envVar : undefined;\n const scope = body.scope === 'org' ? 'org' : 'user';\n try {\n if (ctx.mode === 'tenant') {\n if (scope === 'org' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'organization_admin_required' }, 403);\n }\n const tenant = scope === 'org' ? { orgId: ctx.orgId } : { orgId: ctx.orgId, userId: ctx.userId };\n // envVar is intentionally ignored: tenant credentials are resolved\n // per-request, never written into process.env.\n await ctx.storage.setCredential(tenant, getAuthProviderId(provider), { type: 'api_key', key });\n onCredentialsChanged(tenant);\n const records = await ctx.storage.listCredentials(ctx.orgId, ctx.userId);\n const providers = await listProviders({ controller, tenantCredentials: records });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n }\n if (!authStorage) return c.json({ error: 'Credential storage is not available' }, 503);\n // Local mode is single-user: scope is meaningless and ignored.\n authStorage.setStoredApiKey(provider, key, envVar);\n const providers = await listProviders({ controller, authStorage });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/key', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: options.modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const scope = c.req.query('scope') === 'org' ? 'org' : 'user';\n try {\n if (ctx.mode === 'tenant') {\n if (scope === 'org' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'organization_admin_required' }, 403);\n }\n const tenant = scope === 'org' ? { orgId: ctx.orgId } : { orgId: ctx.orgId, userId: ctx.userId };\n await ctx.storage.removeCredential(tenant, getAuthProviderId(provider));\n onCredentialsChanged(tenant);\n const records = await ctx.storage.listCredentials(ctx.orgId, ctx.userId);\n const providers = await listProviders({ controller, tenantCredentials: records });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n }\n if (!authStorage) return c.json({ error: 'Credential storage is not available' }, 503);\n authStorage.remove(`apikey:${provider}`);\n const providers = await listProviders({ controller, authStorage });\n return c.json({ ok: true, provider: providers.find(p => p.provider === provider) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Custom providers (OpenAI-compatible endpoints) ──────────────────────\n // Mirrors the TUI's /custom-providers command, but backed by the\n // `custom-providers` domain (org rows in tenant mode, a sentinel `local`\n // org in no-auth mode) — the server never reads settings.json for these.\n\n registerApiRoute('/web/config/custom-providers', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCustomProvidersContext({\n c: loose(c),\n auth,\n customProviders: options.customProviders,\n });\n if ('response' in ctx) return ctx.response;\n try {\n const records = await ctx.storage.list({ orgId: ctx.orgId });\n return c.json({ providers: records.map(toCustomProviderInfo) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/custom-providers', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCustomProvidersContext({\n c: loose(c),\n auth,\n customProviders: options.customProviders,\n });\n if ('response' in ctx) return ctx.response;\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const parsed = parseCustomProviderBody(body);\n if ('error' in parsed) return c.json({ error: parsed.error }, 400);\n // `previousId` lets a rename remove the old entry as well as any name clash.\n const previousId =\n body && typeof body === 'object' && typeof (body as Record<string, unknown>).previousId === 'string'\n ? ((body as Record<string, unknown>).previousId as string)\n : undefined;\n try {\n const record = await ctx.storage.upsert({\n orgId: ctx.orgId,\n userId: ctx.userId,\n input: {\n providerId: getCustomProviderId(parsed.name),\n name: parsed.name,\n url: parsed.url,\n apiKey: parsed.apiKey,\n models: parsed.models,\n },\n previousProviderId: previousId,\n });\n onCustomProvidersChanged({ orgId: ctx.orgId });\n return c.json({ ok: true, provider: toCustomProviderInfo(record) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/custom-providers/:id', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCustomProvidersContext({\n c: loose(c),\n auth,\n customProviders: options.customProviders,\n });\n if ('response' in ctx) return ctx.response;\n const id = c.req.param('id');\n try {\n await ctx.storage.delete({ orgId: ctx.orgId, providerId: id });\n onCustomProvidersChanged({ orgId: ctx.orgId });\n return c.json({ ok: true });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Available models ────────────────────────────────────────────────────\n // Session-independent model catalog for settings pickers (Factory default\n // model, pack editors). Only models whose provider has a credential are\n // returned — the same filter the session-scoped hook applies client-side.\n\n registerApiRoute('/web/config/models', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n try {\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n const [models, access] = await Promise.all([\n controller.listAvailableModels(),\n buildProviderAccess({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n }),\n ]);\n const catalog = models\n .filter(m => canUseModelProvider(access, m.provider) && typeof m.id === 'string')\n .map(m => ({ id: m.id!, provider: m.provider, modelName: m.modelName, hasApiKey: true }));\n // Append the caller's custom provider models (DB-backed, org rows in\n // tenant mode / sentinel `local` org in no-auth mode). The boot-time\n // gateway catalog only carries the local list, so tenant callers get\n // theirs here. Dedupe against ids already present.\n if (options.customProviders) {\n try {\n const ctx = await resolveCustomProvidersContext({\n c: loose(c),\n auth,\n customProviders: options.customProviders,\n });\n if (!('response' in ctx)) {\n const known = new Set(catalog.map(m => m.id));\n for (const record of await ctx.storage.list({ orgId: ctx.orgId })) {\n for (const model of record.models) {\n const id = `${record.providerId}/${model}`;\n if (known.has(id)) continue;\n known.add(id);\n catalog.push({ id, provider: record.providerId, modelName: model, hasApiKey: true });\n }\n }\n }\n } catch {\n // Fail soft: the catalog still serves the built-in models.\n }\n }\n return c.json({\n models: catalog.sort((a, b) =>\n a.provider === b.provider ? a.id.localeCompare(b.id) : a.provider.localeCompare(b.provider),\n ),\n });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Model packs ─────────────────────────────────────────────────────────\n // Mirrors the TUI's /models-pack command. Custom-pack CRUD lives in the\n // model-packs storage domain (org-scoped, sentinel `local` org in no-auth\n // mode — never settings.json); activation is session-scoped and resolves\n // the session from the controller registry by resourceId.\n\n registerApiRoute('/web/config/model-packs', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n const resourceId = c.req.query('resourceId');\n const scope = c.req.query('scope') || undefined;\n try {\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n const activePackId = await resolveActivePackId(session);\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n return c.json({\n packs: await listModelPacks({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n packContext,\n activePackId,\n }),\n activePackId,\n });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/model-packs', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n let body: { name?: unknown; models?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const name = typeof body.name === 'string' ? body.name.trim() : '';\n if (!name) return c.json({ error: 'Missing required field: name' }, 400);\n const m = (body.models ?? {}) as Record<string, unknown>;\n const build = typeof m.build === 'string' ? m.build.trim() : '';\n const plan = typeof m.plan === 'string' ? m.plan.trim() : '';\n const fast = typeof m.fast === 'string' ? m.fast.trim() : '';\n if (!build || !plan || !fast) {\n return c.json({ error: 'models.build, models.plan and models.fast are required' }, 400);\n }\n try {\n const record = await packContext.storage.upsert({\n orgId: packContext.orgId,\n userId: packContext.userId,\n input: { name, models: { build, plan, fast } },\n });\n return c.json({ ok: true, pack: recordToModePack(record) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/model-packs/:id', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n const id = decodeURIComponent(c.req.param('id'));\n try {\n const recordId = id.startsWith('custom:') ? id.slice('custom:'.length) : id;\n const deleted = await packContext.storage.delete({ orgId: packContext.orgId, id: recordId });\n return deleted ? c.json({ ok: true }) : c.json({ error: `Unknown pack \"${id}\"` }, 404);\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/model-packs/:id/activate', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const packContext = await resolvePackContext({ c: loose(c), auth, modelPacks: options.modelPacks });\n if ('response' in packContext) return packContext.response;\n const id = decodeURIComponent(c.req.param('id'));\n let body: { resourceId?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n const packs = await listModelPacks({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n packContext,\n });\n const pack = packs.find(p => p.id === id);\n if (!pack) return c.json({ error: `Unknown pack \"${id}\"` }, 404);\n await applyPackToSession({ controller, session, pack });\n return c.json({ ok: true, activePackId: pack.id });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n // ── Observational memory ──────────────────────────────────────────────────\n // Mirrors the TUI's /om command. All five knobs are session-scoped (resolved\n // from the session, persisted to its state + thread setting) and durably\n // stored in the per-(org, user) `memory-settings` app table — never\n // settings.json. GET hydrates the session from the stored row first so the\n // DB, not the SDK's boot-time seed, is the source of truth.\n\n registerApiRoute('/web/config/om', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resourceId = c.req.query('resourceId');\n const scope = c.req.query('scope') || undefined;\n if (!resourceId) return c.json({ error: 'Missing required query param: resourceId' }, 400);\n const context = await resolveMemorySettingsContext({\n c: loose(c),\n auth,\n memorySettings: options.memorySettings,\n });\n if ('response' in context) return context.response;\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n const record = await context.storage.get({ orgId: context.orgId, userId: context.userId });\n await hydrateSessionMemorySettings(session, record);\n return c.json({ config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/om/:role/model', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const role = c.req.param('role');\n if (role !== 'observer' && role !== 'reflector') {\n return c.json({ error: `Unknown OM role \"${role}\"` }, 400);\n }\n let body: { resourceId?: unknown; modelId?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n const modelId = typeof body.modelId === 'string' ? body.modelId.trim() : '';\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n if (!modelId) return c.json({ error: 'Missing required field: modelId' }, 400);\n const context = await resolveMemorySettingsContext({\n c: loose(c),\n auth,\n memorySettings: options.memorySettings,\n });\n if ('response' in context) return context.response;\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n const otherRole = role === 'observer' ? session.om.reflector : session.om.observer;\n const otherRoleCurrentModelId = otherRole.modelId() ?? null;\n await session.om[role].switchModel({ modelId });\n // Pin the other role's current model too, so a later restart\n // doesn't drift it once this role is explicitly overridden. The\n // \"only if still unset\" check runs inside the storage layer's\n // atomic update, so a concurrent explicit switch of the other\n // role is never clobbered by this fill.\n const otherKey = role === 'observer' ? 'reflectorModelId' : 'observerModelId';\n await persistMemorySettings(\n context,\n { [role === 'observer' ? 'observerModelId' : 'reflectorModelId']: modelId },\n otherRoleCurrentModelId ? { [otherKey]: otherRoleCurrentModelId } : undefined,\n );\n return c.json({ ok: true, config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/om/thresholds', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n let body: {\n resourceId?: unknown;\n observationThreshold?: unknown;\n reflectionThreshold?: unknown;\n scope?: unknown;\n };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n const observation =\n typeof body.observationThreshold === 'number' && body.observationThreshold > 0\n ? Math.round(body.observationThreshold)\n : undefined;\n const reflection =\n typeof body.reflectionThreshold === 'number' && body.reflectionThreshold > 0\n ? Math.round(body.reflectionThreshold)\n : undefined;\n if (observation === undefined && reflection === undefined) {\n return c.json({ error: 'Provide observationThreshold and/or reflectionThreshold (positive numbers)' }, 400);\n }\n const context = await resolveMemorySettingsContext({\n c: loose(c),\n auth,\n memorySettings: options.memorySettings,\n });\n if ('response' in context) return context.response;\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n if (observation !== undefined) {\n await session.state.set({ observationThreshold: observation });\n await session.thread.setSetting({ key: 'observationThreshold', value: observation });\n }\n if (reflection !== undefined) {\n await session.state.set({ reflectionThreshold: reflection });\n await session.thread.setSetting({ key: 'reflectionThreshold', value: reflection });\n }\n await persistMemorySettings(context, {\n ...(observation !== undefined ? { observationThreshold: observation } : {}),\n ...(reflection !== undefined ? { reflectionThreshold: reflection } : {}),\n });\n return c.json({ ok: true, config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n\n registerApiRoute('/web/config/om/observe-attachments', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n let body: { resourceId?: unknown; value?: unknown; scope?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const resourceId = typeof body.resourceId === 'string' ? body.resourceId : '';\n const scope = typeof body.scope === 'string' && body.scope ? body.scope : undefined;\n if (!resourceId) return c.json({ error: 'Missing required field: resourceId' }, 400);\n const raw = body.value;\n const value: 'auto' | boolean = raw === 'auto' || raw === true || raw === false ? raw : 'auto';\n if (raw !== 'auto' && raw !== true && raw !== false) {\n return c.json({ error: \"value must be 'auto', true, or false\" }, 400);\n }\n const context = await resolveMemorySettingsContext({\n c: loose(c),\n auth,\n memorySettings: options.memorySettings,\n });\n if ('response' in context) return context.response;\n try {\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ error: `No session for resourceId \"${resourceId}\"` }, 404);\n await session.state.set({ observeAttachments: value });\n await session.thread.setSetting({ key: 'observeAttachments', value });\n await persistMemorySettings(context, { observeAttachments: value });\n return c.json({ ok: true, config: readOMConfig(session) });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n ];\n }\n}\n","/**\n * Per-request model-provider credential context.\n *\n * The provider config/OAuth routes serve two deployment shapes:\n *\n * - **Local** (no web auth adapter): credentials live in the server-global\n * file-backed `AuthStorage` (`auth.json`) — unchanged TUI behavior.\n * - **Tenant** (auth adapter active): credentials live in the\n * `model-credentials` factory storage domain, scoped per `(orgId, userId)`\n * with optional org-wide rows (`userId` absent).\n *\n * `resolveCredentialContext` decides which shape a request is in: an\n * authenticated user always gets the tenant path; an unauthenticated request\n * is rejected when auth is enabled and falls back to local otherwise.\n */\n\nimport type { Context } from 'hono';\n\nimport type {\n CredentialRecord,\n LoginSessionKind,\n ModelCredentialsStorage,\n} from '../storage/domains/credentials/base.js';\nimport type { RouteAuth } from './route.js';\n\n/**\n * OAuth credentials are stored under the auth provider id, which differs from\n * the catalog provider id for OpenAI (stored as `openai-codex`). Tenant rows\n * use the same keying so one lookup serves both OAuth tokens and API keys.\n */\nexport function getAuthProviderId(provider: string): string {\n return provider === 'openai' ? 'openai-codex' : provider;\n}\n\n/**\n * Providers that support a browser-driven OAuth sign-in flow, keyed by\n * *catalog* provider id (what the routes and settings UI use). All flows need\n * no inbound connection to the server: Anthropic uses paste-code PKCE, the\n * rest use RFC 8628-style device codes.\n */\nexport const WEB_OAUTH_FLOW_KINDS: Readonly<Record<string, LoginSessionKind>> = {\n anthropic: 'paste-code',\n openai: 'device-code',\n 'github-copilot': 'device-code',\n xai: 'device-code',\n};\n\nexport type CredentialContext =\n { mode: 'local' } | { mode: 'tenant'; storage: ModelCredentialsStorage; orgId: string; userId: string };\n\n/**\n * The tenant credentials domain, when registered and ready. `undefined` means\n * the factory never ran (no handle threaded in) or the domain's init failed\n * (fail-soft — callers report the feature unavailable instead of crashing).\n */\nexport async function getTenantCredentialsStorage(\n credentials: ModelCredentialsStorage | undefined,\n): Promise<ModelCredentialsStorage | undefined> {\n if (!credentials) return undefined;\n try {\n await credentials.ensureReady();\n } catch {\n return undefined;\n }\n return credentials;\n}\n\n/**\n * Org key for tenant rows. Personal accounts get an org bootstrapped by the\n * auth adapter (`ensureOrg`); if one still isn't present, scope rows under a\n * per-user synthetic org so credentials never become server-global.\n */\nexport function tenantOrgId(tenant: { orgId?: string; userId: string }): string {\n return tenant.orgId ?? `user:${tenant.userId}`;\n}\n\n/**\n * Resolve the credential context for a request, or a ready-to-return error\n * response. Mutating credential routes call this and hard-fail (401/503)\n * when the tenant path is required but unavailable.\n */\nexport async function resolveCredentialContext({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) {\n // When an auth provider is active, credential operations always require a\n // signed-in caller — otherwise one anonymous request could write keys for\n // everyone. Without a provider this is a single-user local server.\n if (auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n return { mode: 'local' };\n }\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) {\n return {\n response: c.json(\n {\n error: 'credentials_unavailable',\n message: 'Tenant credential storage is unavailable — the app database is not configured or failed to start.',\n },\n 503,\n ),\n };\n }\n return { mode: 'tenant', storage, orgId: tenantOrgId(tenant), userId: tenant.userId };\n}\n\n/**\n * List the caller's tenant credential records for provider listing, or\n * `undefined` in local mode (caller should fall back to `AuthStorage`).\n * Read-only and degradation-friendly: an authenticated caller with the domain\n * unavailable gets an empty list (sources show `env`/`none`) instead of a 503\n * so the settings page still renders.\n */\nexport async function listTenantCredentialsForRequest({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialRecord[] | undefined> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return auth.enabled() ? [] : undefined;\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) return [];\n return storage.listCredentials(tenantOrgId(tenant), tenant.userId);\n}\n","/**\n * Base class for factory route modules.\n *\n * Route modules build Mastra `apiRoutes` from injected dependencies instead of\n * reaching into host globals. The host server (e.g. `mastracode/web`) supplies\n * the auth seam and storage domain handles at construction time, so the routes\n * stay portable and testable with fakes.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\n/**\n * The auth surface factory routes need, implemented by the host server.\n *\n * Local (no-auth) deployments implement this with a stub where `enabled()`\n * returns `false` and `tenant()` returns `undefined` — routes then take their\n * single-user local paths.\n */\nexport interface RouteAuth {\n /** Whether an auth provider is active (tenant mode). */\n enabled(): boolean;\n /**\n * Resolve (and cache) the signed-in user for the request, if any. Must be\n * called before `tenant()` so the request context is populated.\n */\n ensureUser(c: Context): Promise<unknown>;\n /** Tenant identity for the request, when signed in. */\n tenant(c: Context): { orgId?: string; userId: string } | undefined;\n /** Fail-closed check that the caller administers the given organization. */\n isOrganizationAdmin(c: Context, organizationId: string): Promise<boolean>;\n}\n\n/** Dependencies shared by every factory route module. */\nexport interface RouteDependencies {\n auth: RouteAuth;\n}\n\n/**\n * A route module: constructed once at boot with its dependencies, then asked\n * for the `ApiRoute[]` it serves.\n */\nexport abstract class Route<TDeps extends RouteDependencies = RouteDependencies> {\n protected readonly deps: TDeps;\n\n constructor(deps: TDeps) {\n this.deps = deps;\n }\n\n /** Build the Mastra `apiRoutes` served by this module. */\n abstract routes(): ApiRoute[];\n}\n"],"mappings":";AACA,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AAEtC,SAAS,qBAAqB,uCAAuC;AAGrE,SAAS,wBAAwB;;;ACuB1B,SAAS,kBAAkB,UAA0B;AAC1D,SAAO,aAAa,WAAW,iBAAiB;AAClD;AAQO,IAAM,uBAAmE;AAAA,EAC9E,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,KAAK;AACP;AAUA,eAAsB,4BACpB,aAC8C;AAC9C,MAAI,CAAC,YAAa,QAAO;AACzB,MAAI;AACF,UAAM,YAAY,YAAY;AAAA,EAChC,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,SAAS,YAAY,QAAoD;AAC9E,SAAO,OAAO,SAAS,QAAQ,OAAO,MAAM;AAC9C;AAOA,eAAsB,yBAAyB;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AACF,GAKwD;AACtD,QAAM,KAAK,WAAW,CAAC;AACvB,QAAM,SAAS,KAAK,OAAO,CAAC;AAC5B,MAAI,CAAC,QAAQ;AAIX,QAAI,KAAK,QAAQ,EAAG,QAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;AAC9E,WAAO,EAAE,MAAM,QAAQ;AAAA,EACzB;AACA,QAAM,UAAU,MAAM,4BAA4B,WAAW;AAC7D,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,MACL,UAAU,EAAE;AAAA,QACV;AAAA,UACE,OAAO;AAAA,UACP,SAAS;AAAA,QACX;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,MAAM,UAAU,SAAS,OAAO,YAAY,MAAM,GAAG,QAAQ,OAAO,OAAO;AACtF;AASA,eAAsB,gCAAgC;AAAA,EACpD;AAAA,EACA;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,KAAK,EAAE,IAAI,MAAM,QAAQ,aAAa,OAAO,EAAE,CAAC;AAAA,UAC3D,SAAS,OAAO;AACd,mBAAO,EAAE,KAAK,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG,GAAG;AAAA,UACtF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["providers"]}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * DB-backed custom providers source for model resolution (factory mode).
3
+ *
4
+ * The SDK's `resolveModel` and gateway catalog ask the registered
5
+ * `CustomProvidersSource` synchronously, so this module keeps a small per-org
6
+ * **snapshot** of custom provider rows hydrated from the `custom-providers`
7
+ * domain. Once registered the source is authoritative — the factory never
8
+ * reads `settings.json` custom providers, in either auth mode:
9
+ *
10
+ * - tenant mode: rows are scoped per org (`tenantOrgId`); calls without an
11
+ * authenticated tenant (boot-time catalog) resolve to an empty list.
12
+ * - no-auth/local mode: rows live under the sentinel `local` org, matching the
13
+ * custom provider routes.
14
+ *
15
+ * Snapshots are primed per request by `createCustomProvidersPrimer` (mounted
16
+ * after the web auth gate) and invalidated on writes via
17
+ * `invalidateCustomProvidersSnapshots` so changes are visible immediately.
18
+ */
19
+ import type { MiddlewareHandler } from 'hono';
20
+ import type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';
21
+ import type { RouteAuth } from './route.js';
22
+ /**
23
+ * Register the DB-backed custom providers source with the SDK. Called by the
24
+ * factory after storage init with the `custom-providers` domain handle; from
25
+ * then on model resolution and the gateway catalog never read settings.json
26
+ * custom providers.
27
+ */
28
+ export declare function registerCustomProvidersSource({ storage, authEnabled, }: {
29
+ storage: CustomProvidersStorage;
30
+ authEnabled: boolean;
31
+ }): void;
32
+ /**
33
+ * Drop the org's cached snapshot after a custom provider write so the change
34
+ * is visible to the next model call immediately instead of after the TTL.
35
+ */
36
+ export declare function invalidateCustomProvidersSnapshots(tenant: {
37
+ orgId: string;
38
+ }): void;
39
+ /** Test hook: clear registration and cached org snapshots. */
40
+ export declare function resetCustomProvidersSourceForTests(): void;
41
+ /**
42
+ * Middleware mounted after the web auth gate: primes the caller's org snapshot
43
+ * so the request's first model call sees their custom providers without an
44
+ * async seam in model resolution. Cheap when fresh (TTL check), best-effort
45
+ * when not — a failed hydrate serves the last snapshot, never blocks a request.
46
+ */
47
+ export declare function createCustomProvidersPrimer({ auth, storage, authEnabled, }: {
48
+ auth: RouteAuth;
49
+ storage: CustomProvidersStorage;
50
+ authEnabled: boolean;
51
+ }): MiddlewareHandler;
52
+ //# sourceMappingURL=custom-provider-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"custom-provider-source.d.ts","sourceRoot":"","sources":["../../src/routes/custom-provider-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AAE1F,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AA6E5C;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,EAC5C,OAAO,EACP,WAAW,GACZ,EAAE;IACD,OAAO,EAAE,sBAAsB,CAAC;IAChC,WAAW,EAAE,OAAO,CAAC;CACtB,GAAG,IAAI,CAMP;AAED;;;GAGG;AACH,wBAAgB,kCAAkC,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAElF;AAED,8DAA8D;AAC9D,wBAAgB,kCAAkC,IAAI,IAAI,CAGzD;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,EAC1C,IAAI,EACJ,OAAO,EACP,WAAW,GACZ,EAAE;IACD,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,sBAAsB,CAAC;IAChC,WAAW,EAAE,OAAO,CAAC;CACtB,GAAG,iBAAiB,CAYpB"}
@@ -0,0 +1,107 @@
1
+ // src/routes/custom-provider-source.ts
2
+ import { setCustomProvidersSource } from "@mastra/code-sdk/agents/custom-provider-source";
3
+
4
+ // src/routes/provider-credentials.ts
5
+ function tenantOrgId(tenant) {
6
+ return tenant.orgId ?? `user:${tenant.userId}`;
7
+ }
8
+
9
+ // src/routes/custom-provider-source.ts
10
+ var SNAPSHOT_TTL_MS = 15e3;
11
+ var MAX_CACHED_ORGS = 1e3;
12
+ var LOCAL_ORG = "local";
13
+ var OrgCustomProvidersSnapshot = class {
14
+ #orgId;
15
+ #storage;
16
+ #snapshot = [];
17
+ #fetchedAt = 0;
18
+ #hydrating;
19
+ constructor(orgId, storage) {
20
+ this.#orgId = orgId;
21
+ this.#storage = storage;
22
+ }
23
+ /** Hydrate the snapshot when stale; coalesces concurrent callers. */
24
+ async ensureFresh(now = Date.now()) {
25
+ if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;
26
+ this.#hydrating ??= this.#hydrate().finally(() => {
27
+ this.#hydrating = void 0;
28
+ });
29
+ await this.#hydrating;
30
+ }
31
+ async #hydrate() {
32
+ await this.#storage.ensureReady();
33
+ const records = await this.#storage.list({ orgId: this.#orgId });
34
+ this.#snapshot = records.map((record) => ({
35
+ name: record.name,
36
+ url: record.url,
37
+ apiKey: record.apiKey ?? void 0,
38
+ models: record.models
39
+ }));
40
+ this.#fetchedAt = Date.now();
41
+ }
42
+ /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */
43
+ get() {
44
+ if (Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS) {
45
+ void this.ensureFresh().catch(() => {
46
+ });
47
+ }
48
+ return this.#snapshot;
49
+ }
50
+ };
51
+ var orgSnapshots = /* @__PURE__ */ new Map();
52
+ function snapshotFor(orgId, storage) {
53
+ let snapshot = orgSnapshots.get(orgId);
54
+ if (!snapshot) {
55
+ if (orgSnapshots.size >= MAX_CACHED_ORGS) {
56
+ const oldest = orgSnapshots.keys().next().value;
57
+ if (oldest !== void 0) orgSnapshots.delete(oldest);
58
+ }
59
+ snapshot = new OrgCustomProvidersSnapshot(orgId, storage);
60
+ orgSnapshots.set(orgId, snapshot);
61
+ }
62
+ return snapshot;
63
+ }
64
+ function orgForTenant(tenant, authEnabled) {
65
+ if (!authEnabled) return LOCAL_ORG;
66
+ return tenant ? tenantOrgId(tenant) : void 0;
67
+ }
68
+ function registerCustomProvidersSource({
69
+ storage,
70
+ authEnabled
71
+ }) {
72
+ setCustomProvidersSource((tenant) => {
73
+ const orgId = orgForTenant(tenant, authEnabled);
74
+ if (!orgId) return [];
75
+ return snapshotFor(orgId, storage).get();
76
+ });
77
+ }
78
+ function invalidateCustomProvidersSnapshots(tenant) {
79
+ orgSnapshots.delete(tenant.orgId);
80
+ }
81
+ function resetCustomProvidersSourceForTests() {
82
+ setCustomProvidersSource(void 0);
83
+ orgSnapshots.clear();
84
+ }
85
+ function createCustomProvidersPrimer({
86
+ auth,
87
+ storage,
88
+ authEnabled
89
+ }) {
90
+ return async (c, next) => {
91
+ const orgId = orgForTenant(auth.tenant(c), authEnabled);
92
+ if (orgId) {
93
+ try {
94
+ await snapshotFor(orgId, storage).ensureFresh();
95
+ } catch {
96
+ }
97
+ }
98
+ await next();
99
+ };
100
+ }
101
+ export {
102
+ createCustomProvidersPrimer,
103
+ invalidateCustomProvidersSnapshots,
104
+ registerCustomProvidersSource,
105
+ resetCustomProvidersSourceForTests
106
+ };
107
+ //# sourceMappingURL=custom-provider-source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/routes/custom-provider-source.ts","../../src/routes/provider-credentials.ts"],"sourcesContent":["/**\n * DB-backed custom providers source for model resolution (factory mode).\n *\n * The SDK's `resolveModel` and gateway catalog ask the registered\n * `CustomProvidersSource` synchronously, so this module keeps a small per-org\n * **snapshot** of custom provider rows hydrated from the `custom-providers`\n * domain. Once registered the source is authoritative — the factory never\n * reads `settings.json` custom providers, in either auth mode:\n *\n * - tenant mode: rows are scoped per org (`tenantOrgId`); calls without an\n * authenticated tenant (boot-time catalog) resolve to an empty list.\n * - no-auth/local mode: rows live under the sentinel `local` org, matching the\n * custom provider routes.\n *\n * Snapshots are primed per request by `createCustomProvidersPrimer` (mounted\n * after the web auth gate) and invalidated on writes via\n * `invalidateCustomProvidersSnapshots` so changes are visible immediately.\n */\n\nimport { setCustomProvidersSource } from '@mastra/code-sdk/agents/custom-provider-source';\nimport type { MastraCodeCustomProvider } from '@mastra/code-sdk/agents/mastracode-gateway';\nimport type { MiddlewareHandler } from 'hono';\n\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport { tenantOrgId } from './provider-credentials.js';\nimport type { RouteAuth } from './route.js';\n\n/** How long a hydrated snapshot is considered fresh. */\nconst SNAPSHOT_TTL_MS = 15_000;\n\n/** Cap on cached org snapshots; oldest-inserted evicted beyond this. */\nconst MAX_CACHED_ORGS = 1000;\n\n/** Sentinel org for no-auth mode — must match the custom provider routes. */\nconst LOCAL_ORG = 'local';\n\nclass OrgCustomProvidersSnapshot {\n readonly #orgId: string;\n readonly #storage: CustomProvidersStorage;\n #snapshot: MastraCodeCustomProvider[] = [];\n #fetchedAt = 0;\n #hydrating: Promise<void> | undefined;\n\n constructor(orgId: string, storage: CustomProvidersStorage) {\n this.#orgId = orgId;\n this.#storage = storage;\n }\n\n /** Hydrate the snapshot when stale; coalesces concurrent callers. */\n async ensureFresh(now = Date.now()): Promise<void> {\n if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;\n this.#hydrating ??= this.#hydrate().finally(() => {\n this.#hydrating = undefined;\n });\n await this.#hydrating;\n }\n\n async #hydrate(): Promise<void> {\n await this.#storage.ensureReady();\n const records = await this.#storage.list({ orgId: this.#orgId });\n this.#snapshot = records.map(record => ({\n name: record.name,\n url: record.url,\n apiKey: record.apiKey ?? undefined,\n models: record.models,\n }));\n this.#fetchedAt = Date.now();\n }\n\n /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */\n get(): MastraCodeCustomProvider[] {\n if (Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS) {\n void this.ensureFresh().catch(() => {});\n }\n return this.#snapshot;\n }\n}\n\nconst orgSnapshots = new Map<string, OrgCustomProvidersSnapshot>();\n\nfunction snapshotFor(orgId: string, storage: CustomProvidersStorage): OrgCustomProvidersSnapshot {\n let snapshot = orgSnapshots.get(orgId);\n if (!snapshot) {\n if (orgSnapshots.size >= MAX_CACHED_ORGS) {\n const oldest = orgSnapshots.keys().next().value;\n if (oldest !== undefined) orgSnapshots.delete(oldest);\n }\n snapshot = new OrgCustomProvidersSnapshot(orgId, storage);\n orgSnapshots.set(orgId, snapshot);\n }\n return snapshot;\n}\n\n/** The org a call resolves to, or `undefined` to fail closed (tenant mode without identity). */\nfunction orgForTenant(\n tenant: { orgId?: string; userId: string } | undefined,\n authEnabled: boolean,\n): string | undefined {\n if (!authEnabled) return LOCAL_ORG;\n return tenant ? tenantOrgId(tenant) : undefined;\n}\n\n/**\n * Register the DB-backed custom providers source with the SDK. Called by the\n * factory after storage init with the `custom-providers` domain handle; from\n * then on model resolution and the gateway catalog never read settings.json\n * custom providers.\n */\nexport function registerCustomProvidersSource({\n storage,\n authEnabled,\n}: {\n storage: CustomProvidersStorage;\n authEnabled: boolean;\n}): void {\n setCustomProvidersSource(tenant => {\n const orgId = orgForTenant(tenant, authEnabled);\n if (!orgId) return [];\n return snapshotFor(orgId, storage).get();\n });\n}\n\n/**\n * Drop the org's cached snapshot after a custom provider write so the change\n * is visible to the next model call immediately instead of after the TTL.\n */\nexport function invalidateCustomProvidersSnapshots(tenant: { orgId: string }): void {\n orgSnapshots.delete(tenant.orgId);\n}\n\n/** Test hook: clear registration and cached org snapshots. */\nexport function resetCustomProvidersSourceForTests(): void {\n setCustomProvidersSource(undefined);\n orgSnapshots.clear();\n}\n\n/**\n * Middleware mounted after the web auth gate: primes the caller's org snapshot\n * so the request's first model call sees their custom providers without an\n * async seam in model resolution. Cheap when fresh (TTL check), best-effort\n * when not — a failed hydrate serves the last snapshot, never blocks a request.\n */\nexport function createCustomProvidersPrimer({\n auth,\n storage,\n authEnabled,\n}: {\n auth: RouteAuth;\n storage: CustomProvidersStorage;\n authEnabled: boolean;\n}): MiddlewareHandler {\n return async (c, next) => {\n const orgId = orgForTenant(auth.tenant(c), authEnabled);\n if (orgId) {\n try {\n await snapshotFor(orgId, storage).ensureFresh();\n } catch {\n // Fail open: model calls serve the last snapshot (or none).\n }\n }\n await next();\n };\n}\n","/**\n * Per-request model-provider credential context.\n *\n * The provider config/OAuth routes serve two deployment shapes:\n *\n * - **Local** (no web auth adapter): credentials live in the server-global\n * file-backed `AuthStorage` (`auth.json`) — unchanged TUI behavior.\n * - **Tenant** (auth adapter active): credentials live in the\n * `model-credentials` factory storage domain, scoped per `(orgId, userId)`\n * with optional org-wide rows (`userId` absent).\n *\n * `resolveCredentialContext` decides which shape a request is in: an\n * authenticated user always gets the tenant path; an unauthenticated request\n * is rejected when auth is enabled and falls back to local otherwise.\n */\n\nimport type { Context } from 'hono';\n\nimport type {\n CredentialRecord,\n LoginSessionKind,\n ModelCredentialsStorage,\n} from '../storage/domains/credentials/base.js';\nimport type { RouteAuth } from './route.js';\n\n/**\n * OAuth credentials are stored under the auth provider id, which differs from\n * the catalog provider id for OpenAI (stored as `openai-codex`). Tenant rows\n * use the same keying so one lookup serves both OAuth tokens and API keys.\n */\nexport function getAuthProviderId(provider: string): string {\n return provider === 'openai' ? 'openai-codex' : provider;\n}\n\n/**\n * Providers that support a browser-driven OAuth sign-in flow, keyed by\n * *catalog* provider id (what the routes and settings UI use). All flows need\n * no inbound connection to the server: Anthropic uses paste-code PKCE, the\n * rest use RFC 8628-style device codes.\n */\nexport const WEB_OAUTH_FLOW_KINDS: Readonly<Record<string, LoginSessionKind>> = {\n anthropic: 'paste-code',\n openai: 'device-code',\n 'github-copilot': 'device-code',\n xai: 'device-code',\n};\n\nexport type CredentialContext =\n { mode: 'local' } | { mode: 'tenant'; storage: ModelCredentialsStorage; orgId: string; userId: string };\n\n/**\n * The tenant credentials domain, when registered and ready. `undefined` means\n * the factory never ran (no handle threaded in) or the domain's init failed\n * (fail-soft — callers report the feature unavailable instead of crashing).\n */\nexport async function getTenantCredentialsStorage(\n credentials: ModelCredentialsStorage | undefined,\n): Promise<ModelCredentialsStorage | undefined> {\n if (!credentials) return undefined;\n try {\n await credentials.ensureReady();\n } catch {\n return undefined;\n }\n return credentials;\n}\n\n/**\n * Org key for tenant rows. Personal accounts get an org bootstrapped by the\n * auth adapter (`ensureOrg`); if one still isn't present, scope rows under a\n * per-user synthetic org so credentials never become server-global.\n */\nexport function tenantOrgId(tenant: { orgId?: string; userId: string }): string {\n return tenant.orgId ?? `user:${tenant.userId}`;\n}\n\n/**\n * Resolve the credential context for a request, or a ready-to-return error\n * response. Mutating credential routes call this and hard-fail (401/503)\n * when the tenant path is required but unavailable.\n */\nexport async function resolveCredentialContext({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) {\n // When an auth provider is active, credential operations always require a\n // signed-in caller — otherwise one anonymous request could write keys for\n // everyone. Without a provider this is a single-user local server.\n if (auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n return { mode: 'local' };\n }\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) {\n return {\n response: c.json(\n {\n error: 'credentials_unavailable',\n message: 'Tenant credential storage is unavailable — the app database is not configured or failed to start.',\n },\n 503,\n ),\n };\n }\n return { mode: 'tenant', storage, orgId: tenantOrgId(tenant), userId: tenant.userId };\n}\n\n/**\n * List the caller's tenant credential records for provider listing, or\n * `undefined` in local mode (caller should fall back to `AuthStorage`).\n * Read-only and degradation-friendly: an authenticated caller with the domain\n * unavailable gets an empty list (sources show `env`/`none`) instead of a 503\n * so the settings page still renders.\n */\nexport async function listTenantCredentialsForRequest({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialRecord[] | undefined> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return auth.enabled() ? [] : undefined;\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) return [];\n return storage.listCredentials(tenantOrgId(tenant), tenant.userId);\n}\n"],"mappings":";AAmBA,SAAS,gCAAgC;;;ACqDlC,SAAS,YAAY,QAAoD;AAC9E,SAAO,OAAO,SAAS,QAAQ,OAAO,MAAM;AAC9C;;;AD9CA,IAAM,kBAAkB;AAGxB,IAAM,kBAAkB;AAGxB,IAAM,YAAY;AAElB,IAAM,6BAAN,MAAiC;AAAA,EACtB;AAAA,EACA;AAAA,EACT,YAAwC,CAAC;AAAA,EACzC,aAAa;AAAA,EACb;AAAA,EAEA,YAAY,OAAe,SAAiC;AAC1D,SAAK,SAAS;AACd,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA,EAGA,MAAM,YAAY,MAAM,KAAK,IAAI,GAAkB;AACjD,QAAI,MAAM,KAAK,aAAa,gBAAiB;AAC7C,SAAK,eAAe,KAAK,SAAS,EAAE,QAAQ,MAAM;AAChD,WAAK,aAAa;AAAA,IACpB,CAAC;AACD,UAAM,KAAK;AAAA,EACb;AAAA,EAEA,MAAM,WAA0B;AAC9B,UAAM,KAAK,SAAS,YAAY;AAChC,UAAM,UAAU,MAAM,KAAK,SAAS,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;AAC/D,SAAK,YAAY,QAAQ,IAAI,aAAW;AAAA,MACtC,MAAM,OAAO;AAAA,MACb,KAAK,OAAO;AAAA,MACZ,QAAQ,OAAO,UAAU;AAAA,MACzB,QAAQ,OAAO;AAAA,IACjB,EAAE;AACF,SAAK,aAAa,KAAK,IAAI;AAAA,EAC7B;AAAA;AAAA,EAGA,MAAkC;AAChC,QAAI,KA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