@mastra/factory 0.7.0 → 0.7.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +7 -1
- package/dist/auth.js.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +5 -0
- package/dist/factory.js.map +1 -1
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +6 -30
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +2 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +3 -3
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/index.d.ts +1 -1
- package/dist/rules/index.d.ts.map +1 -1
- package/dist/rules/index.js +2 -2
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +4 -4
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/transition-service.js +2 -2
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +1 -0
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +4 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +2 -11
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/memory-settings-hydration.d.ts +71 -0
- package/dist/session/memory-settings-hydration.d.ts.map +1 -0
- package/dist/session/memory-settings-hydration.js +57 -0
- package/dist/session/memory-settings-hydration.js.map +1 -0
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":[],"sources":["../../src/routes/config.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport { DEFAULT_OM_MODEL_ID } from '@mastra/code-sdk/constants';\nimport { getAvailableModePacks, resolveProviderOMDefault } from '@mastra/code-sdk/onboarding/packs';\nimport type { ModePack, ProviderAccess, ProviderAccessLevel } from '@mastra/code-sdk/onboarding/packs';\nimport {\n getCustomProviderId,\n isThinkingLevelSetting,\n loadSettings,\n saveSettings,\n THINKING_LEVEL_VALUES,\n THREAD_ACTIVE_MODEL_PACK_ID_KEY,\n} from '@mastra/code-sdk/onboarding/settings';\nimport type { CustomProviderSetting, ThinkingLevelSetting } 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'\n | 'stored'\n | 'env'\n | 'none'\n | 'oauth-user'\n | 'stored-user'\n | '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 /**\n * Tenant mode: whether an org-wide API key exists for this provider, even\n * when the caller's personal credential shadows it. Lets the UI tell\n * \"shared with the org\" apart from \"only works for me\".\n */\n orgKey?: boolean;\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 let orgKey: boolean | undefined;\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 orgKey = orgRec?.credential.type === 'api_key';\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 ...(orgKey !== undefined ? { orgKey } : {}),\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. Settings are persisted per organization and\n// user in the Factory app database. Requests with an active session also apply\n// changes immediately to that session's state and thread settings.\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 interface ProviderOMDefaultsResponse {\n ok: true;\n config: OMConfigInfo;\n}\n\n/** `GET /web/config/thinking` — deployment-scoped reasoning-effort defaults. */\nexport interface ThinkingConfigInfo {\n /** All selectable levels, in escalation order. */\n levels: readonly ThinkingLevelSetting[];\n /** `preferences.thinkingLevel` — fallback when a mode has no default. */\n globalDefault: ThinkingLevelSetting;\n /** `models.modeThinkingDefaults` — per-mode overrides of the global default. */\n modeDefaults: Record<string, ThinkingLevelSetting>;\n /** Mode ids known to the controller (for rendering per-mode rows). */\n modes: string[];\n}\n\n/** `PUT /web/config/thinking` success payload. */\nexport interface UpdateThinkingConfigResponse {\n ok: true;\n globalDefault: ThinkingLevelSetting;\n modeDefaults: Record<string, ThinkingLevelSetting>;\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\nfunction readStoredOMConfig(record: MemorySettingsRecord | null): OMConfigInfo {\n return {\n observerModelId: record?.observerModelId ?? DEFAULT_OM_MODEL_ID,\n reflectorModelId: record?.reflectorModelId ?? DEFAULT_OM_MODEL_ID,\n observationThreshold: record?.observationThreshold ?? DEFAULT_OBSERVATION_THRESHOLD,\n reflectionThreshold: record?.reflectionThreshold ?? DEFAULT_REFLECTION_THRESHOLD,\n observeAttachments: record?.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 * Path of the server's settings.json backing the deployment-scoped thinking\n * defaults. Defaults to the standard app-data location; injectable for tests.\n */\n settingsPath?: string;\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/thinking` — read thinking (reasoning-effort) defaults\n * - `PUT /web/config/thinking` — set global/per-mode thinking defaults\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 // Tenant mode also reports whether the caller may write org-wide\n // keys, so the settings UI can gate the \"Everyone in org\" option.\n const tenant = auth.tenant(loose(c));\n const orgKeyAdmin = tenant ? await auth.isOrganizationAdmin(loose(c), tenantOrgId(tenant)) : undefined;\n return c.json({\n providers: await listProviders({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n }),\n ...(orgKeyAdmin !== undefined ? { orgKeyAdmin } : {}),\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 // ── Thinking (reasoning-effort) defaults ─────────────────────────────────\n // Deployment-scoped defaults stored in the server's settings.json: the\n // global `preferences.thinkingLevel` plus per-mode\n // `models.modeThinkingDefaults`. These are what request-time resolution\n // falls back to when a session carries no explicit override — including\n // automated (rule-driven) Factory runs nobody opens interactively. In\n // tenant mode, writes are disabled because the settings file is shared\n // deployment-wide rather than scoped to an organization.\n\n registerApiRoute('/web/config/thinking', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n try {\n const settings = loadSettings(options.settingsPath);\n const modes = controller.listModes?.().map(mode => mode.id) ?? [];\n return c.json({\n levels: THINKING_LEVEL_VALUES,\n globalDefault: settings.preferences.thinkingLevel,\n modeDefaults: settings.models.modeThinkingDefaults,\n modes,\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/thinking', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n if (auth.enabled()) {\n return c.json({ error: 'Deployment thinking defaults can only be changed in local mode' }, 403);\n }\n let body: { globalDefault?: unknown; modeDefaults?: unknown };\n try {\n const parsed: unknown = await c.req.json();\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return c.json({ error: 'Request body must be a JSON object' }, 400);\n }\n body = parsed as { globalDefault?: unknown; modeDefaults?: unknown };\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n if (body.globalDefault === undefined && body.modeDefaults === undefined) {\n return c.json({ error: 'Provide globalDefault and/or modeDefaults' }, 400);\n }\n if (body.globalDefault !== undefined && !isThinkingLevelSetting(body.globalDefault)) {\n return c.json(\n { error: `Invalid globalDefault — expected one of: ${THINKING_LEVEL_VALUES.join(', ')}` },\n 400,\n );\n }\n // Per-mode patch semantics: a valid level sets the mode's default,\n // `null` clears it (back to the global default).\n const modePatch: Record<string, ThinkingLevelSetting | null> = {};\n if (body.modeDefaults !== undefined) {\n if (!body.modeDefaults || typeof body.modeDefaults !== 'object' || Array.isArray(body.modeDefaults)) {\n return c.json({ error: 'modeDefaults must be an object of mode → level (or null to clear)' }, 400);\n }\n const knownModes = new Set(controller.listModes?.().map(mode => mode.id) ?? []);\n for (const [mode, level] of Object.entries(body.modeDefaults as Record<string, unknown>)) {\n if (!knownModes.has(mode)) {\n return c.json({ error: `Unknown mode \"${mode}\"` }, 400);\n }\n if (level === null) {\n modePatch[mode] = null;\n } else if (isThinkingLevelSetting(level)) {\n modePatch[mode] = level;\n } else {\n return c.json(\n { error: `Invalid level for mode \"${mode}\" — expected one of: ${THINKING_LEVEL_VALUES.join(', ')}` },\n 400,\n );\n }\n }\n }\n try {\n const settings = loadSettings(options.settingsPath);\n if (body.globalDefault !== undefined && isThinkingLevelSetting(body.globalDefault)) {\n settings.preferences.thinkingLevel = body.globalDefault;\n }\n for (const [mode, level] of Object.entries(modePatch)) {\n if (level === null) delete settings.models.modeThinkingDefaults[mode];\n else settings.models.modeThinkingDefaults[mode] = level;\n }\n saveSettings(settings, options.settingsPath);\n return c.json({\n ok: true,\n globalDefault: settings.preferences.thinkingLevel,\n modeDefaults: settings.models.modeThinkingDefaults,\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/om/provider-defaults', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n let body: { providerId?: unknown; factoryModelId?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const providerId = typeof body.providerId === 'string' ? body.providerId.trim() : '';\n const factoryModelId = typeof body.factoryModelId === 'string' ? body.factoryModelId.trim() : '';\n if (!providerId) return c.json({ error: 'Missing required field: providerId' }, 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\n try {\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n const access = await buildProviderAccess({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n });\n if (!access[providerId]) return c.json({ error: `Provider \"${providerId}\" is not configured` }, 400);\n\n const modelId = resolveProviderOMDefault(providerId, factoryModelId).modelId;\n const record = await context.storage.patch({\n orgId: context.orgId,\n userId: context.userId,\n patch: {},\n fillIfUnset: { observerModelId: modelId, reflectorModelId: modelId },\n });\n return c.json({ ok: true, config: readStoredOMConfig(record) });\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 durably stored in the\n // per-(org, user) `memory-settings` app table — never settings.json. When a\n // session is supplied, changes are also applied to its state and thread.\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 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 record = await context.storage.get({ orgId: context.orgId, userId: context.userId });\n if (!resourceId) return c.json({ config: readStoredOMConfig(record) });\n\n // Session sync is best-effort: the stored row is authoritative and\n // new sessions hydrate from it, so a resourceId without a live\n // session (e.g. settings page after a restart) still reads the\n // stored config instead of failing.\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ config: readStoredOMConfig(record) });\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 (!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 // Best-effort session sync: persist regardless, apply to the live\n // session only when one exists for the resourceId.\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n const otherRole = session ? (role === 'observer' ? session.om.reflector : session.om.observer) : undefined;\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 const config = session\n ? readOMConfig(session)\n : readStoredOMConfig(await context.storage.get({ orgId: context.orgId, userId: context.userId }));\n return c.json({ ok: true, config });\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 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 // Best-effort session sync: persist regardless, apply to the live\n // session only when one exists for the resourceId.\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n if (observation !== undefined && session) {\n await session.state.set({ observationThreshold: observation });\n await session.thread.setSetting({ key: 'observationThreshold', value: observation });\n }\n if (reflection !== undefined && session) {\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 const config = session\n ? readOMConfig(session)\n : readStoredOMConfig(await context.storage.get({ orgId: context.orgId, userId: context.userId }));\n return c.json({ ok: true, config });\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 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 // Best-effort session sync: persist regardless, apply to the live\n // session only when one exists for the resourceId.\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n if (session) {\n await session.state.set({ observeAttachments: value });\n await session.thread.setSetting({ key: 'observeAttachments', value });\n }\n await persistMemorySettings(context, { observeAttachments: value });\n const config = session\n ? readOMConfig(session)\n : readStoredOMConfig(await context.storage.get({ orgId: context.orgId, userId: context.userId }));\n return c.json({ ok: true, config });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;AAyCA,SAAS,MAAM,GAAqB;CAClC,OAAO;AACT;;;;;;;;;;AAuGA,eAAsB,cAAc,EAClC,YACA,aACA,qBAK0B;CAC1B,MAAM,SAAS,MAAM,WAAW,oBAAoB;CACpD,MAAM,uBAAO,IAAI,IAA0B;CAE3C,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,KAAK,IAAI,MAAM,QAAQ,GAAG;EAE9B,MAAM,iBAAiB,kBAAkB,MAAM,QAA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,QAAQ;KAC1B,CAAC;KACD,IAAI,cAAc,SAAS,OAAO,QAAQ;KAC1C,IAAI;MAGF,MAAM,UAAU,aAAa,MAAM,WAAW,uBAAuB,YAAY,KAAK,IAAI,KAAA;MAC1F,IAAI,SAAS;OACX,MAAM,QAAQ,MAAM,IAAI,EAAE,oBAAoB,MAAM,CAAC;OACrD,MAAM,QAAQ,OAAO,WAAW;QAAE,KAAK;QAAsB;OAAM,CAAC;MACtE;MACA,MAAM,sBAAsB,SAAS,EAAE,oBAAoB,MAAM,CAAC;MAClE,MAAM,SAAS,UACX,aAAa,OAAO,IACpB,mBAAmB,MAAM,QAAQ,QAAQ,IAAI;OAAE,OAAO,QAAQ;OAAO,QAAQ,QAAQ;MAAO,CAAC,CAAC;MAClG,OAAO,EAAE,KAAK;OAAE,IAAI;OAAM;MAAO,CAAC;KACpC,SAAS,OAAO;MACd,OAAO,EAAE,KAAK,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG,GAAG;KACtF;IACF;GACF,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../../src/routes/config.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport { DEFAULT_OM_MODEL_ID } from '@mastra/code-sdk/constants';\nimport { getAvailableModePacks, resolveProviderOMDefault } from '@mastra/code-sdk/onboarding/packs';\nimport type { ModePack, ProviderAccess, ProviderAccessLevel } from '@mastra/code-sdk/onboarding/packs';\nimport {\n getCustomProviderId,\n isThinkingLevelSetting,\n loadSettings,\n saveSettings,\n THINKING_LEVEL_VALUES,\n THREAD_ACTIVE_MODEL_PACK_ID_KEY,\n} from '@mastra/code-sdk/onboarding/settings';\nimport type { CustomProviderSetting, ThinkingLevelSetting } 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 {\n applyStoredMemorySettings,\n DEFAULT_OBSERVATION_THRESHOLD,\n DEFAULT_REFLECTION_THRESHOLD,\n} from '../session/memory-settings-hydration.js';\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'\n | 'stored'\n | 'env'\n | 'none'\n | 'oauth-user'\n | 'stored-user'\n | '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 /**\n * Tenant mode: whether an org-wide API key exists for this provider, even\n * when the caller's personal credential shadows it. Lets the UI tell\n * \"shared with the org\" apart from \"only works for me\".\n */\n orgKey?: boolean;\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 let orgKey: boolean | undefined;\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 orgKey = orgRec?.credential.type === 'api_key';\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 ...(orgKey !== undefined ? { orgKey } : {}),\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. Settings are persisted per organization and\n// user in the Factory app database. Requests with an active session also apply\n// changes immediately to that session's state and thread settings.\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 interface ProviderOMDefaultsResponse {\n ok: true;\n config: OMConfigInfo;\n}\n\n/** `GET /web/config/thinking` — deployment-scoped reasoning-effort defaults. */\nexport interface ThinkingConfigInfo {\n /** All selectable levels, in escalation order. */\n levels: readonly ThinkingLevelSetting[];\n /** `preferences.thinkingLevel` — fallback when a mode has no default. */\n globalDefault: ThinkingLevelSetting;\n /** `models.modeThinkingDefaults` — per-mode overrides of the global default. */\n modeDefaults: Record<string, ThinkingLevelSetting>;\n /** Mode ids known to the controller (for rendering per-mode rows). */\n modes: string[];\n}\n\n/** `PUT /web/config/thinking` success payload. */\nexport interface UpdateThinkingConfigResponse {\n ok: true;\n globalDefault: ThinkingLevelSetting;\n modeDefaults: Record<string, ThinkingLevelSetting>;\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\nfunction readStoredOMConfig(record: MemorySettingsRecord | null): OMConfigInfo {\n return {\n observerModelId: record?.observerModelId ?? DEFAULT_OM_MODEL_ID,\n reflectorModelId: record?.reflectorModelId ?? DEFAULT_OM_MODEL_ID,\n observationThreshold: record?.observationThreshold ?? DEFAULT_OBSERVATION_THRESHOLD,\n reflectionThreshold: record?.reflectionThreshold ?? DEFAULT_REFLECTION_THRESHOLD,\n observeAttachments: record?.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/** 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 * Path of the server's settings.json backing the deployment-scoped thinking\n * defaults. Defaults to the standard app-data location; injectable for tests.\n */\n settingsPath?: string;\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/thinking` — read thinking (reasoning-effort) defaults\n * - `PUT /web/config/thinking` — set global/per-mode thinking defaults\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 // Tenant mode also reports whether the caller may write org-wide\n // keys, so the settings UI can gate the \"Everyone in org\" option.\n const tenant = auth.tenant(loose(c));\n const orgKeyAdmin = tenant ? await auth.isOrganizationAdmin(loose(c), tenantOrgId(tenant)) : undefined;\n return c.json({\n providers: await listProviders({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n }),\n ...(orgKeyAdmin !== undefined ? { orgKeyAdmin } : {}),\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 // ── Thinking (reasoning-effort) defaults ─────────────────────────────────\n // Deployment-scoped defaults stored in the server's settings.json: the\n // global `preferences.thinkingLevel` plus per-mode\n // `models.modeThinkingDefaults`. These are what request-time resolution\n // falls back to when a session carries no explicit override — including\n // automated (rule-driven) Factory runs nobody opens interactively. In\n // tenant mode, writes are disabled because the settings file is shared\n // deployment-wide rather than scoped to an organization.\n\n registerApiRoute('/web/config/thinking', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n try {\n const settings = loadSettings(options.settingsPath);\n const modes = controller.listModes?.().map(mode => mode.id) ?? [];\n return c.json({\n levels: THINKING_LEVEL_VALUES,\n globalDefault: settings.preferences.thinkingLevel,\n modeDefaults: settings.models.modeThinkingDefaults,\n modes,\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/thinking', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n if (auth.enabled()) {\n return c.json({ error: 'Deployment thinking defaults can only be changed in local mode' }, 403);\n }\n let body: { globalDefault?: unknown; modeDefaults?: unknown };\n try {\n const parsed: unknown = await c.req.json();\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return c.json({ error: 'Request body must be a JSON object' }, 400);\n }\n body = parsed as { globalDefault?: unknown; modeDefaults?: unknown };\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n if (body.globalDefault === undefined && body.modeDefaults === undefined) {\n return c.json({ error: 'Provide globalDefault and/or modeDefaults' }, 400);\n }\n if (body.globalDefault !== undefined && !isThinkingLevelSetting(body.globalDefault)) {\n return c.json(\n { error: `Invalid globalDefault — expected one of: ${THINKING_LEVEL_VALUES.join(', ')}` },\n 400,\n );\n }\n // Per-mode patch semantics: a valid level sets the mode's default,\n // `null` clears it (back to the global default).\n const modePatch: Record<string, ThinkingLevelSetting | null> = {};\n if (body.modeDefaults !== undefined) {\n if (!body.modeDefaults || typeof body.modeDefaults !== 'object' || Array.isArray(body.modeDefaults)) {\n return c.json({ error: 'modeDefaults must be an object of mode → level (or null to clear)' }, 400);\n }\n const knownModes = new Set(controller.listModes?.().map(mode => mode.id) ?? []);\n for (const [mode, level] of Object.entries(body.modeDefaults as Record<string, unknown>)) {\n if (!knownModes.has(mode)) {\n return c.json({ error: `Unknown mode \"${mode}\"` }, 400);\n }\n if (level === null) {\n modePatch[mode] = null;\n } else if (isThinkingLevelSetting(level)) {\n modePatch[mode] = level;\n } else {\n return c.json(\n { error: `Invalid level for mode \"${mode}\" — expected one of: ${THINKING_LEVEL_VALUES.join(', ')}` },\n 400,\n );\n }\n }\n }\n try {\n const settings = loadSettings(options.settingsPath);\n if (body.globalDefault !== undefined && isThinkingLevelSetting(body.globalDefault)) {\n settings.preferences.thinkingLevel = body.globalDefault;\n }\n for (const [mode, level] of Object.entries(modePatch)) {\n if (level === null) delete settings.models.modeThinkingDefaults[mode];\n else settings.models.modeThinkingDefaults[mode] = level;\n }\n saveSettings(settings, options.settingsPath);\n return c.json({\n ok: true,\n globalDefault: settings.preferences.thinkingLevel,\n modeDefaults: settings.models.modeThinkingDefaults,\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/om/provider-defaults', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n let body: { providerId?: unknown; factoryModelId?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const providerId = typeof body.providerId === 'string' ? body.providerId.trim() : '';\n const factoryModelId = typeof body.factoryModelId === 'string' ? body.factoryModelId.trim() : '';\n if (!providerId) return c.json({ error: 'Missing required field: providerId' }, 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\n try {\n const tenantCredentials = await listTenantCredentialsForRequest({\n c: loose(c),\n auth,\n credentials: options.modelCredentials,\n });\n const access = await buildProviderAccess({\n controller,\n authStorage: tenantCredentials ? undefined : authStorage,\n tenantCredentials,\n });\n if (!access[providerId]) return c.json({ error: `Provider \"${providerId}\" is not configured` }, 400);\n\n const modelId = resolveProviderOMDefault(providerId, factoryModelId).modelId;\n const record = await context.storage.patch({\n orgId: context.orgId,\n userId: context.userId,\n patch: {},\n fillIfUnset: { observerModelId: modelId, reflectorModelId: modelId },\n });\n return c.json({ ok: true, config: readStoredOMConfig(record) });\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 durably stored in the\n // per-(org, user) `memory-settings` app table — never settings.json. When a\n // session is supplied, changes are also applied to its state and thread.\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 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 record = await context.storage.get({ orgId: context.orgId, userId: context.userId });\n if (!resourceId) return c.json({ config: readStoredOMConfig(record) });\n\n // Session sync is best-effort: the stored row is authoritative and\n // new sessions hydrate from it, so a resourceId without a live\n // session (e.g. settings page after a restart) still reads the\n // stored config instead of failing.\n const session = await controller.getSessionByResource?.(resourceId, scope);\n if (!session) return c.json({ config: readStoredOMConfig(record) });\n await applyStoredMemorySettings(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 (!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 // Best-effort session sync: persist regardless, apply to the live\n // session only when one exists for the resourceId.\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n const otherRole = session ? (role === 'observer' ? session.om.reflector : session.om.observer) : undefined;\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 const config = session\n ? readOMConfig(session)\n : readStoredOMConfig(await context.storage.get({ orgId: context.orgId, userId: context.userId }));\n return c.json({ ok: true, config });\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 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 // Best-effort session sync: persist regardless, apply to the live\n // session only when one exists for the resourceId.\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n if (observation !== undefined && session) {\n await session.state.set({ observationThreshold: observation });\n await session.thread.setSetting({ key: 'observationThreshold', value: observation });\n }\n if (reflection !== undefined && session) {\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 const config = session\n ? readOMConfig(session)\n : readStoredOMConfig(await context.storage.get({ orgId: context.orgId, userId: context.userId }));\n return c.json({ ok: true, config });\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 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 // Best-effort session sync: persist regardless, apply to the live\n // session only when one exists for the resourceId.\n const session = resourceId ? await controller.getSessionByResource?.(resourceId, scope) : undefined;\n if (session) {\n await session.state.set({ observeAttachments: value });\n await session.thread.setSetting({ key: 'observeAttachments', value });\n }\n await persistMemorySettings(context, { observeAttachments: value });\n const config = session\n ? readOMConfig(session)\n : readStoredOMConfig(await context.storage.get({ orgId: context.orgId, userId: context.userId }));\n return c.json({ ok: true, config });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;AA8CA,SAAS,MAAM,GAAqB;CAClC,OAAO;AACT;;;;;;;;;;AAuGA,eAAsB,cAAc,EAClC,YACA,aACA,qBAK0B;CAC1B,MAAM,SAAS,MAAM,WAAW,oBAAoB;CACpD,MAAM,uBAAO,IAAI,IAA0B;CAE3C,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,KAAK,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@
|
|
|
1
|
-
{"version":3,"file":"surface.d.ts","sourceRoot":"","sources":["../../src/routes/surface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAEtF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC/E,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"surface.d.ts","sourceRoot":"","sources":["../../src/routes/surface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAEtF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;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AC,KAAK,EAAE,8BAA8B,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KAC3E,KAAK,IAAI,CAAC;CACZ;AAiDD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,8BAA8B,CAAC,MAAM,CAAC,GAAG,MAAM,CAsBtF;AAED;;;;;;GAMG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,iBAAiB,EACzB,WAAW,EAAE,uBAAuB,EACpC,QAAQ,EAAE,sBAAsB,EAChC,KAAK,EAAE,8BAA8B,GACpC,OAAO,CAAC,IAAI,CAAC,CAqCf;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,IAAI,CACR,oBAAoB,EACpB,YAAY,GAAG,cAAc,GAAG,MAAM,GAAG,OAAO,GAAG,gBAAgB,GAAG,oBAAoB,GAAG,sBAAsB,CACpH,GAAG;IACF,WAAW,EAAE,WAAW,CAAC;IACzB,SAAS,CAAC,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;IACjC,KAAK,EAAE,YAAY,CAAC;IACpB,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,EAAE,IAAI,CACX,oBAAoB,CAAC,SAAS,CAAC,EAC/B,UAAU,GAAG,QAAQ,GAAG,WAAW,GAAG,iBAAiB,GAAG,gBAAgB,CAC3E,CAAC;IACF;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B,EACD,aAAa,EAAE,MAAM,GACpB,kBAAkB,CAsBpB;AA4ED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,oBAAoB,GAAG,QAAQ,EAAE,CAoH/E"}
|
package/dist/routes/surface.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isFactoryRuleStage } from "../rules/types.js";
|
|
1
2
|
import { getGithubFeatureDiagnostics } from "../integrations/github/config.js";
|
|
2
3
|
import { invalidateCustomProvidersSnapshots } from "./custom-provider-source.js";
|
|
3
4
|
import { ensureFactorySourceSession, resolveFactoryDefaultModelId } from "../session/factory-session.js";
|
|
@@ -80,7 +81,7 @@ async function prepareFactoryRuleBinding(github, coordinator, projects, input) {
|
|
|
80
81
|
branch
|
|
81
82
|
});
|
|
82
83
|
const destinationStage = input.item.stages.length === 1 ? input.item.stages[0] : void 0;
|
|
83
|
-
if (!destinationStage) throw new Error("Factory skill invocation requires one exclusive board stage.");
|
|
84
|
+
if (!isFactoryRuleStage(destinationStage)) throw new Error("Factory skill invocation requires one exclusive board stage.");
|
|
84
85
|
await coordinator.prepare({
|
|
85
86
|
orgId: input.record.orgId,
|
|
86
87
|
userId: preparedSession.userId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport type { SandboxFleet } from '../sandbox/fleet.js';\nimport { ensureFactorySourceSession, resolveFactoryDefaultModelId } from '../session/factory-session.js';\nimport { LiveSessions } from '../session/live-sessions.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SourceControlStorage } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox fleet constructed by the factory (disabled when no machine). */\n fleet: SandboxFleet;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n filesystem: FilesystemStorage;\n modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n factoryTransitionService?: FactoryTransitionService;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\nexport function factoryRuleBranch(item: FactoryBindingPreparationInput['item']): string {\n const metadata = item.metadata ?? {};\n const issueNumber = metadata.githubIssueNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'issue' &&\n typeof issueNumber === 'number'\n ) {\n return `factory/issue-${issueNumber}`;\n }\n const pullRequestNumber = metadata.githubPullRequestNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'pull-request' &&\n typeof pullRequestNumber === 'number'\n ) {\n return `factory/pr-${pullRequestNumber}`;\n }\n if (item.externalSource?.integrationId === 'linear' && typeof metadata.identifier === 'string') {\n return `factory/linear-${metadata.identifier.toLowerCase()}`;\n }\n throw new Error('Factory skill invocation requires a supported issue or pull request identifier.');\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: FactoryStartCoordinator,\n projects: FactoryProjectsStorage,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n const branch = factoryRuleBranch(input.item);\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactorySourceSession({\n sourceControl: github.sourceControlStorage,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n });\n const destinationStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n if (!destinationStage) throw new Error('Factory skill invocation requires one exclusive board stage.');\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n defaultModelId: await resolveFactoryDefaultModelId(projects, input.record.factoryProjectId),\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage: destinationStage as 'intake' | 'triage' | 'planning' | 'execute' | 'review' | 'done',\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n 'controller' | 'publicOrigin' | 'auth' | 'fleet' | 'factoryStorage' | 'integrationStorage' | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n 'projects' | 'intake' | 'workItems' | 'channelIdentity' | 'memorySettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n fleet: deps.fleet,\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n },\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n fleet: deps.fleet,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/model-pack/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, deps.domains.projects, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n fleet: deps.fleet,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n filesystem: deps.domains.filesystem,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n memorySettings: deps.domains.memorySettings,\n customProviders: deps.domains.customProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\n ...integrationRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: new LiveSessions(deps.controller),\n }).routes()\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwFA,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAClB,OAAO,OAAO,KAAI,UAAS;EACzB,IAAI,aAAa,OAAO;GACtB,MAAM,UAAU,MAAM;GACtB,OAAO;IACL,GAAG;IACH,SAAS,OAAO,YAA2C;KACzD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,GACF;KACF;KACA,OAAO,QAAQ,SAAS,YAAY,CAAC,CAAC;IACxC;GACF;EACF;EAEA,MAAM,gBAAgB,MAAM;EAC5B,OAAO;GACL,GAAG;GACH,eAAe,OAAO,SAA8C;IAClE,MAAM,UAAU,MAAM,cAAc,IAAI;IACxC,OAAO,OAAO,YAA2C;KACvD,IAAI;MACF,MAAM,YAAY;KACpB,QA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AsB;EACxB,CAAC,CAAC,CAAC,OAAO;EACV,GAAG,IAAI,YAAY;GACjB,MAAM,KAAK;GACX,cAAc,KAAK;GACnB,YAAY,KAAK;GACjB,sBAAsB;GACtB,0BAA0B,oBAAoB;EAChD,CAAC,CAAC,CAAC,OAAO;EACV,GAAG;EACH,GAAG;EACH,GAAG;EACH,GAAI,KAAK,cACL,IAAI,aAAa;GACf,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,QAAQ,KAAK,QAAQ;GACrB,eAAe,KAAK,gBAAgB,CAAC,EAAA,CAAG,SAAS,EAAE,kBACjD,YAAY,SAAS,CAAC;IAAE,IAAI,YAAY;IAAI,QAAQ,YAAY;GAAO,CAAC,IAAI,CAAC,CAC/E;EACF,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,eACL,IAAI,eAAe;GACjB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,aAAa,KAAK,QAAQ;GAC1B;GACA;GACA,cAAc,IAAI,aAAa,KAAK,UAAU;EAChD,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;CACP;AACF"}
|
|
1
|
+
{"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport { isFactoryRuleStage } from '../rules/types.js';\nimport type { SandboxFleet } from '../sandbox/fleet.js';\nimport { ensureFactorySourceSession, resolveFactoryDefaultModelId } from '../session/factory-session.js';\nimport { LiveSessions } from '../session/live-sessions.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SourceControlStorage } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox fleet constructed by the factory (disabled when no machine). */\n fleet: SandboxFleet;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n filesystem: FilesystemStorage;\n modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n factoryTransitionService?: FactoryTransitionService;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\nexport function factoryRuleBranch(item: FactoryBindingPreparationInput['item']): string {\n const metadata = item.metadata ?? {};\n const issueNumber = metadata.githubIssueNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'issue' &&\n typeof issueNumber === 'number'\n ) {\n return `factory/issue-${issueNumber}`;\n }\n const pullRequestNumber = metadata.githubPullRequestNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'pull-request' &&\n typeof pullRequestNumber === 'number'\n ) {\n return `factory/pr-${pullRequestNumber}`;\n }\n if (item.externalSource?.integrationId === 'linear' && typeof metadata.identifier === 'string') {\n return `factory/linear-${metadata.identifier.toLowerCase()}`;\n }\n throw new Error('Factory skill invocation requires a supported issue or pull request identifier.');\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: FactoryStartCoordinator,\n projects: FactoryProjectsStorage,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n const branch = factoryRuleBranch(input.item);\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactorySourceSession({\n sourceControl: github.sourceControlStorage,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n });\n const destinationStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n if (!isFactoryRuleStage(destinationStage))\n throw new Error('Factory skill invocation requires one exclusive board stage.');\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n defaultModelId: await resolveFactoryDefaultModelId(projects, input.record.factoryProjectId),\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage,\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n 'controller' | 'publicOrigin' | 'auth' | 'fleet' | 'factoryStorage' | 'integrationStorage' | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n 'projects' | 'intake' | 'workItems' | 'channelIdentity' | 'memorySettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n fleet: deps.fleet,\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n },\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n fleet: deps.fleet,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/model-pack/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, deps.domains.projects, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n fleet: deps.fleet,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n filesystem: deps.domains.filesystem,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n memorySettings: deps.domains.memorySettings,\n customProviders: deps.domains.customProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\n ...integrationRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: new LiveSessions(deps.controller),\n }).routes()\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyFA,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAClB,OAAO,OAAO,KAAI,UAAS;EACzB,IAAI,aAAa,OAAO;GACtB,MAAM,UAAU,MAAM;GACtB,OAAO;IACL,GAAG;IACH,SAAS,OAAO,YAA2C;KACzD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MAC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