import { z } from 'zod'; import { DomainError, executorSettingFields, executorSettingsInput, isProduction, plainHttpAllowed, providerBaseUrl, providerCatalog, providers, type Actor, type Entity, type ExecutorSettings, type ProviderId, } from '@wishforge/contracts'; import type { Store, Transaction } from '../db/store.js'; import { record, touch } from './control-plane.js'; import { nativeClaudeEnabled } from './local-execution.js'; import { requireHuman, requireRole } from './policy.js'; const providerParam = z.enum(providers); type Settings = Omit; /** * Why a tenant's base URL cannot apply to this executor here, or undefined when it can: only with * the tenant's own key, sent straight to the model API. Production and the model proxy use the * operator's upstream, and the deployment's native Claude account must never be sent elsewhere. */ export function tenantBaseUrlBlocked(env: NodeJS.ProcessEnv, tenantId: string, provider: ProviderId) { if (!providerCatalog[provider].settings.includes('baseUrl')) return 'unsupported'; if (isProduction(env) || env.WF_PROVIDER_PROXY_ENABLED === 'true') return 'operator_managed'; if (provider === 'claude-code' && nativeClaudeEnabled(env, tenantId)) return 'native_account'; return undefined; } /** An HTTPS origin with an optional path; plain HTTP only where services may use it (plainHttpAllowed). */ export function tenantBaseUrl(env: NodeJS.ProcessEnv, value: string) { let url: URL; try { url = new URL(value); } catch { throw new DomainError('INVALID_BASE_URL', 'The base URL must be a URL such as https://gateway.example/v1', 400); } if ( !(url.protocol === 'https:' || plainHttpAllowed(env, url)) || url.username || url.password || url.search || url.hash ) throw new DomainError( 'INVALID_BASE_URL', 'The base URL must use HTTPS and carry no credentials, query or fragment', 400, ); return url.href.replace(/\/$/, ''); } /** * The gateway a tenant's own key is sent to: the tenant's configured `baseUrl` where allowed, * otherwise the operator's `providerBaseUrl`. Never used with the operator's native login. */ export function effectiveBaseUrl( env: NodeJS.ProcessEnv, tenantId: string, provider: ProviderId, settings: Pick = {}, ) { const configured = settings.baseUrl && !tenantBaseUrlBlocked(env, tenantId, provider) ? tenantBaseUrl(env, settings.baseUrl) : undefined; return configured ?? providerBaseUrl(env, provider); } /** The settings of one executor, or none; tolerant of fields the executor no longer takes. */ export async function storedExecutorSettings(tx: Transaction, provider: ProviderId): Promise { const stored = await tx.get('executor_settings', provider); if (!stored) return {}; const supported = providerCatalog[provider].settings; return Object.fromEntries( executorSettingFields.flatMap(field => supported.includes(field) && stored[field] !== undefined && stored[field] !== null ? [[field, stored[field]]] : [], ), ) as Settings; } /** What the executor of a run applies besides the model: its run context's `executorSettings`. */ export async function runExecutorSettings(tx: Transaction, provider: ProviderId) { const { smallFastModel, fallbackModel, timeoutMinutes } = await storedExecutorSettings(tx, provider); return { ...(smallFastModel ? { smallFastModel } : {}), ...(fallbackModel ? { fallbackModel } : {}), ...(timeoutMinutes ? { timeoutMinutes } : {}), }; } /** * A tenant admin's settings for each executor: gateway, models and time limit. Unset fields keep * the operator's configuration. Settings are not secret; keys stay in provider connections. */ export class ExecutorSettingsService { constructor( private store: Store, private env = process.env, ) {} private view(tenantId: string, provider: ProviderId, settings: Settings, stored?: ExecutorSettings) { const blocked = tenantBaseUrlBlocked(this.env, tenantId, provider); return { provider, ...settings, supported: providerCatalog[provider].settings, baseUrlAllowed: !blocked, ...(blocked && providerCatalog[provider].settings.includes('baseUrl') ? { baseUrlBlocked: blocked } : {}), ...(stored ? { version: stored.version, updatedAt: stored.updatedAt } : {}), }; } list(actor: Actor) { requireRole(actor, ['owner', 'admin']); return this.store.read(actor.tenantId, async tx => Promise.all( providers.map(async provider => this.view( actor.tenantId, provider, await storedExecutorSettings(tx, provider), await tx.get('executor_settings', provider), ), ), ), ); } async get(actor: Actor, provider: unknown) { requireRole(actor, ['owner', 'admin']); const id = providerParam.parse(provider); return this.store.read(actor.tenantId, async tx => this.view( actor.tenantId, id, await storedExecutorSettings(tx, id), await tx.get('executor_settings', id), ), ); } /** Replaces the executor's settings; the same body again changes nothing. */ async put(actor: Actor, provider: unknown, input: unknown) { requireHuman(actor); requireRole(actor, ['owner', 'admin']); const id = providerParam.parse(provider); const data = executorSettingsInput.parse(input); const supported = providerCatalog[id].settings; const unsupported = executorSettingFields.filter(field => data[field] !== undefined && !supported.includes(field)); if (unsupported.length) throw new DomainError( 'SETTING_UNSUPPORTED', `${providerCatalog[id].name} does not take these settings: ${unsupported.join(', ')}`, 400, ); const settings: Settings = Object.fromEntries( executorSettingFields.flatMap(field => (data[field] !== undefined ? [[field, data[field]]] : [])), ); if (settings.baseUrl !== undefined) { const blocked = tenantBaseUrlBlocked(this.env, actor.tenantId, id); if (blocked) throw new DomainError( 'BASE_URL_OPERATOR_MANAGED', blocked === 'native_account' ? 'This executor runs on the deployment’s own Claude account, whose gateway the operator sets' : 'The operator manages the model gateway of this deployment', 400, ); settings.baseUrl = tenantBaseUrl(this.env, settings.baseUrl); } if (settings.fallbackModel && settings.fallbackModel === settings.defaultModel) throw new DomainError('INVALID_FALLBACK_MODEL', 'The fallback model must differ from the default model', 400); return this.store.transaction(actor.tenantId, async tx => { const current = await tx.get('executor_settings', id); const same = current && executorSettingFields.every(field => (current[field] ?? undefined) === (settings[field] ?? undefined)); if (same) return this.view(actor.tenantId, id, settings, current); const next: ExecutorSettings = { ...(current ? touch(current) : { ...record(actor.tenantId), id }), provider: id, ...Object.fromEntries(executorSettingFields.map(field => [field, undefined])), ...settings, updatedBy: actor.userId, }; // Stored rows are JSON: unset fields are left out rather than kept as undefined. for (const field of executorSettingFields) if (next[field] === undefined) delete next[field]; await tx.put('executor_settings', next); return this.view(actor.tenantId, id, settings, next); }); } }