From 4e9e5fb8749168365ad52a6544c6b4384f97d4b4 Mon Sep 17 00:00:00 2001 From: eust-w Date: Wed, 4 Nov 2026 12:19:02 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E2=9C=A8=20Let=20tenant=20admins=20configu?= =?UTF-8?q?re=20each=20executor:=20gateway,=20models=20and=20time=20limit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A per-tenant, per-executor settings record (GET /executor-settings, GET/PUT /executor-settings/:provider, owner/admin, idempotent replace) with baseUrl, defaultModel, smallFastModel, fallbackModel, timeoutMinutes, askModel and askFallbackModel. Unset fields keep the operator's configuration. - defaultModel is pinned at submission below the wish and bundle models. - smallFastModel, fallbackModel and timeoutMinutes travel in the run context to the worker; Claude Code gets ANTHROPIC_SMALL_FAST_MODEL / ANTHROPIC_DEFAULT_HAIKU_MODEL and --fallback-model, CodeBuddy the limit. - baseUrl goes only with the tenant's own key, over HTTPS (plain HTTP only where plainHttpAllowed), never in production, behind the model proxy or with the deployment's native Claude account. - The wish refiner tries the tenant's ask models first. - The 执行器 page gets an 执行器设置 dialog, also in native-account mode; model fields (and the agent page's) accept gateway names like deepseek-flash@latest[1m]. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/api/src/domain/connections.ts | 11 +- apps/api/src/domain/control-plane.ts | 5 + apps/api/src/domain/executor-settings.ts | 179 ++++++++++++++++ apps/api/src/domain/wish-refiner.ts | 22 +- apps/api/src/http.ts | 17 ++ apps/web/src/app/globals.css | 9 + apps/web/src/features/agent.tsx | 9 +- apps/web/src/features/providers.tsx | 215 +++++++++++++++++-- apps/web/src/lib/types.ts | 20 +- apps/worker/src/common.ts | 2 + apps/worker/src/providers.ts | 20 +- docs/architecture.md | 2 +- docs/reference/ui.md | 2 +- docs/user-manual.md | 9 +- packages/contracts/src/entities.ts | 16 ++ packages/contracts/src/index.ts | 25 ++- packages/contracts/src/models.ts | 9 +- packages/contracts/src/providers.ts | 38 +++- packages/runtime/src/providers/codebuddy.ts | 38 +++- packages/runtime/test/claude-native.test.ts | 53 ++++- tests/executor-settings.test.ts | 225 ++++++++++++++++++++ tests/providers.test.ts | 47 +++- 22 files changed, 933 insertions(+), 40 deletions(-) create mode 100644 apps/api/src/domain/executor-settings.ts create mode 100644 tests/executor-settings.test.ts diff --git a/apps/api/src/domain/connections.ts b/apps/api/src/domain/connections.ts index f5c77c3..edcfb4a 100644 --- a/apps/api/src/domain/connections.ts +++ b/apps/api/src/domain/connections.ts @@ -14,6 +14,7 @@ import type { Store } from '../db/store.js'; import { record, touch, must, executionLease } from './control-plane.js'; import { requireHuman, requireRole } from './policy.js'; import { ProviderProxy } from './provider-proxy.js'; +import { storedExecutorSettings, tenantBaseUrl, tenantBaseUrlBlocked } from './executor-settings.js'; /** Production uses a Vault transit key. The development AES key never enters source control. */ export class CredentialVault { @@ -134,9 +135,10 @@ export class Connections { ) return undefined; executionLease(actor, current, run.lease!.token); - return (await tx.list('provider_connection')).find( + const found = (await tx.list('provider_connection')).find( c => c.provider === current.provider && c.status === 'active', ); + return found && { ...found, settings: await storedExecutorSettings(tx, current.provider) }; }); if (!connection?.ciphertext) return undefined; if (isProduction(this.env) || this.env.WF_PROVIDER_PROXY_ENABLED === 'true') { @@ -152,7 +154,12 @@ export class Connections { }; } const apiKey = await this.vault.open(actor.tenantId, String(connection.ciphertext)); - const baseUrl = providerBaseUrl(this.env, run.provider); + // The tenant's gateway goes only with the tenant's own key; otherwise the operator's, if any. + const tenantGateway = + connection.settings.baseUrl && !tenantBaseUrlBlocked(this.env, actor.tenantId, run.provider) + ? tenantBaseUrl(this.env, connection.settings.baseUrl) + : undefined; + const baseUrl = tenantGateway ?? providerBaseUrl(this.env, run.provider); // Vault I/O runs outside the transaction. Re-check revocation and lease after decrypting. return this.store.transaction(actor.tenantId, async tx => { const current = await must(tx, 'run', run.id); diff --git a/apps/api/src/domain/control-plane.ts b/apps/api/src/domain/control-plane.ts index f78077e..d2e2440 100644 --- a/apps/api/src/domain/control-plane.ts +++ b/apps/api/src/domain/control-plane.ts @@ -55,6 +55,7 @@ import { IntegrationLeases } from './integration-lease.js'; import { captureLesson, projectLessons } from './lessons.js'; import { projectSkills } from './skills.js'; import { describeProviderEvent } from './provider-events.js'; +import { runExecutorSettings, storedExecutorSettings } from './executor-settings.js'; import { backendDefined, personWishScope, requirePermission, wishScopeOf } from './permissions.js'; export const now = () => new Date().toISOString(); @@ -424,6 +425,7 @@ export class ControlPlane { } as Wish; const identity = record(actor.tenantId); const bundle = await activeBundle(tx); + const executor = await storedExecutorSettings(tx, data.provider); const run = { ...identity, projectId, @@ -438,6 +440,8 @@ export class ControlPlane { providerModel: model ?? bundle.config.model ?? + // The tenant's default for this executor, then the operator's. + executor.defaultModel ?? (data.provider === 'codex' ? (this.env.WF_CODEX_DEFAULT_MODEL ?? this.env.WF_PROVIDER_PROXY_ALLOWED_MODELS?.split(',')[0]?.trim()) : undefined), @@ -1407,6 +1411,7 @@ export class ControlPlane { bundleConfig: await resolveBundle(tx, run.bundleVersion), lessons: await projectLessons(tx, run.projectId), skills: await projectSkills(tx, run.projectId), + executorSettings: await runExecutorSettings(tx, run.provider), delivery: { release, verificationEvidenceId: current('verification'), diff --git a/apps/api/src/domain/executor-settings.ts b/apps/api/src/domain/executor-settings.ts new file mode 100644 index 0000000..d200b7d --- /dev/null +++ b/apps/api/src/domain/executor-settings.ts @@ -0,0 +1,179 @@ +import { z } from 'zod'; +import { + DomainError, + executorSettingFields, + executorSettingsInput, + isProduction, + plainHttpAllowed, + 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 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); + }); + } +} diff --git a/apps/api/src/domain/wish-refiner.ts b/apps/api/src/domain/wish-refiner.ts index 8a59c61..ae46156 100644 --- a/apps/api/src/domain/wish-refiner.ts +++ b/apps/api/src/domain/wish-refiner.ts @@ -3,6 +3,7 @@ import { askClaude } from '@wishforge/runtime'; import { DomainError, wishRefinementInput, type Actor } from '@wishforge/contracts'; import type { Store } from '../db/store.js'; import { projectAccess } from './control-plane.js'; +import { storedExecutorSettings } from './executor-settings.js'; import { nativeClaudeEnabled } from './local-execution.js'; import { requireRole } from './policy.js'; @@ -97,10 +98,16 @@ const CONCURRENCY = 2; const ASK_TIMEOUT_MS = 180_000; const FLASH = 'deepseek-flash@latest[1m]'; const PRO = 'deepseek-pro@latest[1m]'; -/** The small model first; the coding model if that one times out or returns JSON that does not parse. */ -function askModels(env: NodeJS.ProcessEnv): string[] { - const primary = env.WF_CLAUDE_ASK_MODEL || FLASH; - const fallback = env.WF_CLAUDE_ASK_FALLBACK_MODEL ?? PRO; +/** + * The small model first; the coding model if that one times out or returns JSON that does not + * parse. The tenant's Claude Code settings come before the operator's. + */ +export function askModels( + env: NodeJS.ProcessEnv, + tenant: { askModel?: string; askFallbackModel?: string } = {}, +): string[] { + const primary = tenant.askModel || env.WF_CLAUDE_ASK_MODEL || FLASH; + const fallback = tenant.askFallbackModel || (env.WF_CLAUDE_ASK_FALLBACK_MODEL ?? PRO); return [...new Set([primary, fallback].filter(Boolean))]; } let running = 0; @@ -122,7 +129,10 @@ export class WishRefiner { async refine(actor: Actor, projectId: string, input: unknown) { requireRole(actor, ['owner', 'admin', 'developer']); const draft = wishRefinementInput.parse(input); - const project = await this.store.read(actor.tenantId, tx => projectAccess(tx, actor, projectId)); + const [project, settings] = await this.store.read( + actor.tenantId, + async tx => [await projectAccess(tx, actor, projectId), await storedExecutorSettings(tx, 'claude-code')] as const, + ); if (!this.available(actor.tenantId)) throw new DomainError( 'REFINER_UNAVAILABLE', @@ -151,7 +161,7 @@ export class WishRefiner { schema, timeoutMs: ASK_TIMEOUT_MS, }; - const models = askModels(this.env); + const models = askModels(this.env, settings); let failure: unknown; for (const model of models) { try { diff --git a/apps/api/src/http.ts b/apps/api/src/http.ts index 5b52b5a..aaaa2ee 100644 --- a/apps/api/src/http.ts +++ b/apps/api/src/http.ts @@ -7,6 +7,7 @@ import { Inject, Param, Patch, + Put, Post, Query, Req, @@ -39,6 +40,7 @@ import { Lessons } from './domain/lessons.js'; import { Skills } from './domain/skills.js'; import { WishReports } from './domain/wish-report.js'; import { Connections } from './domain/connections.js'; +import { ExecutorSettingsService } from './domain/executor-settings.js'; import { RunnerBroker } from './domain/runner-broker.js'; import { GitStorage } from './domain/git-storage.js'; import { WorkspaceGit, commitAuthor } from './domain/workspace-git.js'; @@ -62,6 +64,7 @@ export class Services { skills: Skills; reports: WishReports; connections: Connections; + executorSettings: ExecutorSettingsService; runners: RunnerBroker; github: GitHubIntegration; accounts: LocalAccounts; @@ -75,6 +78,7 @@ export class Services { this.skills = new Skills(control.store, control.env); this.reports = new WishReports(control.store); this.connections = new Connections(control.store, control.env); + this.executorSettings = new ExecutorSettingsService(control.store, control.env); this.runners = new RunnerBroker(control.store, this.releases, control.env); this.github = new GitHubIntegration(control.store, control.env); this.accounts = new LocalAccounts(control.store, control.env); @@ -546,6 +550,19 @@ export class ApiController { @Delete('provider-connections/:id') async revoke(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.connections.revoke(r.actor, id)); } + @Get('executor-settings') async executorSettingsList(@Req() r: AuthRequest) { + return ok(await this.s.executorSettings.list(r.actor)); + } + @Get('executor-settings/:provider') async executorSettings(@Req() r: AuthRequest, @Param('provider') p: string) { + return ok(await this.s.executorSettings.get(r.actor, p)); + } + @Put('executor-settings/:provider') async putExecutorSettings( + @Req() r: AuthRequest, + @Param('provider') p: string, + @Body() b: unknown, + ) { + return ok(await this.s.executorSettings.put(r.actor, p, b)); + } @Get('environments') async envs(@Req() r: AuthRequest) { return ok(await this.s.releases.environments(r.actor)); } diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index dcb49d4..70dd385 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -1621,6 +1621,12 @@ button { color: var(--muted); line-height: 1.7; } +.provider-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} .inline-explanation { display: flex; align-items: flex-start; @@ -2439,6 +2445,9 @@ button { flex-basis: 100%; font-size: 11px; } + .provider-actions { + width: 100%; + } .provider-bottom .button { width: 100%; min-height: 35px; diff --git a/apps/web/src/features/agent.tsx b/apps/web/src/features/agent.tsx index 343884e..b984b81 100644 --- a/apps/web/src/features/agent.tsx +++ b/apps/web/src/features/agent.tsx @@ -1,6 +1,7 @@ 'use client'; import { History, Plus } from 'lucide-react'; import { useState } from 'react'; +import { MODEL_NAME_PATTERN } from '@wishforge/contracts/models'; import { messageOf, mutateApi, shortId, formatTime, useResource } from '@/lib/api'; import type { AgentBundleList } from '@/lib/types'; import { @@ -182,7 +183,13 @@ function CreateBundleDialog({ onClose, onSaved }: { onClose: () => void; onSaved