Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
fix: support explicitly configured HTTP model endpoints (#155)
澄潭fce9d367baf1
diff --git a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsxindex b6b8f4b4..dd82f7a9 100644--- a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx+++ b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx@@ -45,6 +45,7 @@ import { ConnectionEditingSession } from './connection-session';import './connection-flow.css';import {connectionErrorMessage,+ PlaintextHttpWarning,ManualModelEditor,manualModelError,manualModelIdError,@@ -709,7 +710,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {? `已收录 ${metadataCandidates.length} 个模型,检查接入后统一选择;未知能力采用可编辑兜底:上下文 200K、输出 32K、工具与流式开启、视觉关闭、思考开关。`: `${metadataCandidates.length} models in this catalog. Choose after checking the connection; missing capabilities use editable defaults (200K context, 32K output, tools and streaming on, vision off, reasoning toggle).`}</p>}</div></Disclosure>}- <label className="field"><span className="field-label">Base URL</span><input className="input" inputMode="url" value={draft.base_url} placeholder="https://example.com/v1" onChange={event => invalidate(current => ({ ...current, base_url: event.target.value }), true, 'connection')} /></label>+ <label className="field"><span className="field-label">Base URL</span><input className="input" inputMode="url" value={draft.base_url} placeholder="https://example.com/v1" onChange={event => invalidate(current => ({ ...current, base_url: event.target.value }), true, 'connection')} /><PlaintextHttpWarning baseUrl={draft.base_url} zh={zh} /></label><label className="field"><span className="field-label">{zh ? '协议' : 'Protocol'}</span><select className="select" value={draft.protocol} onChange={event => {const protocol = event.target.value as UpstreamProtocol;invalidate(current => {@@ -760,7 +761,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {return <section key={`${index}-${endpoint.protocol}`} className="connection-fields"><div className="detail-section-head"><strong>{zh ? '端点' : 'Endpoint'} {index + 2}</strong><button className="btn btn-quiet" type="button" onClick={() => invalidate(current => ({ ...current, additional_endpoints: current.additional_endpoints.filter((_, position) => position !== index) }), true, 'connection')}>{zh ? '移除' : 'Remove'}</button></div><label className="field"><span className="field-label">{zh ? '协议' : 'Protocol'}</span><select className="select" value={endpoint.protocol} onChange={event => { const protocol = event.target.value as UpstreamProtocol; updateEndpoint({ protocol, protocol_profile_id: `profile/custom/${protocol}`, protocol_profile_revision: endpoint.protocol_profile_revision + 1 }); }}><option value="chat_completions">OpenAI Chat Completions</option><option value="responses">OpenAI Responses</option><option value="messages">Anthropic Messages</option></select></label>- <label className="field"><span className="field-label">Base URL</span><input className="input" inputMode="url" value={endpoint.base_url} onChange={event => updateEndpoint({ base_url: event.target.value })} /></label>+ <label className="field"><span className="field-label">Base URL</span><input className="input" inputMode="url" value={endpoint.base_url} onChange={event => updateEndpoint({ base_url: event.target.value })} /><PlaintextHttpWarning baseUrl={endpoint.base_url} zh={zh} /></label><label className="field"><span className="field-label">{zh ? '请求路径' : 'Request path'}</span><input className="input" value={endpoint.request_path_override ?? ''} onChange={event => updateEndpoint({ request_path_override: event.target.value || null })} /></label><label className="field"><span className="field-label">{zh ? '认证方式' : 'Authentication'}</span><select className="select" value={endpoint.authentication.kind} onChange={event => updateEndpoint({ authentication: event.target.value === 'api_key_header' ? { kind: 'api_key_header', header: 'x-api-key' } : event.target.value === 'none' ? { kind: 'none' } : { kind: 'bearer' } })}><option value="none">{zh ? '无认证' : 'None'}</option><option value="bearer">Bearer Token</option><option value="api_key_header">{zh ? '自定义 Header' : 'Custom header'}</option></select></label>{endpoint.authentication.kind === 'api_key_header' && <label className="field"><span className="field-label">Header</span><input className="input" value={endpoint.authentication.header} onChange={event => updateEndpoint({ authentication: { kind: 'api_key_header', header: event.target.value } })} /></label>}diff --git a/apps/desktop/src/features/model-connections/README.md b/apps/desktop/src/features/model-connections/README.mdindex 42e9d6cd..a48b03d0 100644--- a/apps/desktop/src/features/model-connections/README.md+++ b/apps/desktop/src/features/model-connections/README.md@@ -13,6 +13,13 @@ The password field is uncontrolled. Its value is passed only to `registerProtectEach edit has a client `edit_revision`; every check has a unique `check_id`. A result is rendered only when those values, the candidate lineage, and both returned copies of `input_digest` agree. Save uses the backend `candidate_revision`, maps the enable checkbox to `save_ready`, and uses `save_disabled` for a disabled draft. `complete` facts still pass through backend Preview and Apply authorization.+Explicit Custom API endpoints support HTTP and HTTPS for local, LAN and remote+services. Each HTTP field shows a plaintext notice and recommends HTTPS without a+confirmation gate. A missing directory path permits manual model check/save without+network probing. Closed target-validation reasons survive the daemon error envelope+as `message_key` values and become localized correction text; raw exception strings+and provider bodies never become UI messages.+The first inventory check selects no models. A tool check on an explicitly selectedmodel preserves existing choices by exact upstream model identity within the samecandidate and edit revision, using fresh selectable model references. Newlydiff --git a/apps/desktop/src/features/model-connections/form-support.tsx b/apps/desktop/src/features/model-connections/form-support.tsxindex 1306b93f..6e5cd250 100644--- a/apps/desktop/src/features/model-connections/form-support.tsx+++ b/apps/desktop/src/features/model-connections/form-support.tsx@@ -10,6 +10,18 @@ export { safeConnectionErrorCode } from './copy';export { blankModel } from './state';export function connectionErrorMessage(code: string, zh: boolean): string {+ if (code === 'model_connections.invalid_url') return zh+ ? '连接地址无效。请使用完整的 http:// 或 https:// 地址;API Key 请单独填写,不要放在地址中。'+ : 'Enter a complete http:// or https:// endpoint. Enter the API key separately, not in the URL.';+ if (code === 'model_connections.unsafe_path') return zh+ ? '请求路径或模型目录路径无效。请使用以 / 开头的路径,移除查询参数、编码字符和相对路径片段。'+ : 'Check the endpoint, request and model directory paths. Start paths with / and remove queries, encoded characters and relative path segments.';+ if (code === 'model_connections.unsafe_authentication_header') return zh+ ? '认证 Header 无效或不允许使用。请选择 Bearer,或填写允许使用的 Header 名称,例如 x-api-key。'+ : 'The authentication header is invalid or reserved. Select Bearer or use an allowed header name, such as x-api-key.';+ if (code === 'model_connections.unsafe_protocol_header') return zh+ ? '协议 Header 配置无效或冲突。请检查所选协议的 Header,避免覆盖认证或连接控制 Header。'+ : 'Check the selected protocol headers. Do not override authentication or connection control headers.';if (['REVISION_CONFLICT', 'CHANGE_PREVIEW_STALE', 'application.error.revision_conflict', 'application.error.change_preview_stale'].includes(code)) return zh ? '配置在保存前发生变化,尚未提交。输入已保留,请再次保存。' : 'Configuration changed before submission. Your input is preserved; save again.';if (code === 'MODEL_TOOL_CALL_NOT_VERIFIED') return zh ? '该模型未返回有效工具调用,当前不能作为 Agent 工具模型使用。请更换支持工具调用的模型,或修复服务后重新验证。' : 'The model did not return a valid tool call and cannot currently be used as an Agent tool model. Choose a tool-capable model or repair the service and verify again.';if (code === 'MODEL_INFERENCE_FAILED') return zh@@ -68,6 +80,13 @@ export function connectionErrorMessage(code: string, zh: boolean): string {: 'The operation could not complete. Try again; your entries are retained.';}+export function PlaintextHttpWarning({ baseUrl, zh }: { baseUrl: string; zh: boolean }) {+ if (!/^http:\/\//i.test(baseUrl.trim())) return null;+ return <span className="field-help" role="note" data-plaintext-http-warning>{zh+ ? 'HTTP 使用明文传输,API Key 及请求和响应内容可能被读取。建议优先使用 HTTPS。'+ : 'HTTP sends API keys and request and response content in plaintext. Use HTTPS when available.'}</span>;+}+export function registeredConnectionLabel(option: ComputeConnectionOption | null, zh: boolean) {return {title: option?.display_name ?? (zh ? '受支持的 API' : 'Supported API'),diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex ff472433..ad438872 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -82,6 +82,13 @@ Session quality names come from the exact retained execution request (same sessi## Run levels+Custom API transport and error presentation use the production form in+`node tests/v3/visual/connection-flow.mjs /path/to/evidence`. It exercises manual+HTTP save without a directory, closed backend error reasons with retained input,+and plaintext notices in zh/en, light/dark, at 1200×813 and 755×600. Browser IPC is+synthetic; `real_process_custom_http_save_recheck_and_validation_errors` in the+daemon publication tests separately proves actual control/save/restart behavior.+From `apps/desktop`, with the repository's Node 24 and installed dependencies:```shdiff --git a/apps/desktop/tests/v3/browser/connection-flow.tsx b/apps/desktop/tests/v3/browser/connection-flow.tsxindex 3eda5d65..ac3c4d71 100644--- a/apps/desktop/tests/v3/browser/connection-flow.tsx+++ b/apps/desktop/tests/v3/browser/connection-flow.tsx@@ -26,6 +26,9 @@ function Harness() {const invoke = async (command: string, payload?: Record<string, unknown>) => mockProductInvoke(command, payload, kind === 'custom' && !appendTo ? 'unknown_model' : 'ready') as any;const check = async (command: string, request: any) => {if (params.get('hold_check')) await new Promise<void>(resolve => pendingChecks.push(resolve));+ if (params.has('check_error')) throw { source: 'backend', envelope: {+ error: { code: 'INVALID_ARGUMENTS', message_key: params.get('check_error') },+ } };const result = await invoke(command, { request });const ref = request.input_candidate?.candidate_ref ?? 'candidate/no-auth';return { ...result, candidate: { ...result.candidate, candidate: { candidate_ref: ref, candidate_revision: 2 },diff --git a/apps/desktop/tests/v3/visual/connection-flow-active.mjs b/apps/desktop/tests/v3/visual/connection-flow-active.mjsindex fec69a5c..18dbc36f 100644--- a/apps/desktop/tests/v3/visual/connection-flow-active.mjs+++ b/apps/desktop/tests/v3/visual/connection-flow-active.mjs@@ -7,7 +7,12 @@ const [port, base, output] = process.argv.slice(2);const client = await connectPage(Number(port));const keepAlive = setInterval(() => {}, 1000);const results = [];+const settled = async () => {+ await evaluate(client, `Promise.all(document.getAnimations().filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => undefined))).then(() => true)`);+ await evaluate(client, 'new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))))');+};const screenshot = async name => {+ await settled();const shot = await client.send('Page.captureScreenshot', { format: 'png' });await writeFile(path.join(output, `${name}.png`), Buffer.from(shot.data, 'base64'));};@@ -19,6 +24,7 @@ const open = async (query = '', viewport = { width: 1200, height: 813 }, page =await waitFor(client, `location.href === ${JSON.stringify(url)} && document.readyState === 'complete'`);await evaluate(client, 'document.fonts.ready.then(() => true)');await waitFor(client, `document.querySelector('.connection-flow') && !document.querySelector('.oc-spinner')`);+ await settled();};const click = async (selector, text = '') => {const expression = `Array.from(document.querySelectorAll(${JSON.stringify(selector)})).find(item => item.getClientRects().length && !item.disabled && (!${JSON.stringify(text)} || item.textContent.trim() === ${JSON.stringify(text)} || item.querySelector('strong')?.textContent === ${JSON.stringify(text)}))`;@@ -51,7 +57,7 @@ try {await open();await waitFor(client, `Array.from(document.querySelectorAll('.connection-provider-card img')).every(image=>image.complete&&image.naturalWidth>0)`);const facts = await evaluate(client, `({count:document.querySelectorAll('.connection-provider-card').length,intro:document.querySelector('.connection-directory-intro').textContent,logos:Array.from(document.querySelectorAll('.connection-provider-card img')).every(image=>image.complete&&image.naturalWidth>0)})`);- assert.equal(facts.count, 13); assert.match(facts.intro, /13.*18/); assert.ok(facts.logos);+ assert.equal(facts.count, 13); assert.match(facts.intro, /13.*19/); assert.ok(facts.logos);await screenshot('catalog');await field('搜索供应商或产品', 'Coding Plan');await waitFor(client, `document.querySelectorAll('.connection-provider-card').length === 4`);@@ -116,7 +122,7 @@ try {});await run('custom no-auth and manual model declarations remain usable', async () => {await open('kind=custom');- await field('连接名称', '本地模型'); await field('Base URL', 'http://127.0.0.1:51234/v1');+ await field('连接名称', '团队 HTTP 模型'); await field('Base URL', 'http://192.0.2.10:51234/v1');await click('summary', '高级设置展开'); await field('认证方式', 'none');await waitFor(client, `!document.querySelector('#mc-connection-form input[type=password]')`);await click('#mc-connection-form button', '手工维护模型');@@ -127,7 +133,60 @@ try {assert.equal(trace.registered.length, 0); assert.equal(trace.saves.length, 1);assert.equal(trace.checks[0].draft.authentication.kind, 'none');assert.equal(trace.checks[0].draft.models[0].upstream_model_id, 'local-test-model');- assert.equal(trace.checks[0].draft.display_name, '本地模型');+ assert.equal(trace.checks[0].draft.display_name, '团队 HTTP 模型');+ assert.equal(trace.checks[0].draft.base_url, 'http://192.0.2.10:51234/v1');+ assert.equal(trace.checks[0].draft.inventory_path_override, null);+ });+ await run('explicit HTTP explains plaintext without blocking the configured endpoint', async () => {+ for (const lang of ['zh', 'en']) for (const theme of ['light', 'dark']) for (const viewport of [{ width: 1200, height: 813 }, { width: 755, height: 600 }]) {+ await open(`kind=custom&lang=${lang}&theme=${theme}`, viewport);+ await field('Base URL', 'http://gateway.invalid:8123/v1');+ await waitFor(client, 'Boolean(document.querySelector("[data-plaintext-http-warning]"))');+ const warning = await evaluate(client, `(() => {+ const note = document.querySelector('[data-plaintext-http-warning]');+ note.scrollIntoView({ block: 'center', behavior: 'instant' });+ const rect = note.getBoundingClientRect(); const footer = document.querySelector('.modal-foot').getBoundingClientRect();+ const header = document.querySelector('.modal-head').getBoundingClientRect();+ return { text: note.textContent, left: rect.left, right: rect.right, height: rect.height,+ fontSize: parseFloat(getComputedStyle(note).fontSize),+ top: rect.top, bottom: rect.bottom, headerBottom: header.bottom, footerTop: footer.top,+ footerBottom: footer.bottom, overflow: document.documentElement.scrollWidth > innerWidth + 1 };+ })()`);+ assert.match(warning.text, /API Key|API keys/);+ assert.match(warning.text, /明文|plaintext/);+ assert.match(warning.text, /HTTPS/);+ assert.ok(warning.left >= 0 && warning.right <= viewport.width && warning.height >= warning.fontSize && !warning.overflow, JSON.stringify(warning));+ assert.ok(warning.top >= warning.headerBottom && warning.bottom <= warning.footerTop, JSON.stringify(warning));+ assert.ok(warning.footerBottom <= viewport.height + 1, JSON.stringify(warning));+ await screenshot(`http-warning-${lang}-${theme}-${viewport.width}`);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.checks.length'), 0);+ await field('Base URL', 'https://gateway.invalid/v1');+ await waitFor(client, '!document.querySelector("[data-plaintext-http-warning]")');+ }+ });+ await run('safe backend target reasons become actionable localized errors and retain input', async () => {+ for (const lang of ['zh', 'en']) for (const [reason, correction] of [+ ['invalid_url', /http:\/\/.*https:\/\//],+ ['unsafe_path', /路径|paths/],+ ['unsafe_authentication_header', /Bearer.*x-api-key/],+ ['unsafe_protocol_header', /协议.*Header|protocol headers/],+ ]) {+ const key = `model_connections.${reason}`;+ await open(`kind=custom&lang=${lang}&check_error=${key}`, { width: 755, height: 600 });+ await field(lang === 'zh' ? '连接名称' : 'Connection name', 'HTTP fixture');+ await field('Base URL', 'http://gateway.invalid:8123/v1');+ await click('summary', lang === 'zh' ? '高级设置展开' : 'Advanced settingsExpand');+ await field(lang === 'zh' ? '认证方式' : 'Authentication', 'none');+ await click('.modal-foot button', lang === 'zh' ? '检查并继续' : 'Check and continue');+ await waitFor(client, `Boolean(document.querySelector('[data-error-code="${key}"]'))`);+ const error = await evaluate(client, `document.querySelector('[data-error-code="${key}"]').textContent`);+ assert.match(error, correction);+ assert.ok(!/暂时无法完成操作|The operation could not complete/.test(error), error);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.saves.length'), 0);+ const retained = await evaluate(client, `Array.from(document.querySelectorAll('.field')).find(item => item.querySelector('.field-label')?.textContent === 'Base URL')?.querySelector('input').value`);+ assert.equal(retained, 'http://gateway.invalid:8123/v1');+ await screenshot(`target-error-${lang}-${reason}`);+ }});await run('cancel preserves the credential and ignores late check results', async () => {await open('hold_check=1'); await provider('Anthropic按量付费');diff --git a/crates/application/src/compute_management/dispatch.rs b/crates/application/src/compute_management/dispatch.rsindex deb69e91..e57163ad 100644--- a/crates/application/src/compute_management/dispatch.rs+++ b/crates/application/src/compute_management/dispatch.rs@@ -493,7 +493,13 @@ fn result<T: serde::Serialize>(fn map_error(error: ComputeManagementControlError) -> ErrorCode {match error {- ComputeManagementControlError::Invalid => ErrorCode::InvalidArguments,+ ComputeManagementControlError::Invalid+ | ComputeManagementControlError::InvalidModelConnectionUrl+ | ComputeManagementControlError::UnsafeModelConnectionPath+ | ComputeManagementControlError::UnsafeModelConnectionAuthenticationHeader+ | ComputeManagementControlError::UnsafeModelConnectionProtocolHeader => {+ ErrorCode::InvalidArguments+ }ComputeManagementControlError::NotFound => ErrorCode::ResourceNotFound,ComputeManagementControlError::Conflict => ErrorCode::RevisionConflict,ComputeManagementControlError::RegisteredOptionUnavailable => ErrorCode::ResourceNotFound,@@ -517,6 +523,14 @@ fn failed_control() -> MachineEnvelopeV2<Value> {let mut failure = ErrorV1::new(map_error(error));failure.message_key = match error {+ ComputeManagementControlError::InvalidModelConnectionUrl => "model_connections.invalid_url",+ ComputeManagementControlError::UnsafeModelConnectionPath => "model_connections.unsafe_path",+ ComputeManagementControlError::UnsafeModelConnectionAuthenticationHeader => {+ "model_connections.unsafe_authentication_header"+ }+ ComputeManagementControlError::UnsafeModelConnectionProtocolHeader => {+ "model_connections.unsafe_protocol_header"+ }ComputeManagementControlError::RegisteredOptionUnavailable => {"compute.registered_option_unavailable"}@@ -547,6 +561,39 @@ fn failed(code: ErrorCode, request_id: String) -> MachineEnvelopeV2<Value> {mod tests {use super::*;+ #[test]+ fn connection_target_errors_keep_the_released_machine_code_and_specific_safe_reason() {+ for (error, message_key) in [+ (+ ComputeManagementControlError::InvalidModelConnectionUrl,+ "model_connections.invalid_url",+ ),+ (+ ComputeManagementControlError::UnsafeModelConnectionPath,+ "model_connections.unsafe_path",+ ),+ (+ ComputeManagementControlError::UnsafeModelConnectionAuthenticationHeader,+ "model_connections.unsafe_authentication_header",+ ),+ (+ ComputeManagementControlError::UnsafeModelConnectionProtocolHeader,+ "model_connections.unsafe_protocol_header",+ ),+ ] {+ let envelope =+ serde_json::to_value(failed_control(error, "check/test".into())).unwrap();+ assert_eq!(envelope["error"]["code"], "INVALID_ARGUMENTS");+ assert_eq!(envelope["error"]["message_key"], message_key);+ assert_eq!(envelope["request_id"], "check/test");+ assert_eq!(+ envelope["error"]["details_schema"],+ "hiroute.error-details/none-v1"+ );+ assert_eq!(envelope["error"]["retryable"], false);+ }+ }+#[test]fn registered_business_failures_keep_closed_message_keys() {for (error, code, key) in [diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rsindex d4fa3132..1d8bcc9c 100644--- a/crates/application/src/control/mod.rs+++ b/crates/application/src/control/mod.rs@@ -342,6 +342,10 @@ pub trait ComputeFactsPort: Send + Sync {#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub enum ComputeManagementControlError {Invalid,+ InvalidModelConnectionUrl,+ UnsafeModelConnectionPath,+ UnsafeModelConnectionAuthenticationHeader,+ UnsafeModelConnectionProtocolHeader,NotFound,Conflict,RegisteredOptionUnavailable,diff --git a/crates/application/src/control_plane/mod.rs b/crates/application/src/control_plane/mod.rsindex c72f923b..0a63b61f 100644--- a/crates/application/src/control_plane/mod.rs+++ b/crates/application/src/control_plane/mod.rs@@ -463,7 +463,11 @@ fn management_port(fn map_management_error(error: super::control::ComputeManagementControlError) -> ErrorCode {use super::control::ComputeManagementControlError as E;match error {- E::Invalid => ErrorCode::InvalidArguments,+ E::Invalid+ | E::InvalidModelConnectionUrl+ | E::UnsafeModelConnectionPath+ | E::UnsafeModelConnectionAuthenticationHeader+ | E::UnsafeModelConnectionProtocolHeader => ErrorCode::InvalidArguments,E::NotFound | E::RegisteredOptionUnavailable | E::DiscoveryUnavailable => {ErrorCode::ResourceNotFound}diff --git a/crates/daemon/src/control/runtime/model_connections.rs b/crates/daemon/src/control/runtime/model_connections.rsindex 54e7026b..7ce56243 100644--- a/crates/daemon/src/control/runtime/model_connections.rs+++ b/crates/daemon/src/control/runtime/model_connections.rs@@ -33,6 +33,7 @@ use hiroute_integrations::{use super::LocalControlAdapter;mod discovered;+mod error;mod hermes_points;mod key_inputs;mod key_masks;@@ -44,6 +45,8 @@ mod registered;mod saved;mod saved_prefill;+use error::{map_check_error, map_target_error};+pub(super) fn registered_source_matches_current_option(source: &hiroute_domain::ComputeManagementSourceV2,resolved: &hiroute_domain::ResolvedConnectionOptionV1,@@ -372,7 +375,7 @@ impl ComputeManagementControlPort for LocalControlAdapter {};self.model_connections.check(draft, credential, &cancellation)- .map_err(|_| ComputeManagementControlError::Invalid)+ .map_err(map_check_error)})();self.model_connection_cancellations.lock()@@ -433,7 +436,7 @@ impl ComputeManagementControlPort for LocalControlAdapter {},&cancellation,)- .map_err(|_| ComputeManagementControlError::Invalid)+ .map_err(map_check_error)})();self.model_connection_cancellations.lock()@@ -483,7 +486,7 @@ impl ComputeManagementControlPort for LocalControlAdapter {};self.model_connections.check(prepared.draft, credential, &cancellation)- .map_err(|_| ComputeManagementControlError::Invalid)+ .map_err(map_check_error)})();self.model_connection_cancellations.lock()@@ -755,7 +758,7 @@ fn trusted_draft(authentication: &endpoint.authentication,},)- .map_err(|_| ComputeManagementControlError::Invalid)?;+ .map_err(map_target_error)?;let target = normalized.candidate_target;Ok(hiroute_domain::ComputeNativeEndpointV3 {target: hiroute_domain::ComputeManagementTargetV2 {diff --git a/crates/daemon/src/control/runtime/model_connections/error.rs b/crates/daemon/src/control/runtime/model_connections/error.rsnew file mode 100644index 00000000..737be391--- /dev/null+++ b/crates/daemon/src/control/runtime/model_connections/error.rs@@ -0,0 +1,34 @@+//! Closed connection-check failures; no URL, credential or provider text crosses control.++use hiroute_application::control::ComputeManagementControlError;+use hiroute_integrations::{ModelConnectionTargetError, NativeModelConnectionErrorV1};++pub(super) fn map_check_error(+ error: NativeModelConnectionErrorV1,+) -> ComputeManagementControlError {+ match error {+ NativeModelConnectionErrorV1::Target(error) => map_target_error(error),+ NativeModelConnectionErrorV1::InvalidDraft => ComputeManagementControlError::Invalid,+ NativeModelConnectionErrorV1::Candidate(error) => super::map_port(error),+ NativeModelConnectionErrorV1::RandomUnavailable => {+ ComputeManagementControlError::Unavailable+ }+ }+}++pub(super) fn map_target_error(error: ModelConnectionTargetError) -> ComputeManagementControlError {+ match error {+ ModelConnectionTargetError::InvalidUrl => {+ ComputeManagementControlError::InvalidModelConnectionUrl+ }+ ModelConnectionTargetError::UnsafePath => {+ ComputeManagementControlError::UnsafeModelConnectionPath+ }+ ModelConnectionTargetError::UnsafeAuthenticationHeader => {+ ComputeManagementControlError::UnsafeModelConnectionAuthenticationHeader+ }+ ModelConnectionTargetError::UnsafeProtocolHeader => {+ ComputeManagementControlError::UnsafeModelConnectionProtocolHeader+ }+ }+}diff --git a/crates/daemon/tests/publication_process.rs b/crates/daemon/tests/publication_process.rsindex 5085912e..f42162a7 100644--- a/crates/daemon/tests/publication_process.rs+++ b/crates/daemon/tests/publication_process.rs@@ -72,6 +72,11 @@ fn real_process_native_model_save_publishes_and_reaches_gateway() {run_script("model_connections_product.py");}+#[test]+fn real_process_custom_http_save_recheck_and_validation_errors() {+ run_script("custom_http_product.py");+}+/// Branch execution identity must not replace current managed source membership.#[test]fn real_process_native_branch_credentials_preserve_source_and_key_permissions() {diff --git a/crates/daemon/tests/support/custom_http_product.py b/crates/daemon/tests/support/custom_http_product.pynew file mode 100644index 00000000..b228400b--- /dev/null+++ b/crates/daemon/tests/support/custom_http_product.py@@ -0,0 +1,104 @@+"""Explicit HTTP admission and safe validation errors through real Local Control/save/restart."""+import hashlib+import json+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace+from urllib.parse import urlsplit++from model_connections_product import (+ control, desktop_grant, recheck_saved_native_source, save_native_source,+)+from publication_product import Product, encoded+++def check_invalid(product, label, **changes):+ draft = {+ 'candidate_ref': None, 'lineage_ref': 'lineage/http/' + label,+ 'display_name': 'HTTP validation fixture', 'existing_source_id': None,+ 'expected_source_revision': None, 'edit_revision': 1,+ 'check_id': 'check/http/' + label, 'base_url': 'http://gateway.invalid/v1',+ 'base_kind': 'api_root', 'request_path_override': None,+ 'inventory_path_override': None, 'protocol': 'responses',+ 'protocol_profile_id': 'profile/custom/responses', 'protocol_profile_revision': 1,+ 'authentication': {'kind': 'none'}, 'configuration_revision': 1,+ 'inference_model_id': None, 'models': [], 'additional_endpoints': [],+ **changes,+ }+ request = {'draft': draft}+ revisions = control(product, 'GetClientServiceStatus', {})['data']['revisions']+ grant = desktop_grant(product, 'CheckNativeModelConnection',+ 'sha256:' + hashlib.sha256(encoded(request)).hexdigest(),+ revisions, 'http-' + label)+ envelope = control(product, 'CheckNativeModelConnection', request, grant,+ expected_error='INVALID_ARGUMENTS')+ assert envelope.get('data') is None, envelope+ assert 'must-not-leak' not in json.dumps(envelope), envelope+ return envelope['error']['message_key']+++def main():+ repository = Path(sys.argv[1]).resolve()+ revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repository, text=True).strip()+ if len(sys.argv) > 2:+ assert revision == sys.argv[2], (revision, sys.argv[2])+ product = Product(repository)+ saved_sources = []+ # No directory or inference operation is requested: these synthetic addresses+ # must be admitted and saved without DNS, network access or provider credentials.+ endpoints = [+ 'http://192.0.2.10:8123/v1', 'http://192.168.1.10:8123/v1',+ 'http://gateway.invalid:8123/v1', 'http://localhost:8123/v1',+ 'http://127.0.0.1:8123/v1', 'http://[::1]:8123/v1',+ 'http://[2001:db8::10]:8123/v1', 'https://gateway.invalid/v1',+ ]+ try:+ product.start()+ for index, endpoint in enumerate(endpoints):+ saved = save_native_source(product, SimpleNamespace(base_url=endpoint),+ token='synthetic-http-key-' + str(index) if index % 2 else None,+ variant='http-' + str(index), cli_input=True,+ source_display_name='HTTP fixture ' + str(index),+ inventory_path=None)+ saved_sources.append((saved, endpoint))+ for label, changes, expected in [+ ('url', {'base_url': 'http://user:[email protected]/v1'},+ 'model_connections.invalid_url'),+ ('scheme', {'base_url': 'ftp://gateway.invalid/v1'}, 'model_connections.invalid_url'),+ ('path', {'request_path_override': '/v1/../must-not-leak'}, 'model_connections.unsafe_path'),+ ('directory', {'inventory_path_override': '/v1/models?key=must-not-leak'},+ 'model_connections.unsafe_path'),+ ('header', {'authentication': {'kind': 'api_key_header', 'header': 'Host'}},+ 'model_connections.unsafe_authentication_header'),+ ('extra-url', {'additional_endpoints': [{+ 'base_url': 'http://user:[email protected]/v1', 'base_kind': 'api_root',+ 'request_path_override': None, 'inventory_path_override': None,+ 'protocol': 'messages', 'protocol_profile_id': 'profile/custom/messages',+ 'protocol_profile_revision': 1, 'authentication': {'kind': 'none'},+ }]}, 'model_connections.invalid_url'),+ ]:+ assert check_invalid(product, label, **changes) == expected, label+ product.stop()+ product.start()+ sources = control(product, 'ListCompute', {})['data']['sources']+ for index, (saved, endpoint) in enumerate(saved_sources):+ source = next(item for item in sources if item['source_id'] == saved['source_id'])+ url = urlsplit(endpoint)+ assert source['target']['scheme'] == url.scheme, source+ assert source['target']['authority'] == url.hostname, source+ assert source['target']['port'] == (url.port or 443), source+ assert source.get('inventory_path') is None, source+ checked = recheck_saved_native_source(product, saved, 2, 'http-' + str(index),+ directory='not_run')+ assert checked['target'] == source['target'], (checked, source)+ assert checked['inference'] == 'not_run', checked+ print(json.dumps({'scenario': 'custom-http-save-recheck-and-errors', 'state': 'green',+ 'revision': revision, 'saved_and_rechecked': len(saved_sources),+ 'validation_errors': 6}), flush=True)+ finally:+ product.close()+++if __name__ == '__main__':+ main()diff --git a/crates/daemon/tests/support/model_connections_product.py b/crates/daemon/tests/support/model_connections_product.pyindex 687fc1fc..71f5168d 100644--- a/crates/daemon/tests/support/model_connections_product.py+++ b/crates/daemon/tests/support/model_connections_product.py@@ -23,7 +23,7 @@ V2 = {'major': 2, 'minor': 0}class NativeUpstream:- def __init__(self):+ def __init__(self, base_host=None):self.requests = []self.rejected_token = Noneself.reject_reasoning_history = False@@ -50,6 +50,7 @@ class NativeUpstream:owner.requests.append({'method': self.command,'path': self.path,+ 'host': self.headers.get('Host'),'authorization': self.headers.get('Authorization'),'api_key': self.headers.get('x-api-key'),'body': body,@@ -97,7 +98,8 @@ class NativeUpstream:self.server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)self.thread.start()- self.base_url = 'http://%s:%d/v1' % self.server.server_address+ address, port = self.server.server_address+ self.base_url = 'http://%s:%d/v1' % (base_host or address, port)def close(self):self.server.shutdown()@@ -169,7 +171,8 @@ def save_native_source(product, upstream, token=None, unknown=False,protocol='responses', upstream_model_id=MODEL, variant='',context_tokens=32768, cli_input=False,source_display_name='Product Native API',- model_display_name='Manual Native Model'):+ model_display_name='Manual Native Model',+ inventory_path='/v1/models'):status = control(product, 'GetClientServiceStatus', {})['data']suffix = ('-unknown' if unknown else '') + ('-' + variant if variant else '')candidate_ref = 'candidate/native/product' + suffix@@ -200,7 +203,7 @@ def save_native_source(product, upstream, token=None, unknown=False,'base_url': upstream.base_url,'base_kind': 'api_root','request_path_override': None,- 'inventory_path_override': '/v1/models',+ 'inventory_path_override': inventory_path,'protocol': protocol,'protocol_profile_id': 'profile/custom/' + protocol,'protocol_profile_revision': 1,@@ -246,8 +249,11 @@ def save_native_source(product, upstream, token=None, unknown=False,status['revisions'], 'native-check' + suffix)checked = control(product, 'CheckNativeModelConnection', check_request, grant)['data']- assert checked['directory'] == ('not_run' if unknown else 'unavailable'), checked+ assert checked['directory'] == ('not_run' if unknown or inventory_path is None else 'unavailable'), checkedassert checked['inference'] == 'not_run', checked+ if inventory_path is None:+ assert checked['reachability'] != 'reachable', checked+ assert checked['authentication'] != 'verified', checkedmanual = next(model for model in checked['candidate']['models']if model['upstream_model_id'] == upstream_model_id)assert manual['selectable'] and manual['membership'] == 'user_declared', manual@@ -288,7 +294,8 @@ def save_compute_candidate(product, candidate, model_ref, idempotency_key):}-def recheck_saved_native_source(product, saved, edit_revision, suffix, unknown=False):+def recheck_saved_native_source(product, saved, edit_revision, suffix, unknown=False,+ directory='unavailable'):request = {'source_id': saved['source_id'],'expected_source_revision': saved['source_revision'],@@ -302,7 +309,7 @@ def recheck_saved_native_source(product, saved, edit_revision, suffix, unknown=Fproduct, 'CheckSavedModelConnection', digest, revisions,'saved-native-' + suffix)checked = control(product, 'CheckSavedModelConnection', request, grant)['data']- assert checked['directory'] == ('not_run' if unknown else 'unavailable'), checked+ assert checked['directory'] == ('not_run' if unknown else directory), checkedif unknown:assert checked['candidate']['models'][0]['fact_basis'] == 'unknown', checkedassert checked['candidate']['candidate']['candidate_ref'] == saved['candidate_ref'], checked@@ -666,7 +673,7 @@ def run(repository, expected_sha=None):if expected_sha is not None:assert actual_sha == expected_sha, (actual_sha, expected_sha)product = Product(repository)- upstream = NativeUpstream()+ upstream = NativeUpstream(base_host='localhost')product.install_codex_fixture(MODEL, 'medium', upstream.base_url, NATIVE_TOKEN)started_ms = int(time.time() * 1000)@@ -701,6 +708,8 @@ def run(repository, expected_sha=None):assert_session_record(product, started_ms, saved['binding_id'])with upstream.lock:requests = list(upstream.requests)+ expected_host = 'localhost:%d' % upstream.server.server_address[1]+ assert all(request['host'] == expected_host for request in requests), requestsassert [request['path'] for request in requests] == ['/v1/models', '/v1/models', '/v1/responses', '/v1/responses','/v1/responses', '/v1/models'], requestsdiff --git a/crates/domain/src/compute/management/mod.rs b/crates/domain/src/compute/management/mod.rsindex 7e969f8a..9a53589d 100644--- a/crates/domain/src/compute/management/mod.rs+++ b/crates/domain/src/compute/management/mod.rs@@ -211,15 +211,7 @@ pub struct ComputeManagementTargetV2 {impl ComputeManagementTargetV2 {pub fn validate(&self) -> Result<(), ComputeManagementErrorV2> {- let https = self.scheme.eq_ignore_ascii_case("https");- let loopback_http = self.scheme.eq_ignore_ascii_case("http")- && self- .authority- .trim_start_matches('[')- .trim_end_matches(']')- .parse::<std::net::IpAddr>()- .is_ok_and(|address| address.is_loopback());- if (!https && !loopback_http)+ if (!self.scheme.eq_ignore_ascii_case("https") && !self.scheme.eq_ignore_ascii_case("http"))|| self.port == 0|| !valid_authority(&self.authority)|| !valid_request_path(&self.request_path)diff --git a/crates/domain/src/compute/management/tests.rs b/crates/domain/src/compute/management/tests.rsindex 0ec3f66b..14e22f7b 100644--- a/crates/domain/src/compute/management/tests.rs+++ b/crates/domain/src/compute/management/tests.rs@@ -181,15 +181,66 @@ fn custom_header_rejects_reserved_or_injected_names() {}#[test]-fn only_https_or_loopback_http_targets_are_accepted() {+fn explicit_http_and_https_targets_survive_source_serialization() {+ for scheme in ["http", "https"] {+ for authority in [+ "192.0.2.10",+ "192.168.1.10",+ "gateway.invalid",+ "localhost",+ "127.0.0.1",+ "::1",+ "2001:db8::10",+ ] {+ let mut value = source(GatewayAuthenticationSemanticsV1::None);+ value.target.scheme = scheme.into();+ value.target.authority = authority.into();+ value.target.port = 8123;+ assert_eq!(value.validate(), Ok(()));+ let reopened: ComputeManagementSourceV2 =+ serde_json::from_slice(&serde_json::to_vec(&value).unwrap()).unwrap();+ assert_eq!(reopened, value);+ assert_eq!(reopened.validate(), Ok(()));+ }+ }+}++#[test]+fn explicit_http_retains_target_and_credential_scope_guards() {let mut value = source(GatewayAuthenticationSemanticsV1::None);+ for scheme in ["ftp", "file", "ws", ""] {+ value.target.scheme = scheme.into();+ assert_eq!(+ value.validate(),+ Err(ComputeManagementErrorV2::InvalidTarget)+ );+ }value.target.scheme = "http".into();+ for authority in [+ "",+ "user:[email protected]",+ "gateway.invalid/path",+ "gateway.invalid?key=secret",+ ] {+ value.target.authority = authority.into();+ assert_eq!(+ value.validate(),+ Err(ComputeManagementErrorV2::InvalidTarget)+ );+ }+ value.target.authority = "gateway.invalid".into();+ value.target.port = 0;assert_eq!(value.validate(),Err(ComputeManagementErrorV2::InvalidTarget));- value.target.authority = "127.0.0.1".into();- assert_eq!(value.validate(), Ok(()));++ // Expanding supported transport must not give a saved HTTPS key authority+ // over a different HTTP destination. The save planner must bind it afresh.+ let mut authenticated = source(GatewayAuthenticationSemanticsV1::Bearer);+ authenticated.target.scheme = "http".into();+ assert!(authenticated.target.validate().is_ok());+ assert!(authenticated.validate().is_err());}#[test]diff --git a/crates/domain/src/routing/gateway_execution.rs b/crates/domain/src/routing/gateway_execution.rsindex bda43dfd..33f614ee 100644--- a/crates/domain/src/routing/gateway_execution.rs+++ b/crates/domain/src/routing/gateway_execution.rs@@ -104,13 +104,16 @@ fn valid_user_configured_native_endpoint(value: &str) -> bool {if valid_executable_endpoint(value) || valid_numeric_loopback_http(value) {return true;}- let Some(rest) = value.strip_prefix("https://") else {+ let Some(rest) = value+ .strip_prefix("https://")+ .or_else(|| value.strip_prefix("http://"))+ else {return false;};let Some((authority, path)) = rest.split_once('/') else {return false;};- valid_user_configured_https_authority(authority)+ valid_user_configured_authority(authority)&& !path.is_empty()&& !path.starts_with('/')&& !path.contains(['?', '#', '\\', '%'])@@ -121,7 +124,7 @@ fn valid_user_configured_native_endpoint(value: &str) -> bool {})}-fn valid_user_configured_https_authority(value: &str) -> bool {+fn valid_user_configured_authority(value: &str) -> bool {if value.is_empty()|| value.len() > 253|| value.contains(['@', '/', '?', '#'])@@ -833,6 +836,62 @@ mod tests {use super::*;use crate::ReasoningRenderModeV1;+ #[test]+ fn explicit_http_gateway_targets_keep_exact_user_and_connector_scopes() {+ for uri in [+ "http://192.0.2.10/v1/responses",+ "http://192.168.1.10:8123/v1/responses",+ "http://gateway.invalid:8123/v1/responses",+ "http://localhost:8123/v1/responses",+ "http://127.0.0.1:8123/v1/responses",+ "http://[::1]:8123/v1/responses",+ "http://[2001:db8::10]:8123/v1/responses",+ "https://gateway.invalid/v1/responses",+ ] {+ let target = GatewayOperationalTargetV1::UserConfiguredNative { uri: uri.into() };+ assert!(+ target.validate_for(ConnectorRuntimeKind::BuiltinNative, uri),+ "{uri}"+ );+ assert!(!target.validate_for(ConnectorRuntimeKind::CpaBridge, uri));+ assert!(!target.validate_for(+ ConnectorRuntimeKind::BuiltinNative,+ "http://other.invalid/v1/responses"+ ));+ }+ for uri in [+ "http://192.0.2.10:8123/v1/responses",+ "http://gateway.invalid/v1/responses",+ ] {+ assert!(+ !GatewayOperationalTargetV1::RegisteredHttps { uri: uri.into() }+ .validate_for(ConnectorRuntimeKind::BuiltinNative, uri)+ );+ assert!(+ !GatewayOperationalTargetV1::ManagedCpaLoopback {+ uri: uri.into(),+ runtime_epoch: 1,+ target_epoch: 1+ }+ .validate_for(ConnectorRuntimeKind::CpaBridge, uri)+ );+ }+ for uri in [+ "ftp://gateway.invalid/v1/responses",+ "http://user:[email protected]/v1/responses",+ "http://gateway.invalid/v1/responses?key=secret",+ "http://gateway.invalid/v1/../responses",+ "http://gateway.invalid/v1/%2e%2e/responses",+ "http://gateway.invalid:0/v1/responses",+ ] {+ assert!(+ !GatewayOperationalTargetV1::UserConfiguredNative { uri: uri.into() }+ .validate_for(ConnectorRuntimeKind::BuiltinNative, uri),+ "{uri}"+ );+ }+ }+#[test]fn registered_protocol_path_keeps_authority_and_user_target_stays_exact() {let registered = GatewayOperationalTargetV1::RegisteredHttps {diff --git a/crates/integrations/src/model_connections/mod.rs b/crates/integrations/src/model_connections/mod.rsindex e7d7c39c..cfbf0c7f 100644--- a/crates/integrations/src/model_connections/mod.rs+++ b/crates/integrations/src/model_connections/mod.rs@@ -20,7 +20,7 @@ use std::{collections::BTreeMap,fmt::{self, Write as _},sync::Mutex,- time::{Duration, Instant, SystemTime, UNIX_EPOCH},+ time::{Instant, SystemTime, UNIX_EPOCH},};use hiroute_application::compute_management::{@@ -478,20 +478,17 @@ where// Allocate before DNS or request I/O. If an older request completes after a newer one for// the same candidate lineage, the candidate directory rejects its lower backend revision.let (candidate_ref, revision) = self.issue_candidate(draft.candidate_ref.as_deref())?;- let target = normalize_model_connection_target_with_timeout(- ModelConnectionTargetInputV1 {- base_url: &draft.base_url,- base_kind: draft.base_kind,- protocol: draft.protocol,- request_path_override: draft.request_path_override.as_deref(),- inventory_path_override: draft.inventory_path_override.as_deref(),- protocol_profile_id: &draft.protocol_profile_id,- protocol_profile_revision: draft.protocol_profile_revision,- protocol_header_semantics: &draft.protocol_header_semantics,- authentication: &draft.authentication,- },- self.limits.total_timeout.min(Duration::from_secs(2)),- )?;+ let target = normalize_model_connection_target(ModelConnectionTargetInputV1 {+ base_url: &draft.base_url,+ base_kind: draft.base_kind,+ protocol: draft.protocol,+ request_path_override: draft.request_path_override.as_deref(),+ inventory_path_override: draft.inventory_path_override.as_deref(),+ protocol_profile_id: &draft.protocol_profile_id,+ protocol_profile_revision: draft.protocol_profile_revision,+ protocol_header_semantics: &draft.protocol_header_semantics,+ authentication: &draft.authentication,+ })?;let input_digest = input_digest(&draft, &credential)?;let remaining = self.limitsdiff --git a/crates/integrations/src/model_connections/target.rs b/crates/integrations/src/model_connections/target.rsindex 2b582f74..4d2bfabf 100644--- a/crates/integrations/src/model_connections/target.rs+++ b/crates/integrations/src/model_connections/target.rs@@ -1,9 +1,3 @@-use std::{- net::{IpAddr, SocketAddr, ToSocketAddrs},- sync::mpsc,- time::Duration,-};-use hiroute_application_api::ComputeCandidateTargetV2;use hiroute_domain::{GatewayAuthenticationSemanticsV1, GatewayHeaderSemanticsV1, UpstreamProtocol,@@ -41,7 +35,6 @@ pub struct NormalizedModelConnectionTargetV1 {pub candidate_target: ComputeCandidateTargetV2,pub inventory_path: Option<String>,host_header: String,- network_authority: String,directory_headers: Vec<(HeaderName, HeaderValue)>,}@@ -73,7 +66,7 @@ impl NormalizedModelConnectionTargetV1 {fn url_for(&self, path: &str) -> String {format!("{}://{}{}",- self.candidate_target.scheme, self.network_authority, path+ self.candidate_target.scheme, self.host_header, path)}}@@ -82,41 +75,31 @@ impl NormalizedModelConnectionTargetV1 {pub enum ModelConnectionTargetError {#[error("model connection URL is invalid")]InvalidUrl,- #[error("HTTP is allowed only when every resolved target address is loopback")]- NonLoopbackHttp,#[error("model connection URL contains an unsafe path")]UnsafePath,#[error("model connection authentication header is unsafe")]UnsafeAuthenticationHeader,#[error("model connection protocol profile headers are unsupported or unsafe")]UnsafeProtocolHeader,- #[error("loopback hostname resolution timed out")]- ResolutionTimeout,}+/// Validate the configured target without DNS or I/O. The bounded transport resolves+/// its hostname when explicitly checking or executing a request, for HTTP and HTTPS alike.pub fn normalize_model_connection_target(input: ModelConnectionTargetInputV1<'_>,) -> Result<NormalizedModelConnectionTargetV1, ModelConnectionTargetError> {- normalize_model_connection_target_with_timeout(input, Duration::from_secs(2))-}--pub(crate) fn normalize_model_connection_target_with_timeout(- input: ModelConnectionTargetInputV1<'_>,- resolution_timeout: Duration,-) -> Result<NormalizedModelConnectionTargetV1, ModelConnectionTargetError> {- normalize_target(input, Some(resolution_timeout))+ normalize_target(input)}/// Pure scan projection. It never resolves hostnames or opens a socket.pub fn project_model_connection_target(input: ModelConnectionTargetInputV1<'_>,) -> Result<NormalizedModelConnectionTargetV1, ModelConnectionTargetError> {- normalize_target(input, None)+ normalize_target(input)}fn normalize_target(input: ModelConnectionTargetInputV1<'_>,- resolution_timeout: Option<Duration>,) -> Result<NormalizedModelConnectionTargetV1, ModelConnectionTargetError> {let ModelConnectionTargetInputV1 {base_url,@@ -159,7 +142,12 @@ fn normalize_target(if authority.as_str().contains('@') {return Err(ModelConnectionTargetError::InvalidUrl);}- let host = authority.host().trim_end_matches('.').to_ascii_lowercase();+ let host = authority+ .host()+ .trim_start_matches('[')+ .trim_end_matches(']')+ .trim_end_matches('.')+ .to_ascii_lowercase();if host.is_empty() {return Err(ModelConnectionTargetError::InvalidUrl);}@@ -180,33 +168,10 @@ fn normalize_target(.transpose()?;let host_header = authority_for(&host, port, &scheme);- let network_authority = if scheme == "http" {- let addresses = match resolution_timeout {- Some(timeout) => resolve_loopback(&host, port, timeout)?,- None => match host.parse::<IpAddr>() {- Ok(ip) if ip.is_loopback() => vec![SocketAddr::new(ip, port)],- _ if host == "localhost" => {- vec![SocketAddr::new(IpAddr::from([127, 0, 0, 1]), port)]- }- _ => return Err(ModelConnectionTargetError::NonLoopbackHttp),- },- };- let address = addresses- .first()- .ok_or(ModelConnectionTargetError::NonLoopbackHttp)?;- socket_authority(*address)- } else {- host_header.clone()- };- let published_authority = if scheme == "http" {- addresses_host(&network_authority)?- } else {- host.clone()- };Ok(NormalizedModelConnectionTargetV1 {candidate_target: ComputeCandidateTargetV2 {scheme,- authority: published_authority,+ authority: host,port,request_path,upstream_protocol: protocol,@@ -215,18 +180,10 @@ fn normalize_target(},inventory_path,host_header,- network_authority,directory_headers,})}-fn addresses_host(authority: &str) -> Result<String, ModelConnectionTargetError> {- let address = authority- .parse::<SocketAddr>()- .map_err(|_| ModelConnectionTargetError::InvalidUrl)?;- Ok(address.ip().to_string())-}-fn validated_directory_headers(protocol: UpstreamProtocol,authentication: &GatewayAuthenticationSemanticsV1,@@ -362,39 +319,6 @@ fn append(base: &str, suffix: &str) -> String {}}-fn resolve_loopback(- host: &str,- port: u16,- timeout: Duration,-) -> Result<Vec<SocketAddr>, ModelConnectionTargetError> {- if let Ok(ip) = host.parse::<IpAddr>() {- return if ip.is_loopback() {- Ok(vec![SocketAddr::new(ip, port)])- } else {- Err(ModelConnectionTargetError::NonLoopbackHttp)- };- }- let (tx, rx) = mpsc::sync_channel(1);- let host = host.to_owned();- std::thread::spawn(move || {- let result = (host.as_str(), port)- .to_socket_addrs()- .map(|values| values.collect::<Vec<_>>());- let _ = tx.send(result);- });- let mut addresses = rx- .recv_timeout(timeout)- .map_err(|_| ModelConnectionTargetError::ResolutionTimeout)?- .map_err(|_| ModelConnectionTargetError::NonLoopbackHttp)?;- addresses.sort();- addresses.dedup();- if addresses.is_empty() || addresses.iter().any(|address| !address.ip().is_loopback()) {- Err(ModelConnectionTargetError::NonLoopbackHttp)- } else {- Ok(addresses)- }-}-fn authority_for(host: &str, port: u16, scheme: &str) -> String {let host = if host.contains(':') {format!("[{host}]")@@ -408,13 +332,6 @@ fn authority_for(host: &str, port: u16, scheme: &str) -> String {}}-fn socket_authority(address: SocketAddr) -> String {- match address {- SocketAddr::V4(value) => value.to_string(),- SocketAddr::V6(value) => format!("[{}]:{}", value.ip(), value.port()),- }-}-#[cfg(test)]mod tests {use super::*;@@ -485,29 +402,96 @@ mod tests {}#[test]- fn plaintext_and_unsafe_headers_fail_before_network() {- let loopback = normalize_model_connection_target(input(- "http://127.0.0.1:8123/v1",+ fn explicit_http_and_https_targets_preserve_the_host_without_dns() {+ for (base, authority, host, port) in [+ ("http://192.0.2.10/v1", "192.0.2.10", "192.0.2.10", 80),+ (+ "http://192.168.1.10:8123/v1",+ "192.168.1.10",+ "192.168.1.10:8123",+ 8123,+ ),+ (+ "http://gateway.invalid:8123/v1",+ "gateway.invalid",+ "gateway.invalid:8123",+ 8123,+ ),+ (+ "http://localhost:8123/v1",+ "localhost",+ "localhost:8123",+ 8123,+ ),+ (+ "http://127.0.0.1:8123/v1",+ "127.0.0.1",+ "127.0.0.1:8123",+ 8123,+ ),+ ("http://[::1]:8123/v1", "::1", "[::1]:8123", 8123),+ (+ "http://[2001:db8::10]:8123/v1",+ "2001:db8::10",+ "[2001:db8::10]:8123",+ 8123,+ ),+ (+ "https://gateway.invalid/v1",+ "gateway.invalid",+ "gateway.invalid",+ 443,+ ),+ ] {+ for authentication in [+ GatewayAuthenticationSemanticsV1::None,+ GatewayAuthenticationSemanticsV1::Bearer,+ GatewayAuthenticationSemanticsV1::ApiKeyHeader {+ header: "x-api-key".into(),+ },+ ] {+ let draft = input(+ base,+ ModelConnectionBaseKindV1::ApiRoot,+ UpstreamProtocol::Responses,+ "profile/responses",+ &authentication,+ );+ let target = normalize_model_connection_target(draft).unwrap();+ assert_eq!(target.candidate_target.authority, authority);+ assert_eq!(target.candidate_target.port, port);+ assert_eq!(target.host_header(), host);+ assert_eq!(target.request_url(), format!("{base}/responses"));+ assert_eq!(target.inventory_path, None);+ assert_eq!(project_model_connection_target(draft).unwrap(), target);+ }+ }+ }++ #[test]+ fn explicit_http_directory_uses_the_same_configured_authority() {+ let mut draft = input(+ "http://gateway.invalid:8123/proxy",ModelConnectionBaseKindV1::ApiRoot,UpstreamProtocol::Responses,"profile/responses",- &GatewayAuthenticationSemanticsV1::None,- ))- .unwrap();- assert_eq!(loopback.candidate_target.authority, "127.0.0.1");- assert_eq!(loopback.candidate_target.port, 8123);- assert_eq!(loopback.request_url(), "http://127.0.0.1:8123/v1/responses");-+ &GatewayAuthenticationSemanticsV1::Bearer,+ );+ draft.inventory_path_override = Some("/proxy/models");+ let target = normalize_model_connection_target(draft).unwrap();+ assert_eq!(+ target.inventory_url(None),+ "http://gateway.invalid:8123/proxy/models"+ );assert_eq!(- normalize_model_connection_target(input(- "http://192.0.2.10/v1",- ModelConnectionBaseKindV1::ApiRoot,- UpstreamProtocol::Responses,- "profile/responses",- &GatewayAuthenticationSemanticsV1::Bearer,- )),- Err(ModelConnectionTargetError::NonLoopbackHttp)+ target.request_url(),+ "http://gateway.invalid:8123/proxy/responses");+ assert_eq!(target.host_header(), "gateway.invalid:8123");+ }++ #[test]+ fn unsafe_authentication_headers_fail_before_network() {assert_eq!(validate_authentication_header(&GatewayAuthenticationSemanticsV1::ApiKeyHeader {header: "Proxy-Authorization".into()@@ -516,9 +500,34 @@ mod tests {);}+ #[test]+ fn http_does_not_allow_protocol_headers_to_inject_credentials() {+ let headers = GatewayHeaderSemanticsV1 {+ content_type: "application/json".into(),+ required_headers: vec![("authorization".into(), "Bearer must-not-leak".into())],+ forbidden_forward_headers: Vec::new(),+ };+ let mut draft = input(+ "http://gateway.invalid/v1",+ ModelConnectionBaseKindV1::ApiRoot,+ UpstreamProtocol::Responses,+ "profile/responses",+ &GatewayAuthenticationSemanticsV1::None,+ );+ draft.protocol_header_semantics = &headers;+ assert_eq!(+ normalize_model_connection_target(draft),+ Err(ModelConnectionTargetError::UnsafeProtocolHeader)+ );+ }+#[test]fn embedded_secrets_and_ambiguous_paths_are_rejected() {for url in [+ "http://user:[email protected]/v1",+ "http://gateway.invalid/v1?api_key=secret",+ "http://gateway.invalid/v1/%2e%2e/private",+ "ftp://gateway.invalid/v1","https://user:[email protected]/v1","https://example.test/v1?api_key=secret","https://example.test/v1/%2e%2e/private",diff --git a/crates/integrations/tests/model_connections/onboarding.rs b/crates/integrations/tests/model_connections/onboarding.rsindex 2240b0d7..129b306b 100644--- a/crates/integrations/tests/model_connections/onboarding.rs+++ b/crates/integrations/tests/model_connections/onboarding.rs@@ -1,5 +1,53 @@use super::*;+#[test]+fn explicit_non_loopback_http_checks_only_probe_a_configured_directory() {+ for endpoint in [+ "http://192.0.2.10:8123/v1",+ "http://gateway.invalid:8123/v1",+ ] {+ for directory in [None, Some("/v1/models")] {+ let transport = CountingTransport::default();+ let calls = transport.calls();+ let service =+ NativeModelConnectionServiceV1::new(TestOnlyComputeCandidatePort::new(), transport);+ let mut input = draft(endpoint.into(), GatewayAuthenticationSemanticsV1::None);+ input.inventory_path_override = directory.map(str::to_owned);+ let result = service+ .check(+ input,+ NativeModelConnectionCredentialV1::NotRequired,+ &ModelConnectionProbeCancellationV1::default(),+ )+ .unwrap();+ assert_eq!(+ calls.load(Ordering::SeqCst),+ usize::from(directory.is_some())+ );+ assert_eq!(result.inventory_path.as_deref(), directory);+ assert_eq!(result.target.scheme, "http");+ assert_eq!(result.target.port, 8123);+ assert_eq!(+ result.target.authority,+ if endpoint.contains("192.0.2.10") {+ "192.0.2.10"+ } else {+ "gateway.invalid"+ }+ );+ assert!(result.candidate.models.iter().any(|model| model.selectable));+ assert_eq!(result.inference, ModelConnectionInferenceStatusV1::NotRun);+ if directory.is_none() {+ assert_eq!(result.directory, ModelConnectionDirectoryStatusV1::NotRun);+ assert_ne!(+ result.reachability,+ ModelConnectionReachabilityV1::Reachable+ );+ }+ }+ }+}+#[test]fn directory_is_optional_for_registered_and_manual_text_models() {for registered in [false, true] {diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex 3b098ca2..b685c2d3 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -74,6 +74,18 @@ module before extending it; a local feature does not require a facade-wide rewri## Model sources and native configuration+Custom API [target normalization](../../crates/integrations/src/model_connections/target.rs)+is pure for HTTP and HTTPS, retaining the configured hostname until bounded request+transport resolves it. Explicit LAN/remote HTTP uses the ordinary check/save flow.+The [durable target](../../crates/domain/src/compute/management/mod.rs) and+[user-configured Gateway target](../../crates/domain/src/routing/gateway_execution.rs)+admit the same explicit transports while retaining exact credential destinations+and the separate registered/managed-connector scopes.+[Control error translation](../../crates/daemon/src/control/runtime/model_connections/error.rs)+retains closed target reasons in the existing error envelope; the Desktop form owns+localized corrections and plaintext notices. The [real-process regression](../../crates/daemon/tests/support/custom_http_product.py)+covers omitted-directory save/restart/recheck and safe error propagation.+Branch execution keys distinguish reasoning selections. The derived Gateway candidatealso retains its original source binding for current credential membership and exactleases; routing, retry and context identities continue using the execution key.diff --git a/docs/code-map/testing.md b/docs/code-map/testing.mdindex 429957ea..4692f10a 100644--- a/docs/code-map/testing.md+++ b/docs/code-map/testing.md@@ -51,6 +51,7 @@ validate the oracle. The real installed management loop is in| Need | Reuse / preserve || --- | --- || Prepare a daemon's current sources, grants and plans | [Publication Product](../../crates/daemon/tests/support/publication_product.py): its `Product.cli` is internal Local Control notation, not the standalone CLI; protected input belongs to that fixture's daemon |+| Save an explicit HTTP model source or correct its target | [Custom HTTP journey](../../crates/daemon/tests/support/custom_http_product.py): real control/save/restart/recheck with synthetic literal/hostname targets and no directory; [connection form browser checks](../../apps/desktop/tests/v3/visual/connection-flow-active.mjs) separately cover plaintext notices, localized errors and retained input || Configure a real native Agent | [Agent product support](../../crates/daemon/tests/support/agent_product_support.py): shared Preview → Apply → status and bounded process capture; native argv/ownership/result interpretation remain in the leaf || Prove saved model configuration | [Additional-model journey](../../crates/daemon/tests/support/additional_model_product.py), [Windows Pi/DSH journey](../../crates/daemon/tests/support/windows_user_models.rs), [Windows Qoder account journey](../../crates/daemon/tests/support/windows_qoder_user_models.rs): ordinary native startup reads saved settings without provider/endpoint/credential overrides; `agent-user-models` and protected `account-qoder-user-models` remain separate from Worker profiles || Observe native routing and rejected attempts | [NativeContextUpstream](../../crates/daemon/tests/support/native_context_fixture.py): count every model POST, including rejected endpoints/models/credentials; keep the ledger for positive route/history assertions |diff --git a/issue-spec/specs/model-connections/spec.md b/issue-spec/specs/model-connections/spec.mdindex a88fd0fc..c5b7b51e 100644--- a/issue-spec/specs/model-connections/spec.md+++ b/issue-spec/specs/model-connections/spec.md@@ -157,8 +157,17 @@ execution is preferred; an absent protocol may use only an expressible existingconversion. Endpoint health is isolated; manual Key disable affects the source.Custom configuration supports name, base URL/path prefix, None/Bearer/specified-Header authentication, and multiple manual models. Public endpoints require TLS;-loopback may use plain HTTP. Target changes require revalidation. Credentials cannot+Header authentication, and multiple manual models. A user may explicitly configure+HTTP or HTTPS for a loopback, LAN or remote endpoint, whether its host is a literal+address or a hostname. HTTP is not rejected solely because the destination is+non-loopback. HTTPS is recommended; an HTTP selection explains that API keys and+request/response content travel in plaintext without adding a mandatory confirmation.+Target normalization preserves the configured hostname; DNS and connectivity are+evaluated by bounded request transport, not by passive discovery or a syntactic check.+The same transport policy applies to durable source validation, publication and+actual Gateway execution. Registered catalog destinations remain bound to their+exact HTTPS authority; managed CPA transport retains its numeric-loopback scope.+Target changes require revalidation. Credentials cannotbe redirected to an unauthorized destination; TLS failure never falls back to plaintransport. Embedded URL passwords/query Keys must use protected input instead.@@ -170,6 +179,26 @@ an otherwise expressible model. Cost hints without currency/unit/product/region/semantics are not PriceRate, free entitlement, or savings evidence. Metadata fieldclosure and reference pricing follow [model facts](../model-catalog-price/spec.md).+#### Scenario: Save an explicitly configured HTTP source without a directory++- **WHEN** the owner configures a valid LAN or remote HTTP endpoint, leaves the model+ directory path empty and supplies supported manual model declarations+- **THEN** connection check, save and saved-source recheck accept that target without+ DNS or directory/inference calls, preserve the exact target and authentication,+ and do not claim reachability, account access or inference has been verified.++#### Scenario: Correct an invalid connection target++- **WHEN** a connection check rejects an invalid URL, unsafe path, authentication+ header or protocol header, including an additional protocol endpoint+- **THEN** the daemon/API retains a closed, specific reason in the existing error+ envelope, with the released `INVALID_ARGUMENTS` machine code; Desktop presents+ a localized correction and retains input. Errors never expose URL credentials,+ protected keys or raw provider responses. Other URL/path/authentication checks,+ redirect restrictions and HTTPS certificate validation remain enforced.++Source Issue: https://github.com/higress-group/HiRoute/issues/154+### Requirement: Saved-source recheck reconstructs protected factsRecheck submits source ID, exact expected revision, permitted candidate reference,