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
feat: add DeepSeek Harness routing and native ACP delegation (#48)
澄潭873b4eec8c05
diff --git a/.github/actions/ci-setup/action.yml b/.github/actions/ci-setup/action.ymlindex 14a0dc45..ca37a0eb 100644--- a/.github/actions/ci-setup/action.yml+++ b/.github/actions/ci-setup/action.yml@@ -3,6 +3,9 @@ description: Prepare the hosted Linux checkout without using the SSH workbenchruns:using: compositesteps:+ - name: Cargo Git transport+ shell: bash+ run: printf '%s\n' 'CARGO_NET_GIT_FETCH_WITH_CLI=true' >> "$GITHUB_ENV"- name: Native build prerequisitesshell: bashrun: sudo apt-get update && sudo apt-get install --yes cmake clang pkg-config libssl-devdiff --git a/Cargo.lock b/Cargo.lockindex c19066e4..c68ac5b3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2492,6 +2492,7 @@ dependencies = ["rustix","serde","serde_json",+ "serde_yaml","tempfile","thiserror 2.0.20","toml_edit 0.25.13+spec-1.1.0",diff --git a/apps/desktop/src-tauri/src/agent_check_session.rs b/apps/desktop/src-tauri/src/agent_check_session.rsindex d7bc3dfc..080bb6a7 100644--- a/apps/desktop/src-tauri/src/agent_check_session.rs+++ b/apps/desktop/src-tauri/src/agent_check_session.rs@@ -123,6 +123,7 @@ impl AgentCheckConfirmation {"agent_claude_default" => "Claude Code","agent_qoder_default" => "Qoder","agent_pi_default" => "Pi",+ "agent_dsh_default" => "DeepSeek Harness",_ => "Codex",};if self.request.scope == AgentCheckScopeV1::Live {@@ -137,6 +138,7 @@ impl AgentCheckConfirmation {AgentModelSurfaceV2::ClaudeCli => "Claude Code CLI",AgentModelSurfaceV2::QoderCli => "Qoder CLI",AgentModelSurfaceV2::PiCli => "Pi CLI",+ AgentModelSurfaceV2::DshCli => "DeepSeek Harness",};let models = target.client_model_ids.join(", ");let message = if self.english {@@ -183,6 +185,15 @@ impl AgentCheckConfirmation {"检查本机 Pi 任务委派兼容性?\n读取所选官方 SDK、原生技能设置和同一安装中的 HiRoute CLI。不发起模型调用、不执行委派任务、不修改原生配置。".into()};}+ if self.request.scope == AgentCheckScopeV1::Collaboration+ && self.request.agent_id == "agent_dsh_default"+ {+ return if self.english {+ "Check local DeepSeek Harness task delegation compatibility?\nReads the native CLI's public composition, Skill locations and trusted sibling HiRoute CLI. No model call, delegated task or native configuration change.".into()+ } else {+ "检查本机 DeepSeek Harness 任务委派兼容性?\n读取原生 CLI 的公开配置能力、技能位置及同一安装中的 HiRoute CLI。不发起模型调用、不执行委派任务、不修改原生配置。".into()+ };+ }if self.request.scope == AgentCheckScopeV1::Collaboration && self.english {return format!("Check local {agent} task delegation compatibility?\nLaunches the installed {agent} client in a private environment and verifies isolated Skill loading plus read-only trusted CLI execution. No provider call or daily configuration change."@@ -266,7 +277,7 @@ impl AgentCheckInput {};let supported = match self.agent_id.as_str() {"agent_codex_default" | "agent_claude_default" => true,- "agent_pi_default" => scope == AgentCheckScopeV1::Collaboration,+ "agent_pi_default" | "agent_dsh_default" => scope == AgentCheckScopeV1::Collaboration,"agent_qoder_default" => matches!(scope,AgentCheckScopeV1::Collaboration | AgentCheckScopeV1::Livediff --git a/apps/desktop/src/features/WorkerDependencies.tsx b/apps/desktop/src/features/WorkerDependencies.tsxindex 056abce1..c6308756 100644--- a/apps/desktop/src/features/WorkerDependencies.tsx+++ b/apps/desktop/src/features/WorkerDependencies.tsx@@ -53,7 +53,7 @@ export function WorkerDependencies({}) {const zh = language === 'zh';const text = (cn: string, en: string) => zh ? cn : en;- const name = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', qoder_cli: 'Qoder CLI', pi: 'Pi' }[harness];+ const name = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', qoder_cli: 'Qoder CLI', pi: 'Pi', deepseek_harness: 'DeepSeek Harness' }[harness];const components = workerDependencyComponents(harness);const [view, setView] = useState<WorkerDependenciesView | null>(null);const [selection, setSelection] = useState<WorkerDependencySelectionRequest | null>(null);@@ -125,7 +125,7 @@ export function WorkerDependencies({setSelection(current => ({harness,cli_path: '',- ...(harness === 'qoder_cli' ? {} : { ...(harness === 'pi' ? {} : { adapter_path: '' }), node_path: null }),+ ...((harness === 'qoder_cli' || harness === 'deepseek_harness') ? {} : { ...(harness === 'pi' ? {} : { adapter_path: '' }), node_path: null }),expected_selection_revision: view ? workerDependencyRevision(view, harness) : 0,...current,...patch,@@ -222,6 +222,7 @@ export function WorkerDependencies({{text('选择已安装的 Qoder CLI(qoder 或 qodercli)。需要登录时,请在终端正常启动该 CLI 并完成登录,再返回使用。', 'Select your installed Qoder CLI (qoder or qodercli). When sign-in is needed, start that CLI normally in a terminal and sign in, then return here.')} {' '}<a href="https://docs.qoder.com/cli/installation" target="_blank" rel="noreferrer" onClick={event => void openInstallationGuide(event)}>{text('官方安装与升级说明', 'Official installation and upgrade guide')}</a></p>}+ {harness === 'deepseek_harness' && <p className="field-help" data-dsh-installation-guide>{text('安装官方 dsh CLI 并检测安装位置。npm 安装需要受支持的 Node.js;任务通过原生 ACP 执行,无需连接组件。', 'Install the official dsh CLI and detect its location. npm installations need supported Node.js; tasks use native ACP with no adapter.')}</p>}{harness === 'pi' && <p className="field-help" data-pi-installation-guide>{text('使用官方 npm 安装的 Pi 和 Node.js。检测安装位置后,保存时会检查所需能力;也可查看安装命令。', 'Use the official npm installation of Pi and Node.js. Detect installation paths; saving checks the required capabilities. Installation commands are also available.')}</p>}{!view && <div className="option-panel"><div className="option-row"><div><strong>{text('检测本机安装', 'Detect local installation')}</strong><span>{harness === 'qoder_cli'? text('查找当前环境中的 Qoder CLI。', 'Find Qoder CLI in the current environment.')diff --git a/apps/desktop/src/features/agents/AdditionalModelEditor.tsx b/apps/desktop/src/features/agents/AdditionalModelEditor.tsxindex e39f871e..bb78823f 100644--- a/apps/desktop/src/features/agents/AdditionalModelEditor.tsx+++ b/apps/desktop/src/features/agents/AdditionalModelEditor.tsx@@ -8,6 +8,7 @@ import type { AgentModelEditorProps } from './AgentModelEditor';/** Shared Plan selection for ecosystems that add an independent native provider. */export function AdditionalModelEditor({ agent, values, plans, language, disabled, invalid, onChange, onEdited, onCreatePlan }: AgentModelEditorProps) {const text = (zh: string, en: string) => language === 'zh' ? zh : en;+ const dsh = agent.agent_id === 'agent_dsh_default';const name = agentDisplayName(agent.agent_id, language);const enabledPlans = plans.filter(plan => plan.head.status === 'enabled');const unavailable = values.allowedPlanIds.filter(id => !enabledPlans.some(plan => plan.agent_plan_id === id));@@ -30,7 +31,7 @@ export function AdditionalModelEditor({ agent, values, plans, language, disabled</label>)}</fieldset><div className="additional-model-editor__help">- <p className="field-help" data-agent-activation>{text(`保存后重新启动 ${name},通过 /model 明确选用已添加的 HiRoute 路由。未选择时继续使用原来的模型。`, `Restart ${name} after saving, then explicitly select an added HiRoute route with /model. Otherwise it keeps using your previous model.`)}</p>+ <p className="field-help" data-agent-activation>{dsh ? text('保存后启动 dsh web,在模型选择器中选用 HiRoute 路由。此配置作用于标准 web profile;其他 profile 保留原有配置。', 'After saving, start dsh web and select a HiRoute route in the model picker. This configures the standard web profile; other profiles retain their configuration.') : text(`保存后重新启动 ${name},通过 /model 明确选用已添加的 HiRoute 路由。未选择时继续使用原来的模型。`, `Restart ${name} after saving, then explicitly select an added HiRoute route with /model. Otherwise it keeps using your previous model.`)}</p><p className="field-help">{text(`在 HiRoute 中调整或移除这些路由。如果已将某条路由设为 ${name} 默认模型,移除前请先在 ${name} 中切换到其他模型。`, `Adjust or remove these routes in HiRoute. If one is now your ${name} default, switch to another model in ${name} before removing it.`)}</p></div>{invalid && <span className="oc-inline-error">{text(`至少选择一条已启用路由,并取消不可用的选择。`, `Select at least one enabled route and remove unavailable selections.`)}</span>}diff --git a/apps/desktop/src/features/agents/AgentModelEditor.tsx b/apps/desktop/src/features/agents/AgentModelEditor.tsxindex 24bdbf07..02f9e7e1 100644--- a/apps/desktop/src/features/agents/AgentModelEditor.tsx+++ b/apps/desktop/src/features/agents/AgentModelEditor.tsx@@ -27,6 +27,7 @@ export function AgentModelEditor(props: AgentModelEditorProps) {switch (agentEcosystem(props.agent.agent_id)) {case 'codex': return <CodexModelEditor {...props} />;case 'claude': return <ClaudeModelEditor {...props} />;+ case 'dsh':case 'pi':case 'qoder': return <AdditionalModelEditor {...props} />;default: return null;@@ -49,6 +50,7 @@ export function modelSelectionSummary(selection: AgentModelSelection | null | un? text('三个档位共用:', 'All presets use: ') + (planName(sharedPlan) ?? text('当前路由不可用', 'Current route unavailable')): Object.entries(selection.preset_mappings).map(([preset, choice]) => `${preset[0].toUpperCase() + preset.slice(1)}: ${choice.kind === 'plan' ? planName(choice.plan_id) ?? text('当前路由不可用', 'Current route unavailable') : text('保留原生', 'Native')}`).join(' · ');}+ case 'dsh_additional':case 'pi_additional':case 'qoder_additional':return selection.allowed_plan_ids.map(id => planName(id) ?? text('当前路由不可用', 'Current route unavailable')).join(' · ');diff --git a/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx b/apps/desktop/src/features/agents/AgentSettingsFeedback.tsxindex 4da8c789..ccc9a3ee 100644--- a/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx+++ b/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx@@ -31,7 +31,7 @@ export function AgentSettingsFeedback({ preview, agent: selected, facet, default: block.reason === 'restore_native_model_invalid'? text('恢复将留下无效的原生默认模型。请在“连接详情与恢复”中明确选择一个原生模型后重试。', 'Restoring would leave an invalid native default. Choose a native model under Connection details and recovery, then retry.'): block.reason === 'additional_default_in_use'- ? text('当前默认模型仍引用将被移除的路由。请先在 Pi 中通过 /model 切换到其他模型,然后重试。', 'The default model still uses a route being removed. Switch to another model with /model in Pi, then retry.')+ ? text('当前默认模型仍引用将被移除的路由。请先在所选客户端中切换到其他模型,然后重试;HiRoute 不会替你更改默认模型。', 'The default model still uses a route being removed. Switch to another model in the selected client, then retry; HiRoute will not change the default for you.'): block.reason === 'qoder_default_in_use'? text('Qoder 当前默认模型仍引用将被移除的 HiRoute 路由。请先在 Qoder 中通过 /model 切换到其他模型,再重试;HiRoute 不会替你更改默认模型。', 'Qoder’s current default still uses a HiRoute route being removed. Switch to another model with /model in Qoder, then retry; HiRoute will not change the default for you.'): block.reason === 'qoder_model_file_conflict'diff --git a/apps/desktop/src/features/agents/README.md b/apps/desktop/src/features/agents/README.mdindex 53793e2d..cb555f9e 100644--- a/apps/desktop/src/features/agents/README.md+++ b/apps/desktop/src/features/agents/README.md@@ -22,14 +22,19 @@ to their production owners and executable contracts.| [mutation-feedback.ts](mutation-feedback.ts) | Submitted, pre-apply cancelled and uncertain outcomes; truthful disable/recovery messages. || [Agents page](../../agents.tsx) | Snapshot refresh, selected Agent/tab, in-memory draft and mode, discard guard, native calls, Operation handoff, confirmation-dependent copy effect and task-history composition. |-Qoder adds only explicitly selected Plan IDs through `qoder_additional`. It does not+Qoder, Pi and DSH share the additional-route editor and explicitly selected Plan IDs+through `qoder_additional`, `pi_additional` and `dsh_additional`. It does notedit the native default or show native catalogs, fixed-source choices or import controls.Its model configuration uses the existing Preview, protected token and independentrestore flow. A model restore keeps the collaboration Skill; a collaboration restorekeeps the model routes. Token updates retain the saved ecosystem-specific selection.Task collaboration remains independently usable without any model connection or-published Plan: its form submits `model: keep`. Both model-capable status and actual+published Plan: its form submits `model: keep`. DSH configures the standard Web profile model picker; global provider shadowing is+reported by the backend before Apply. Each selected Plan has its own provider and+user-selected Responses/Messages protocol.++Both model-capable status and actualcollaboration-only status retain this path. Capability and installed-Skill checksprovide scoped prerequisite or diagnostic facts; neither proves a delegated taskcompleted or a model route worked. They do not create another settings workflow.@@ -90,7 +95,7 @@ additional enable/save steps or model-verification badges on the settings page.| User journey or invariant | Representative evidence || --- | --- |-| Shared configuration actions and state across Codex, Claude Code and Qoder, without an automatic live model call | `agent.configuration.shared-interactions` in the [Agent browser scenarios](../../../tests/v3/browser/agent-trust-scenarios.mjs) |+| Shared configuration actions and state across the supported Agent ecosystems, without an automatic live model call | `agent.configuration.shared-interactions` in the [Agent browser scenarios](../../../tests/v3/browser/agent-trust-scenarios.mjs) || First enable, exact existing selections, unknown state and discard protection | [agent-editor-state.test.mjs](../../../tests/agent-editor-state.test.mjs) || Correct ecosystem intent, independent restores, saved-selection token rotation and unsupported identity rejection | [agent-settings-request.test.mjs](../../../tests/agent-settings-request.test.mjs) || Collaboration without a model or published Plan, prerequisite failure/retry and restore; independent single-CLI selection | `qoder.collaboration.enable-without-model`, `qoder.collaboration.retry-and-restore`, `qoder.installation.single-cli` in the browser scenarios; [status projection](../../../tests/agent-status.test.mjs) |diff --git a/apps/desktop/src/features/agents/ecosystems.ts b/apps/desktop/src/features/agents/ecosystems.tsindex 44ceb445..1e8a2238 100644--- a/apps/desktop/src/features/agents/ecosystems.ts+++ b/apps/desktop/src/features/agents/ecosystems.ts@@ -1,12 +1,13 @@import type { AgentModelSelection, AgentModelSurface } from './types';-export type AgentEcosystem = 'codex' | 'claude' | 'qoder' | 'pi';+export type AgentEcosystem = 'codex' | 'claude' | 'qoder' | 'pi' | 'dsh';/** Only these current integrations have settings editors; discovery is independent. */export function agentEcosystem(agentId: string): AgentEcosystem | null {switch (agentId) {case 'agent_codex_default': return 'codex';case 'agent_claude_default': return 'claude';+ case 'agent_dsh_default': return 'dsh';case 'agent_pi_default': return 'pi';case 'agent_qoder_default': return 'qoder';default: return null;@@ -15,7 +16,7 @@ export function agentEcosystem(agentId: string): AgentEcosystem | null {export function agentSupportsModelRouting(agentId: string): boolean {const ecosystem = agentEcosystem(agentId);- return ecosystem === 'codex' || ecosystem === 'claude' || ecosystem === 'qoder' || ecosystem === 'pi';+ return ecosystem === 'codex' || ecosystem === 'claude' || ecosystem === 'qoder' || ecosystem === 'pi' || ecosystem === 'dsh';}/** A saved selection must belong to the actual integration, including token-only edits. */@@ -23,6 +24,7 @@ export function agentModelSelectionMatches(agentId: string, selection: AgentModeswitch (agentEcosystem(agentId)) {case 'codex': return selection.mode === 'codex_default';case 'claude': return selection.mode === 'claude_launcher';+ case 'dsh': return selection.mode === 'dsh_additional';case 'pi': return selection.mode === 'pi_additional';case 'qoder': return selection.mode === 'qoder_additional';default: return false;@@ -33,16 +35,18 @@ export function agentDisplayName(agentId: string, language: 'zh' | 'en'): stringswitch (agentEcosystem(agentId)) {case 'codex': return 'Codex';case 'claude': return 'Claude Code';+ case 'dsh': return 'DeepSeek Harness';case 'pi': return 'Pi';case 'qoder': return 'Qoder';default: return agentId.toLowerCase().includes('cursor') ? 'Cursor' : language === 'zh' ? '本机 Agent' : 'Local Agent';}}-export function agentBrand(agentId: string): 'codex' | 'claude-code' | 'qoder' | 'pi' | 'agent' {+export function agentBrand(agentId: string): 'codex' | 'claude-code' | 'qoder' | 'pi' | 'dsh' | 'agent' {switch (agentEcosystem(agentId)) {case 'codex': return 'codex';case 'claude': return 'claude-code';+ case 'dsh': return 'dsh';case 'pi': return 'pi';case 'qoder': return 'qoder';default: return 'agent';@@ -54,6 +58,7 @@ export function surfaceName(surface: AgentModelSurface): string {case 'codex_desktop': return 'Codex Desktop';case 'codex_cli': return 'Codex CLI';case 'claude_cli': return 'Claude Code CLI';+ case 'dsh_cli': return 'DeepSeek Harness';case 'pi_cli': return 'Pi CLI';case 'qoder_cli': return 'Qoder CLI';default: return surface;diff --git a/apps/desktop/src/features/agents/editor-state.ts b/apps/desktop/src/features/agents/editor-state.tsindex 816fd397..0ceab240 100644--- a/apps/desktop/src/features/agents/editor-state.ts+++ b/apps/desktop/src/features/agents/editor-state.ts@@ -72,7 +72,7 @@ export function agentEditorSeed(const currentModel = facet === 'model' ? agentModelStatus(agent)?.current_selection : undefined;const codex = currentModel?.mode === 'codex_default' ? currentModel : undefined;const claude = currentModel?.mode === 'claude_launcher' ? currentModel : undefined;- const qoder = (currentModel?.mode === 'qoder_additional' || currentModel?.mode === 'pi_additional') ? currentModel : undefined;+ const qoder = (currentModel?.mode === 'qoder_additional' || currentModel?.mode === 'pi_additional' || currentModel?.mode === 'dsh_additional') ? currentModel : undefined;const collaboration = facet === 'collaboration'&& selection&& 'trigger_mode' in selection@@ -88,7 +88,7 @@ export function agentEditorSeed(fixedModels: currentModel && 'fixed_models' in currentModel ? currentModel.fixed_models : [],nativeModelMode: codex?.native_model_mode ?? 'hiroute_only',allowedPlanIds: codex?.allowed_plan_ids ?? qoder?.allowed_plan_ids- ?? (initialPlan && (ecosystem === 'codex' || ecosystem === 'qoder' || ecosystem === 'pi') ? [initialPlan] : []),+ ?? (initialPlan && (ecosystem === 'codex' || ecosystem === 'qoder' || ecosystem === 'pi' || ecosystem === 'dsh') ? [initialPlan] : []),defaultChoice: codex?.default_selection ?? (initialPlan && ecosystem === 'codex'? { kind: 'plan', plan_id: initialPlan } : { kind: 'preserve_native' }),claudePresets: claude?.preset_mappings ?? {@@ -116,7 +116,7 @@ export function sharedClaudePlan(planId: string): AgentClaudePresetMappings {/** Local form completeness only; Preview remains the authority for capabilities and grants. */export function agentModelFormInvalid(agent: Agent | undefined, editorValues: AgentEditorValues, enabledPlanIds: string[]): boolean {if (!agent || agentEcosystem(agent.agent_id) === null) return true;- if (['qoder', 'pi'].includes(agentEcosystem(agent.agent_id) ?? '')) {+ if (['qoder', 'pi', 'dsh'].includes(agentEcosystem(agent.agent_id) ?? '')) {return editorValues.allowedPlanIds.length === 0|| editorValues.allowedPlanIds.some(id => !enabledPlanIds.includes(id));}diff --git a/apps/desktop/src/features/agents/settings-request.ts b/apps/desktop/src/features/agents/settings-request.tsindex c8cb0169..10905410 100644--- a/apps/desktop/src/features/agents/settings-request.ts+++ b/apps/desktop/src/features/agents/settings-request.ts@@ -38,6 +38,9 @@ export function agentSettingsSpec(agent: Agent, facet: AgentFacet, restore: boolpreset_mappings: values.claudePresets,};break;+ case 'dsh':+ settings = { mode: 'dsh_additional', allowed_plan_ids: values.allowedPlanIds, plan_protocols: Object.fromEntries(values.allowedPlanIds.map(id => [id, values.planProtocols?.[id] ?? 'responses'])) };+ break;case 'pi':settings = { mode: 'pi_additional', allowed_plan_ids: values.allowedPlanIds, plan_protocols: Object.fromEntries(values.allowedPlanIds.map(id => [id, values.planProtocols?.[id] ?? 'responses'])) };break;diff --git a/apps/desktop/src/features/agents/types.ts b/apps/desktop/src/features/agents/types.tsindex 68f2b813..40abfc5f 100644--- a/apps/desktop/src/features/agents/types.ts+++ b/apps/desktop/src/features/agents/types.ts@@ -36,7 +36,7 @@ export type CollaborationStatus = {restore_point_ref: string | null;current_selection?: { trigger_mode: AgentCollaborationTriggerMode } | null;};-export type AgentModelSurface = 'codex_cli' | 'codex_desktop' | 'claude_cli' | 'qoder_cli' | 'pi_cli';+export type AgentModelSurface = 'codex_cli' | 'codex_desktop' | 'claude_cli' | 'qoder_cli' | 'pi_cli' | 'dsh_cli';export type AgentReasoningSelection =| { kind: 'profile'; profile: string }| { kind: 'toggle'; enabled: boolean }@@ -87,7 +87,8 @@ export type QoderModelSelection = {allowed_plan_ids: string[];};export type PiModelSelection = { mode: 'pi_additional'; plan_protocols?: Record<string, 'responses' | 'messages'>; allowed_plan_ids: string[] };-export type AgentModelSelection = CodexModelSelection | ClaudeModelSelection | QoderModelSelection | PiModelSelection;+export type DshModelSelection = { mode: 'dsh_additional'; plan_protocols?: Record<string, 'responses' | 'messages'>; allowed_plan_ids: string[] };+export type AgentModelSelection = CodexModelSelection | ClaudeModelSelection | QoderModelSelection | PiModelSelection | DshModelSelection;export type AgentSurfaceResult = {surface: AgentModelSurface;applied_revision: number;diff --git a/apps/desktop/src/features/device-scan/DeviceScanList.tsx b/apps/desktop/src/features/device-scan/DeviceScanList.tsxindex f046c371..91b63083 100644--- a/apps/desktop/src/features/device-scan/DeviceScanList.tsx+++ b/apps/desktop/src/features/device-scan/DeviceScanList.tsx@@ -23,6 +23,7 @@ export type ComputeScanResult = { items: ComputeScanItem[] };function agentName(agentId: string, language: 'zh' | 'en') {if (agentId.includes('claude')) return 'Claude Code';if (agentId.includes('codex')) return 'Codex';+ if (agentId === 'agent_dsh_default') return 'DeepSeek Harness';if (agentId === 'agent_pi_default') return 'Pi';if (agentId.includes('qoder')) return 'Qoder';return language === 'zh' ? '本机 Agent' : 'Local agent';diff --git a/apps/desktop/src/features/worker-dependencies-state.ts b/apps/desktop/src/features/worker-dependencies-state.tsindex 9c06cfc0..7b944aeb 100644--- a/apps/desktop/src/features/worker-dependencies-state.ts+++ b/apps/desktop/src/features/worker-dependencies-state.ts@@ -1,4 +1,4 @@-export type WorkerHarness = 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi';+export type WorkerHarness = 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi' | 'deepseek_harness';export type WorkerDependencyComponent = 'cli' | 'adapter' | 'node';export type WorkerDependencyCandidateState = 'found' | 'missing' | 'invalid' | 'unavailable';@@ -37,12 +37,12 @@ export type WorkerDependencySelectionRequest = WorkerDependencySelection & {};export function workerDependencyComponents(harness: WorkerHarness): WorkerDependencyComponent[] {- return harness === 'qoder_cli' ? ['cli'] : harness === 'pi' ? ['cli', 'node'] : ['cli', 'adapter', 'node'];+ return (harness === 'qoder_cli' || harness === 'deepseek_harness') ? ['cli'] : harness === 'pi' ? ['cli', 'node'] : ['cli', 'adapter', 'node'];}export function workerDependencySelectionComplete(selection: WorkerDependencySelection | null): boolean {if (!selection?.cli_path) return false;- return selection.harness === 'qoder_cli'+ return (selection.harness === 'qoder_cli' || selection.harness === 'deepseek_harness')? selection.adapter_path == null && selection.node_path == null: selection.harness === 'pi' ? selection.adapter_path == null && Boolean(selection.node_path) : Boolean(selection.adapter_path);}@@ -95,7 +95,7 @@ export function recommendedWorkerDependencies(if (selected) {return {...selected,- ...(harness === 'qoder_cli' ? {} : { node_path: selected.node_path ?? null }),+ ...((harness === 'qoder_cli' || harness === 'deepseek_harness') ? {} : { node_path: selected.node_path ?? null }),expected_selection_revision: workerDependencyRevision(view, harness),};}@@ -104,7 +104,7 @@ export function recommendedWorkerDependencies(return {harness,cli_path: found('cli')?.path ?? '',- ...(harness === 'qoder_cli' ? {} : {+ ...((harness === 'qoder_cli' || harness === 'deepseek_harness') ? {} : {...(harness === 'pi' ? {} : { adapter_path: found('adapter')?.path ?? '' }),node_path: found('node')?.path ?? null,}),@@ -123,13 +123,13 @@ export function workerDependencySelectionState(&& candidate.component === component&& candidate.path === path)?.state: undefined;- const nodeRequired = harness === 'pi' || harness !== 'qoder_cli' && (Boolean(request.node_path)+ const nodeRequired = harness === 'pi' || harness !== 'qoder_cli' && harness !== 'deepseek_harness' && (Boolean(request.node_path)|| (!selected && view.install_hints.some(hint => hint.harness === harness&& hint.component === 'node'&& hint.reason_code === 'worker.dependencies.install_required')));const complete = workerDependencySelectionComplete(request)&& fact('cli', request.cli_path) === 'found'- && (harness === 'qoder_cli' || harness === 'pi' || fact('adapter', request.adapter_path) === 'found')+ && (harness === 'qoder_cli' || harness === 'deepseek_harness' || harness === 'pi' || fact('adapter', request.adapter_path) === 'found')&& (!nodeRequired || fact('node', request.node_path) === 'found');if (selected && complete) return 'configured';if (complete) return 'found';diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsxindex 154d8d55..2987e8b0 100644--- a/apps/desktop/src/plan-editor.tsx+++ b/apps/desktop/src/plan-editor.tsx@@ -17,7 +17,7 @@ import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } fimport { invoke } from '@tauri-apps/api/core';export type Selection = { binding_id: string; reasoning?: { kind: 'profile'; profile: string } | { kind: 'toggle'; enabled: boolean } | { kind: 'budget'; tokens: number } };type Mode = 'fixed_model' | 'smart_saving' | 'free_first';-type Work = { harness: 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi'; protocol: 'responses' | 'messages' };+type Work = { harness: 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi' | 'deepseek_harness'; protocol: 'responses' | 'messages' };type ClassifierAuthHeader = { name: string; value_secret_ref: string };type SmartClassifier = { kind: 'local_rules' } | {kind: 'rest';@@ -135,7 +135,7 @@ function activePlanQualityModels(plan: Plan, candidates: Candidate[]): PlanQuali}return models;}-export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Draft; creating?: boolean; initialBindingId?: string; editingMemory?: PlanEditorMemory; language: 'zh' | 'en'; active?: boolean; refreshVersion?: number; usedBy?: { id: string; name: string; brand: 'codex' | 'claude-code' | 'qoder' | 'pi' | 'agent'; isDefault: boolean }[]; onOpenAgent?: (agentId: string) => void; onOpenSession?: (sessionId: string, requestId: string) => void; onDone: () => Promise<void>; onClose: () => void; onDirty?: (dirty: boolean) => void; onEdit?: () => void; onBusyChange?: (busy: boolean) => void; onOperation?: (operation: PlanOperation | null) => void; onPersisted?: (editor: PersistedEditor<Plan, Draft> | null, action: 'save_draft' | 'publish', identity: PersistenceIdentity, operation: PlanOperation | null) => void }>(function PlanEditor({ plan, draft, creating = false, initialBindingId, editingMemory, language, active = true, refreshVersion = 0, usedBy = [], onOpenAgent, onOpenSession, onDone, onClose, onDirty, onEdit, onBusyChange, onOperation, onPersisted }, ref) {+export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Draft; creating?: boolean; initialBindingId?: string; editingMemory?: PlanEditorMemory; language: 'zh' | 'en'; active?: boolean; refreshVersion?: number; usedBy?: { id: string; name: string; brand: 'codex' | 'claude-code' | 'qoder' | 'pi' | 'dsh' | 'agent'; isDefault: boolean }[]; onOpenAgent?: (agentId: string) => void; onOpenSession?: (sessionId: string, requestId: string) => void; onDone: () => Promise<void>; onClose: () => void; onDirty?: (dirty: boolean) => void; onEdit?: () => void; onBusyChange?: (busy: boolean) => void; onOperation?: (operation: PlanOperation | null) => void; onPersisted?: (editor: PersistedEditor<Plan, Draft> | null, action: 'save_draft' | 'publish', identity: PersistenceIdentity, operation: PlanOperation | null) => void }>(function PlanEditor({ plan, draft, creating = false, initialBindingId, editingMemory, language, active = true, refreshVersion = 0, usedBy = [], onOpenAgent, onOpenSession, onDone, onClose, onDirty, onEdit, onBusyChange, onOperation, onPersisted }, ref) {const en = language === 'en', text = (zh: string, eng: string) => en ? eng : zh;const [editor, setEditor] = useState<Editor>(() => structuredClone(draft?.editor ?? (plan ? reopen(plan) : emptyEditor())));const [draftId] = useState(() => draft?.draft_id ?? 'draft/' + crypto.randomUUID());@@ -513,10 +513,11 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr{editor.delegation_enabled && <div className="field"><label className="field-label">{text('执行任务的 Agent', 'Task execution agent')}</label><p className="field-help">{text('每份计划选择一个执行 Agent,不做自动回退。', 'Choose one execution agent per plan; there is no automatic fallback.')}</p><div className="v3-executors">{([['codex_cli', 'Codex CLI', text('使用 Codex CLI 执行委派任务', 'Use Codex CLI for delegated tasks')],['claude_code', 'Claude Code', text('使用 Claude Code 执行委派任务', 'Use Claude Code for delegated tasks')],+ ['deepseek_harness', 'DeepSeek Harness', text('原生 ACP 任务委派', 'Native ACP task delegation')],['pi', 'Pi', text('使用 Pi 执行委派任务', 'Use Pi for delegated tasks')],['qoder_cli', 'Qoder CLI', text('使用 Qoder CLI 执行委派任务', 'Use Qoder CLI for delegated tasks')],- ] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => { if (editor.work?.harness !== value) update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } }); }}><BrandIcon kind={value === 'codex_cli' ? 'codex' : value === 'claude_code' ? 'claude-code' : value === 'pi' ? 'pi' : 'qoder'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}- {editor.work && (editor.work.harness === 'pi' || editor.work.harness === 'qoder_cli') && <AgentProtocolChoice name={editor.display_name || text('任务路由', 'Task route')} language={language} value={editor.work.protocol} advice={workerProtocolAdvice(editor, options)} onChange={protocol => update({ work: { ...editor.work!, protocol } })} />}+ ] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => { if (editor.work?.harness !== value) update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } }); }}><BrandIcon kind={value === 'codex_cli' ? 'codex' : value === 'claude_code' ? 'claude-code' : value === 'pi' ? 'pi' : value === 'deepseek_harness' ? 'dsh' : 'qoder'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}+ {editor.work && (editor.work.harness === 'pi' || editor.work.harness === 'deepseek_harness' || editor.work.harness === 'qoder_cli') && <AgentProtocolChoice name={editor.display_name || text('任务路由', 'Task route')} language={language} value={editor.work.protocol} advice={workerProtocolAdvice(editor, options)} onChange={protocol => update({ work: { ...editor.work!, protocol } })} />}{editor.work && <WorkerDependencies key={editor.work.harness} harness={editor.work.harness} language={language} active={active && moreSettingsOpen} onOperation={onOperation} />}</div>}</section></Disclosure>diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsxindex 2c61559c..5b0a69db 100644--- a/apps/desktop/src/product/ModelManagementPage.tsx+++ b/apps/desktop/src/product/ModelManagementPage.tsx@@ -88,7 +88,9 @@ function discoveryFailureMessage(code: string, language: 'zh' | 'en'): string {switch (code.toLocaleLowerCase()) {case 'compute.discovery_changed':case 'revision_conflict':+ case 'application.error.revision_conflict':case 'change_preview_stale':+ case 'application.error.change_preview_stale':return zh ? '本机配置或保存依据已发生变化,请重新扫描后再接入。' : 'The local configuration or save context changed. Scan again before connecting it.';case 'compute.discovery_unavailable':return zh ? '暂时无法重新读取这项配置,请重新扫描。' : 'This configuration cannot be read right now. Scan again.';@@ -946,7 +948,7 @@ export function ModelManagementPage({const subscriptionSaving = subscriptionAction === 'saving';const discoverySaving = discoveryAction === 'saving';const scanWorking = subscriptionWorking || discoveryAction !== null;- const discoveryFailureNeedsRescan = ['compute.discovery_changed', 'compute.discovery_unavailable', 'revision_conflict', 'change_preview_stale']+ const discoveryFailureNeedsRescan = ['compute.discovery_changed', 'compute.discovery_unavailable', 'revision_conflict', 'application.error.revision_conflict', 'change_preview_stale', 'application.error.change_preview_stale'].includes(discoveryError.toLocaleLowerCase());const discoveryFailureCanRetry = Boolean(discoveryError&& !['compute.discovery_not_importable', 'registered_option_unavailable'].includes(discoveryError.toLocaleLowerCase()));diff --git a/apps/desktop/src/ui/BrandIcon.tsx b/apps/desktop/src/ui/BrandIcon.tsxindex 88c061f8..3530125a 100644--- a/apps/desktop/src/ui/BrandIcon.tsx+++ b/apps/desktop/src/ui/BrandIcon.tsx@@ -6,14 +6,16 @@ import codexLight from './assets/codex-light.png?inline';import claudeCode from './assets/claude-code.svg';import qoder from './assets/qoder.svg';import pi from './assets/pi.svg';+import dsh from './assets/providers/deepseek.svg';-export type BrandKind = 'codex' | 'claude-code' | 'qoder' | 'pi' | 'agent' | 'model';+export type BrandKind = 'codex' | 'claude-code' | 'qoder' | 'pi' | 'dsh' | 'agent' | 'model';export function agentBrandFromId(agentId: string): BrandKind {const normalized = agentId.toLowerCase();if (normalized.includes('codex')) return 'codex';if (normalized.includes('claude')) return 'claude-code';if (normalized.includes('qoder')) return 'qoder';+ if (normalized === 'agent_dsh_default') return 'dsh';if (normalized === 'agent_pi_default') return 'pi';return 'agent';}@@ -49,9 +51,9 @@ export function BrandIcon({);}- if (kind === 'qoder' || kind === 'pi') {+ if (kind === 'qoder' || kind === 'pi' || kind === 'dsh') {return <span className={classes} data-size={size} data-brand={kind} {...accessibility}>- <img src={kind === 'pi' ? pi : qoder} alt="" />+ <img src={kind === 'pi' ? pi : kind === 'dsh' ? dsh : qoder} alt="" /></span>;}diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex 047c72c5..d14ee7d0 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -13,6 +13,7 @@ proves native authorization, persistence, process cleanup or real model calls.| Configure Claude routing and collaboration | `claude.enable.shared-presets`, `agent.configuration.independent-facets`, `claude.collaboration.check-before-save`, `claude.collaboration.retry-preserves-edit` | Ordinary Claude entry and account Default limitations remain clear; prerequisite checks precede mutation; retry preserves edits. || Enable, recover or disable Qoder task collaboration | `qoder.collaboration.enable-without-model`, `qoder.collaboration.retry-and-restore` | No model connection or published Plan is required; required capability checks happen during save. Login and changed-Skill failures retain edits and enabled collaboration with the shared retry action; restore keeps model configuration unchanged. || Add and adjust Qoder model routes | `qoder.routing.additional-plans`, `qoder.routing.adjust-and-restore` | Cancelled drafts do not write; only selected Plans are submitted; unavailable choices stay visible; token changes and independent restores keep the other facet. Native default/provider preservation and real model calls require production acceptance. |+| Remove Pi or DSH routes used by the native default | `pi.routing.default-in-use`, `dsh.routing.default-in-use` | A blocked removal retains model routes and task collaboration, directs the user to their selected client, and never changes the native default or calls a model. Both reuse the additional-provider fixture. || Configure Agents through common interactions | `agent.configuration.shared-interactions`; [Agent status projection](agent-status.test.mjs) | Codex, Claude Code and Qoder show configured routing without verification badges or extra check buttons. Ordinary navigation never probes a model; backend verification facts cannot hide actual configuration/recovery state. || Diagnose or recover an Agent | `codex.restore.conflict-active`, `agent.recovery.non-runnable` | A file conflict preserves current access and unrelated settings; executable diagnostics do not hide recovery. || Choose or replace a Worker installation | `worker.discovery.visible-only`, `worker.installation.harness-isolation`, `worker.installation.replace`, `worker.installation.latest-edit` in [routing/Worker scenarios](v3/browser/routing-worker-scenarios.mjs) | Discovery follows visible configuration; installations stay independent; one explicit save commits the latest edit exactly once. |diff --git a/apps/desktop/tests/agent-settings-request.test.mjs b/apps/desktop/tests/agent-settings-request.test.mjsindex 1856272e..e0751b81 100644--- a/apps/desktop/tests/agent-settings-request.test.mjs+++ b/apps/desktop/tests/agent-settings-request.test.mjs@@ -117,7 +117,7 @@ test('collaboration-only Qoder and cross-ecosystem selections cannot authorize m}});-for (const ecosystem of ['qoder', 'pi']) test(`${ecosystem} adds only selected routes and keeps token rotation and both restores independent`, () => {+for (const ecosystem of ['qoder', 'pi', 'dsh']) test(`${ecosystem} adds only selected routes and keeps token rotation and both restores independent`, () => {const native = { ...qoder, agent_id: `agent_${ecosystem}_default`, context_id: `context/${ecosystem}`,settings: { collaboration: { ...qoder.settings.collaboration, restore_point_ref: `restore/${ecosystem}-skill` } } };const capable = { ...native, settings: { state: 'not_configured', collaboration: native.settings.collaboration } };@@ -201,7 +201,7 @@ test('editing model routes retains distinct Codex authorization and Claude preseassert.equal(agentModelFormInvalid(claude, { ...EMPTY_EDITOR_VALUES, fixedModels: [fixed] }, []), false, 'an existing Claude fixed model can survive without a preset route');});-for (const ecosystem of ['qoder', 'pi']) test(`${ecosystem} saves each selected plan protocol and excludes deselected plans`, () => {+for (const ecosystem of ['qoder', 'pi', 'dsh']) test(`${ecosystem} saves each selected plan protocol and excludes deselected plans`, () => {const capable = { ...qoder, agent_id: `agent_${ecosystem}_default`, context_id: `context/${ecosystem}`, settings: { state: 'not_configured' } };const values = { ...draft.values, planProtocols: { 'route/a': 'messages', 'route/b': 'responses', 'removed': 'messages' } };const result = agentSettingsSpec(capable, 'model', false, { ...draft, values });diff --git a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjsindex cd5946e9..d99d70f2 100644--- a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs@@ -526,14 +526,18 @@ const scenarios = [const pick = () => [...dialog().querySelectorAll('[data-agent-plan-id] input')].slice(0, 2).forEach(input => input.click());pick(); await tick();assert(dialog().textContent.includes('当前默认模型保持不变') && dialog().textContent.includes('/model'), 'Additional routing does not explain native preservation and selection');- assert(!dialog().querySelector('[data-agent-default], [data-client-model-id], [data-agent-fixed-models], select'), 'Qoder borrowed native model, source or default controls');+ assert(!dialog().querySelector('[data-agent-default], [data-client-model-id], [data-agent-fixed-models]'), 'Qoder borrowed native model, source or default controls');+ assert(dialog().querySelectorAll('[data-plan-protocol] select').length === 2, 'Each selected route needs its own protocol choice');[...dialog().querySelectorAll('button')].find(button => button.textContent === '取消').click(); await tick();assert(configureSpecs().length === 0 && !dialog(), 'Cancelling Qoder model draft changed configuration');await openEditor('model'); pick(); await tick();const selected = [...dialog().querySelectorAll('[data-agent-plan-id]')].filter(row => row.querySelector('input').checked).map(row => row.dataset.agentPlanId);+ changeSelect(dialog().querySelector(`[data-agent-plan-id="${selected[1]}"] [data-plan-protocol] select`), 'messages');+ await tick();await save();const spec = configureSpecs().at(-1);- assert(JSON.stringify(spec.model.settings) === JSON.stringify({ mode: 'qoder_additional', allowed_plan_ids: selected }), 'Qoder submitted another ecosystem or changed the route set');+ assert(JSON.stringify(spec.model.settings) === JSON.stringify({ mode: 'qoder_additional', allowed_plan_ids: selected,+ plan_protocols: { [selected[0]]: 'responses', [selected[1]]: 'messages' } }), 'Qoder changed the ecosystem, selected routes or their independent protocols');assert(spec.collaboration.intent === 'keep' && !spec.restore_native_model, 'Model save changed collaboration or a native default');assert(!c().commands.some(({ command }) => /subscription|discovered_model|model_catalog/.test(command)), 'Additional routing opened model discovery or import');assert(calls('check_agent_live').length === 0, 'Saving routes implicitly invoked a model');@@ -588,6 +592,26 @@ const scenarios = [await until(() => configureSpecs().some(spec => spec.collaboration.intent === 'restore'), 'independent collaboration restore');assert(configureSpecs().at(-1).model.intent === 'keep' && agent.settings.current_selection.mode === 'qoder_additional', 'Collaboration restore removed model routes');}),+ ...['pi', 'dsh'].map(ecosystem => scenario(`${ecosystem}.routing.default-in-use`, ['agent-recovery'], `${ecosystem} preserves a route used by its native default and directs recovery to the selected client`, async () => {+ c().reset(); c().agents = c().additionalRouted(ecosystem); await tick();+ await until(() => facet('model')?.textContent === '调整' && !facet('model').disabled, 'additional model routing');+ const agent = c().agents.agents[0];+ const before = structuredClone(agent.settings);+ c().handlers.preview_agent_settings = () => ({+ preview: { applicable: false, blockers: [{ reason: 'additional_default_in_use' }] }, mutation: null,+ });+ [...document.querySelectorAll('.detail-section-head button')].find(button => button.textContent === '停用').click();+ await until(() => document.querySelector('.agent-feedback')?.textContent.includes('当前默认模型仍引用'), 'default reference recovery');+ const guidance = document.querySelector('.agent-feedback').textContent;+ assert(guidance.includes('所选客户端中切换到其他模型') && guidance.includes('HiRoute 不会替你更改默认模型'), 'Recovery did not direct the user to their selected client');+ assert(!guidance.includes('Pi 中') && !guidance.includes('/model'), 'Shared recovery assumed another ecosystem or a CLI-only selector');+ assert(c().operations.length === 0 && JSON.stringify(agent.settings) === JSON.stringify(before), 'Blocked removal changed model routes or task collaboration');+ assert(configureSpecs().at(-1).collaboration.intent === 'keep', 'Model recovery tried to restore task collaboration');+ assert(calls('check_agent_live').length === 0, 'Recovery called a model');+ const spec = configureSpecs().at(-1);+ assert(spec.context_id === agent.context_id && spec.model.intent === 'restore'+ && spec.model.restore_point_ref === before.restore_point_ref, 'Removal targeted another client or restore point');+ })),scenario('qoder.routing.resume-pending', ['qoder', 'qoder-model-routing'], 'Qoder resumes the original incomplete model operation without replacing task collaboration', async () => {c().reset(); c().agents = c().qoderRouted();const agent = c().agents.agents[0];diff --git a/apps/desktop/tests/v3/browser/agent-trust.tsx b/apps/desktop/tests/v3/browser/agent-trust.tsxindex 5cdbe67e..5fd28566 100644--- a/apps/desktop/tests/v3/browser/agent-trust.tsx+++ b/apps/desktop/tests/v3/browser/agent-trust.tsx@@ -103,19 +103,19 @@ function splitCodexStatus(): AgentSnapshot {return snapshot;}-function qoder(configured: boolean): AgentSnapshot {- const context = `agent-context/qoder/sha256:${'a'.repeat(64)}`;+function additionalAgent(configured: boolean, ecosystem: 'qoder' | 'pi' | 'dsh' = 'qoder'): AgentSnapshot {+ const context = `agent-context/${ecosystem}/sha256:${'a'.repeat(64)}`;return {trusted_authority: true, plans: { plans: [] },agents: [{- agent_id: 'agent_qoder_default', version: 'fixture', context_id: context,+ agent_id: `agent_${ecosystem}_default`, version: 'fixture', context_id: context,configuration_state: configured ? 'configured' : 'not_configured',- available_surfaces: ['qoder_cli'], native_model_catalog: null, status_error: null,+ available_surfaces: [`${ecosystem}_cli`], native_model_catalog: null, status_error: null,settings: {state: 'not_configured', model_verified: false, restore_point_ref: null, current_selection: null,collaboration: {state: configured ? 'configured' : 'not_configured',- restore_point_ref: configured ? 'task-restore/qoder' : null,+ restore_point_ref: configured ? `task-restore/${ecosystem}` : null,current_selection: configured ? { trigger_mode: 'explicit' } : null,},},@@ -123,17 +123,17 @@ function qoder(configured: boolean): AgentSnapshot {};}-function qoderRouted(): AgentSnapshot {- const snapshot = qoder(true);+function additionalRouted(ecosystem: 'qoder' | 'pi' | 'dsh' = 'qoder'): AgentSnapshot {+ const snapshot = additionalAgent(true, ecosystem);snapshot.plans = structuredClone(readyAgents.plans);- const agent = modelAgent(snapshot, 'agent_qoder_default');+ const agent = modelAgent(snapshot, `agent_${ecosystem}_default`);const plans = snapshot.plans.plans.slice(0, 2);agent.settings = {- ...agent.settings, state: 'configured', applied_revision: 23, restore_point_ref: 'model-restore/qoder',- current_selection: { mode: 'qoder_additional', allowed_plan_ids: plans.map(plan => plan.agent_plan_id) },- live_check_targets: [{ context_id: agent.context_id!, surface: 'qoder_cli', expected_applied_revision: 23,+ ...agent.settings, state: 'configured', applied_revision: 23, restore_point_ref: `model-restore/${ecosystem}`,+ current_selection: { mode: `${ecosystem}_additional`, allowed_plan_ids: plans.map(plan => plan.agent_plan_id) },+ live_check_targets: [{ context_id: agent.context_id!, surface: `${ecosystem}_cli`, expected_applied_revision: 23,client_model_ids: plans.map(plan => `fixture-hiroute/${plan.model_alias}`) }],- surface_results: [{ surface: 'qoder_cli', applied_revision: 23, state: 'not_verified', reason_code: null }],+ surface_results: [{ surface: `${ecosystem}_cli`, applied_revision: 23, state: 'not_verified', reason_code: null }],};return snapshot;}@@ -156,9 +156,10 @@ const control = {protectedCodex,cliOnly: () => freshCodex('codex_cli'),splitCodexStatus,- qoderFresh: () => qoder(false),- qoderConfigured: () => qoder(true),- qoderRouted,+ qoderFresh: () => additionalAgent(false),+ qoderConfigured: () => additionalAgent(true),+ qoderRouted: () => additionalRouted(),+ additionalRouted,};Object.assign(window, { agentTrust: control });diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjsindex 439cf1f7..9d6970c4 100644--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs@@ -24,6 +24,8 @@ export const agentTrustRequired = ['codex.restore.conflict-active','qoder.routing.additional-plans','qoder.routing.adjust-and-restore','qoder.routing.resume-pending',+ 'pi.routing.default-in-use',+ 'dsh.routing.default-in-use','agent.diagnostics.configuration-state','codex.routing.unproven-native-model'];diff --git a/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs b/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjsindex 9010bc2f..e2a69b09 100644--- a/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs@@ -191,19 +191,35 @@ const scenarios = [assert(calls('apply_compute_save').length === 0 && calls('cancel_model_connection_check').length === 0, 'Prepare close wrote or called cancellation');}],['stale discovery Preview requires a new scan and Prepare', async () => {- await fresh(control => { control.handlers.preview_compute_save = () => { throw { code: 'CHANGE_PREVIEW_STALE' }; }; });- await scan(); await connect('智谱 Coding Plan');- await until(() => button('保存接入'), 'discovery prepared');- await click('保存接入');- await until(() => button('重新扫描'), 'stale requires rescan');- assert(!button('保存接入') && calls('apply_compute_save').length === 0, 'Stale candidate still saveable');- const next = { ...c().discovered, discovery: { discovery_ref: `discovery/${'b'.repeat(64)}`, discovery_revision: '2' } };- c().handlers.compute_scan = () => ({ items: [next] });- delete c().handlers.preview_compute_save;- await click('重新扫描'); await until(() => text().includes('可复用的订阅'), 'rescan complete');- await connect('智谱 Coding Plan');- await until(() => button('保存接入'), 'new candidate prepared');- assert(calls('prepare_discovered_model_connection').at(-1).payload.discovery.discovery_ref === next.discovery.discovery_ref, 'Old discovery reused');+ for (const [stage, code] of [+ ['preview_compute_save', 'CHANGE_PREVIEW_STALE'],+ ['apply_compute_save', 'application.error.change_preview_stale'],+ ['preview_compute_save', 'application.error.revision_conflict'],+ ]) {+ await fresh(control => {+ control.handlers[stage] = () => { throw {+ source: 'backend',+ envelope: { error: { code: code.split('.').at(-1).toLocaleUpperCase(), message_key: code }, operation: null },+ }; };+ });+ await scan(); await connect('智谱 Coding Plan');+ await until(() => button('保存接入'), 'discovery prepared');+ await click('保存接入');+ await until(() => button('重新扫描'), 'stale requires rescan');+ assert(text().includes('请重新扫描后再接入'), 'Stale discovery did not explain the recovery action');+ assert(!button('保存接入') && c().changes === 0, 'Stale candidate was saved');+ assert(calls('apply_compute_save').length === (stage === 'apply_compute_save' ? 1 : 0), 'Unexpected Apply attempt');+ const next = { ...c().discovered, discovery: { discovery_ref: `discovery/${'b'.repeat(64)}`, discovery_revision: '2' } };+ c().handlers.compute_scan = () => ({ items: [next] });+ delete c().handlers[stage];+ await click('重新扫描'); await until(() => text().includes('可复用的订阅'), 'rescan complete');+ await connect('智谱 Coding Plan');+ await until(() => button('保存接入'), 'new candidate prepared');+ assert(calls('prepare_discovered_model_connection').at(-1).payload.discovery.discovery_ref === next.discovery.discovery_ref, 'Old discovery reused');+ await click('保存接入');+ await until(() => text().includes('模型接入已保存'), 'refreshed discovery saved');+ assert(c().changes === 1, 'Fresh discovery was not saved exactly once');+ }}],['late admitted save failure does not close a newer scan', async () => {const late = deferred();diff --git a/apps/desktop/tests/worker-dependencies-state.test.mjs b/apps/desktop/tests/worker-dependencies-state.test.mjsindex 6dc5b467..6e103003 100644--- a/apps/desktop/tests/worker-dependencies-state.test.mjs+++ b/apps/desktop/tests/worker-dependencies-state.test.mjs@@ -37,43 +37,43 @@ test('detection recommends but never invents a persisted selection', () => {assert.deepEqual(detected.selected, []);});-test('Qoder recommends and recognizes a saved native CLI without adapter or Node fields', () => {- const selected = { harness: 'qoder_cli', cli_path: '/bin/qodercli' };+for (const native of ['qoder_cli','deepseek_harness']) test(`${native} recommends and recognizes a saved native CLI without adapter or Node fields`, () => {+ const selected = { harness: native, cli_path: '/bin/qodercli' };const detected = view({- selection_revisions: [{ harness: 'qoder_cli', revision: 7 }],+ selection_revisions: [{ harness: native, revision: 7 }],candidates: [...view().candidates,- { harness: 'qoder_cli', component: 'cli', path: '/bin/qodercli', source: 'path', state: 'found' },+ { harness: native, component: 'cli', path: '/bin/qodercli', source: 'path', state: 'found' },],});- const request = recommendedWorkerDependencies(detected, 'qoder_cli');+ const request = recommendedWorkerDependencies(detected, native);assert.deepEqual(request, { ...selected, expected_selection_revision: 7 });- assert.deepEqual(workerDependencyComponents('qoder_cli'), ['cli']);+ assert.deepEqual(workerDependencyComponents(native), ['cli']);assert.equal(workerDependencySelectionComplete(request), true);- assert.equal(workerDependencySelectionState(detected, 'qoder_cli'), 'found');+ assert.equal(workerDependencySelectionState(detected, native), 'found');assert.deepEqual(detected.selected, []);const saved = { ...detected, selected: [selected] };- assert.deepEqual(recommendedWorkerDependencies(saved, 'qoder_cli'), request);+ assert.deepEqual(recommendedWorkerDependencies(saved, native), request);assert.equal(workerDependencySelectionMatches(saved, request), true);- assert.equal(workerDependencySelectionState(saved, 'qoder_cli'), 'configured');+ assert.equal(workerDependencySelectionState(saved, native), 'configured');});-test('a missing selected Qoder CLI stays incomplete and does not fall back to a discovered installation', () => {- const selected = { harness: 'qoder_cli', cli_path: '/old/qoder' };+for (const native of ['qoder_cli','deepseek_harness']) test(`a missing selected ${native} CLI stays incomplete and does not fall back to a discovered installation`, () => {+ const selected = { harness: native, cli_path: '/old/qoder' };const detected = view({- selection_revisions: [{ harness: 'qoder_cli', revision: 7 }],+ selection_revisions: [{ harness: native, revision: 7 }],selected: [selected],candidates: [- { harness: 'qoder_cli', component: 'cli', path: '/old/qoder', source: 'selected', state: 'missing' },- { harness: 'qoder_cli', component: 'cli', path: '/bin/qodercli', source: 'path', state: 'found' },+ { harness: native, component: 'cli', path: '/old/qoder', source: 'selected', state: 'missing' },+ { harness: native, component: 'cli', path: '/bin/qodercli', source: 'path', state: 'found' },],});- assert.deepEqual(recommendedWorkerDependencies(detected, 'qoder_cli'), {+ assert.deepEqual(recommendedWorkerDependencies(detected, native), {...selected, expected_selection_revision: 7,});- assert.equal(workerDependencySelectionState(detected, 'qoder_cli'), 'incomplete');+ assert.equal(workerDependencySelectionState(detected, native), 'incomplete');assert.equal(workerDependencySelectionMatches(detected, {- harness: 'qoder_cli', cli_path: '/bin/qodercli', expected_selection_revision: 7,+ harness: native, cli_path: '/bin/qodercli', expected_selection_revision: 7,}), false);});diff --git a/assets/agent-profiles/current/profile-seed.json b/assets/agent-profiles/current/profile-seed.jsonindex a1a9b172..dc5eba02 100644--- a/assets/agent-profiles/current/profile-seed.json+++ b/assets/agent-profiles/current/profile-seed.json@@ -1 +1 @@-{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/1","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/1","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"dsh-responses-v1","integration_profile_ref":"builtin/dsh-responses/v1","kind":"deepseek_harness","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}diff --git a/assets/release-facts/current/bundle/agent-profiles.json b/assets/release-facts/current/bundle/agent-profiles.jsonindex 8d05ab49..92a0c6a9 100644--- a/assets/release-facts/current/bundle/agent-profiles.json+++ b/assets/release-facts/current/bundle/agent-profiles.json@@ -1 +1 @@-{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"dsh-responses-v1","integration_profile_ref":"builtin/dsh-responses/v1","kind":"deepseek_harness","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}diff --git a/contracts/cli/agent-plan-catalog-query.v2.schema.json b/contracts/cli/agent-plan-catalog-query.v2.schema.jsonindex 80b36d7b..7ef9a1ac 100644--- a/contracts/cli/agent-plan-catalog-query.v2.schema.json+++ b/contracts/cli/agent-plan-catalog-query.v2.schema.json@@ -442,7 +442,8 @@"codex_cli","claude_code","qoder_cli",- "pi"+ "pi",+ "deepseek_harness"]},"protocol": {diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.jsonindex 964ec251..3fa92164 100644--- a/contracts/cli/contract-set.v1.json+++ b/contracts/cli/contract-set.v1.json@@ -3,7 +3,7 @@"files": {"agent-check-request.v1.schema.json": "sha256:fbd9e9b19282a5ed8c3e30b5ae16538bc01318a70e4bb7c7a55e8e0472553feb","agent-launch-descriptor-request.v1.schema.json": "sha256:28f2f9d2d7f9a1618bea0f13383002429bc9e0ff56166cbee86958a245d0fd48",- "agent-plan-catalog-query.v2.schema.json": "sha256:fae6bcd7e9ed4ab480c2bfe055d7bb3422977b7748374d6063c100eb7db4bff4",+ "agent-plan-catalog-query.v2.schema.json": "sha256:bcc84c5271cc6f78fda86371a850b5eaf7d456b0fcc7666626e5c39c08677647","coverage-manifest.v1.json": "sha256:76d8776f13d953fd0b1c0387ba877c30fba7ecf564d927d131cb7e76b3f5a822","delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878","delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93",@@ -19,10 +19,10 @@"manifest.v1.json": "sha256:c602e9b661621403bc05405674f5522604be0e716a886673776199492f686f75","operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f","operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850",- "plan-content-change.v2.schema.json": "sha256:fa5f868e137901db656ff833f022377fc22d64d10d5108ab3bdb5bc0d11812f0",- "plan-draft-change.v1.schema.json": "sha256:d3c5b3371af4d2ef939a22315717fded032bc6343ee672e9fae84ea9067c312a",- "plan-editor.v2.schema.json": "sha256:63d84d21f5fa67cd63d68b0de141ee9b2109905780e00a98ffd2b6d47bebd5f5",- "plan-lifecycle-change.v1.schema.json": "sha256:5e4009cafa5d2f75328ec4a7ce689a8feff02d4494e8b8721d3424148eb7713f",+ "plan-content-change.v2.schema.json": "sha256:dccd43664a3d5c3a8856f02e54aaf33fc9b065ad4efa1c2904ede24659b0ce3c",+ "plan-draft-change.v1.schema.json": "sha256:b122bbc11b2b0ea722c3b36a70ad9ecffa70aef5fa7da2941bac9a3df41feac1",+ "plan-editor.v2.schema.json": "sha256:5bca80444d0ab798740d7b598aaecbdcb05b19f0337fc04cdf9e880ce691722f",+ "plan-lifecycle-change.v1.schema.json": "sha256:ef72b9b964d5e3ced696886d744d3ba69949c5da20cfbb244c55f11dc1aec801","planned-manifest.v1.json": "sha256:eac0c7583245a881de141f9b8d853a86efb3f9ef8fa9a3ffb3ed75d759467072","session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44","session-lookup.v1.schema.json": "sha256:0c9e0ea31bdde7f720a9a17e8dc175902a20b3fb92abc21ce4bdae9fc3d97587",@@ -32,8 +32,8 @@"work-plan-list-request.v1.schema.json": "sha256:d50adc8e139cbed719fcec6412c796a7cf4d4f280dd7a56c525619f72c26c58d","worker-cancel-request.v1.schema.json": "sha256:f731e6a6be762d409a53afe9697be105d0debb89fe5e28be96b15ae03b31dfdc","worker-continue-request.v1.schema.json": "sha256:cfe89487d3524061dd277a97b11291fcd0db4a0a0ca333118023628ab7d61b3b",- "worker-dependencies-discover-request.v1.schema.json": "sha256:383af1b2f41e8d5210a1a8f77238dcc54938868846bb472fdb5d9dcc5e5ca61d",- "worker-dependencies-select-request.v1.schema.json": "sha256:af583e55e3199755fc6e7a7248fa07672e120273a0d5e81792cc1687e897e91e",+ "worker-dependencies-discover-request.v1.schema.json": "sha256:a585c2c179b5349a0491b63bebf41cd72308054fee6b9aa4f047a19847575423",+ "worker-dependencies-select-request.v1.schema.json": "sha256:72518d78c18877ac30360fa29ca4f510dca90e2603fc579dd0e037167b311795","worker-exec-request.v1.schema.json": "sha256:78bfea83b08e595ad4d4b5a5a20884ad9ebb34bb05e5ceed966f9e8e16f4d0fa","worker-list-request.v1.schema.json": "sha256:f1a2b5900b0412d8d561a5925a6f9489b495e74c41f386a3504175b2be3aff64","worker-plans-request.v1.schema.json": "sha256:a7f2d13869ab542223bf51eef4f0c1a05a4c8afef43f202165fd3025a2ab72c1",diff --git a/contracts/cli/plan-content-change.v2.schema.json b/contracts/cli/plan-content-change.v2.schema.jsonindex cdc73585..d5f35aaa 100644--- a/contracts/cli/plan-content-change.v2.schema.json+++ b/contracts/cli/plan-content-change.v2.schema.json@@ -442,7 +442,8 @@"codex_cli","claude_code","qoder_cli",- "pi"+ "pi",+ "deepseek_harness"]},"protocol": {diff --git a/contracts/cli/plan-draft-change.v1.schema.json b/contracts/cli/plan-draft-change.v1.schema.jsonindex cd56396e..73fa0a75 100644--- a/contracts/cli/plan-draft-change.v1.schema.json+++ b/contracts/cli/plan-draft-change.v1.schema.json@@ -442,7 +442,8 @@"codex_cli","claude_code","qoder_cli",- "pi"+ "pi",+ "deepseek_harness"]},"protocol": {diff --git a/contracts/cli/plan-editor.v2.schema.json b/contracts/cli/plan-editor.v2.schema.jsonindex 5fbae689..0da1525f 100644--- a/contracts/cli/plan-editor.v2.schema.json+++ b/contracts/cli/plan-editor.v2.schema.json@@ -442,7 +442,8 @@"codex_cli","claude_code","qoder_cli",- "pi"+ "pi",+ "deepseek_harness"]},"protocol": {diff --git a/contracts/cli/plan-lifecycle-change.v1.schema.json b/contracts/cli/plan-lifecycle-change.v1.schema.jsonindex 0b5bb681..ddc35390 100644--- a/contracts/cli/plan-lifecycle-change.v1.schema.json+++ b/contracts/cli/plan-lifecycle-change.v1.schema.json@@ -442,7 +442,8 @@"codex_cli","claude_code","qoder_cli",- "pi"+ "pi",+ "deepseek_harness"]},"protocol": {diff --git a/contracts/cli/worker-dependencies-discover-request.v1.schema.json b/contracts/cli/worker-dependencies-discover-request.v1.schema.jsonindex 230c3f0d..c408d4ab 100644--- a/contracts/cli/worker-dependencies-discover-request.v1.schema.json+++ b/contracts/cli/worker-dependencies-discover-request.v1.schema.json@@ -8,7 +8,8 @@"codex_cli","claude_code","qoder_cli",- "pi"+ "pi",+ "deepseek_harness"]}},diff --git a/contracts/cli/worker-dependencies-select-request.v1.schema.json b/contracts/cli/worker-dependencies-select-request.v1.schema.jsonindex ab7326d6..dc8eea37 100644--- a/contracts/cli/worker-dependencies-select-request.v1.schema.json+++ b/contracts/cli/worker-dependencies-select-request.v1.schema.json@@ -27,7 +27,10 @@"if": {"properties": {"harness": {- "const": "qoder_cli"+ "enum": [+ "qoder_cli",+ "deepseek_harness"+ ]}}},@@ -52,7 +55,8 @@"codex_cli","claude_code","qoder_cli",- "pi"+ "pi",+ "deepseek_harness"]},"node_path": {diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.jsonindex d9f1a33a..9bde4e05 100644--- a/contracts/compatibility-support.v1.json+++ b/contracts/compatibility-support.v1.json@@ -162,6 +162,9 @@"hiroute.diagnostic-settings/v1","hiroute.diagnostic-status/v1","hiroute.discovered-model-candidate/v1",+ "hiroute.dsh-additional-model/v1",+ "hiroute.dsh-native-restore/v2",+ "hiroute.dsh-public-native-resources/v1","hiroute.empty-request/v1","hiroute.fixed-local-id/v2","hiroute.frozen-candidate-ledger/v1",@@ -308,6 +311,7 @@"hiroute.session-store-status/v1","hiroute.settings-claude-model-file/v1","hiroute.settings-codex-model-file/v1",+ "hiroute.settings-dsh-model-file/v1","hiroute.settings-login-item/v1","hiroute.settings-model-publication/v1","hiroute.settings-pi-model-file/v1",@@ -992,7 +996,7 @@"field": "context_window_tokens","mode": "recovery_read_only","owner": "agent-connections",- "reason": "A descriptor reconstructed from a pre-window immutable settings operation has no managed context policy. It retains that operation’s behavior until settings are saved again.",+ "reason": "A descriptor reconstructed from a pre-window immutable settings operation has no managed context policy. It retains that operation\u2019s behavior until settings are saved again.","removal_condition": "Retire with the pre-window settings operation recovery reader.","allowed_paths": ["crates/domain/src/agents/managed_launch.rs",@@ -1083,13 +1087,15 @@},{"contract": "hiroute.delegation-native-root/v1",- "field": "current runtime task/run record_json identity witness for a cancelled Qoder acceptance task",+ "field": "current runtime task/run record_json identity witness for a cancelled native acceptance task","mode": "frozen_fixture","owner": "worker-product-acceptance",- "reason": "Cancellation does not grant successful-Continue eligibility. The opt-in fixture reads only its own runtime.db in read-only mode with exact workspace/task/run keys, verifies the task-owned context descriptor, Qoder harness, cancelled state, completed cleanup and matching native/ACP identity, then locates that exact native transcript. It never scans a daily database or changes the production Continue reader.",+ "reason": "Cancellation does not grant successful-Continue eligibility. The opt-in fixture reads only its own runtime.db in read-only mode with exact workspace/task/run keys, verifies the task-owned context descriptor, selected native harness, cancelled state, completed cleanup and matching native/ACP identity, then locates that exact native transcript. It never scans a daily database or changes the production Continue reader.","removal_condition": "Replace this test-only current-storage reader when a public exact-native-session identity projection can establish cancellation history retention independently of successful-Continue material; update the fixture if the task/run storage contract changes.","allowed_paths": ["crates/daemon/tests/support/qoder_native_context.py",+ "crates/daemon/tests/support/native_task_witness.py",+ "crates/daemon/tests/support/dsh_native_context.py","scripts/test-qoder-product.py","tools/product-e2e/tests/QODER_DELEGATION.md"]diff --git a/crates/application-api/src/agent_settings.rs b/crates/application-api/src/agent_settings.rsindex 54d7cb63..d2c6b767 100644--- a/crates/application-api/src/agent_settings.rs+++ b/crates/application-api/src/agent_settings.rs@@ -242,6 +242,7 @@ impl AgentModelSettingsStatusV2 {AgentModelSurfaceV2::CodexCli | AgentModelSurfaceV2::CodexDesktop),AgentModelSelectionV2::ClaudeLauncher { surfaces, .. } => surfaces.contains(surface),+ AgentModelSelectionV2::DshAdditional { .. } => *surface == AgentModelSurfaceV2::DshCli,AgentModelSelectionV2::PiAdditional { .. } => *surface == AgentModelSurfaceV2::PiCli,AgentModelSelectionV2::QoderAdditional { .. } => {*surface == AgentModelSurfaceV2::QoderClidiff --git a/crates/application-api/src/generated/plan_authoring.rs b/crates/application-api/src/generated/plan_authoring.rsindex 82194d4f..f9355534 100644--- a/crates/application-api/src/generated/plan_authoring.rs+++ b/crates/application-api/src/generated/plan_authoring.rs@@ -81,7 +81,7 @@ fn definitions() -> Value {"schema":{"const":"hiroute.plan-editor/v2"},"display_name":{"type":"string","maxLength":128},"purpose":{"type":"string","maxLength":512},"custom_alias":{"type":"string","maxLength":64},"mode":{"enum":["fixed_model","smart_saving","free_first"]},"candidates":reference("candidates"),"smart":smart,"free":free,"delegation_enabled":{"type":"boolean"},"requirements":requirements,"limits":limits,- "work":object(&["harness","protocol"],json!({"harness":{"enum":["codex_cli","claude_code","qoder_cli","pi"]},"protocol":{"enum":["responses","messages"]}}))+ "work":object(&["harness","protocol"],json!({"harness":{"enum":["codex_cli","claude_code","qoder_cli","pi","deepseek_harness"]},"protocol":{"enum":["responses","messages"]}}))}),);let draft = object(diff --git a/crates/application-api/src/generated/worker.rs b/crates/application-api/src/generated/worker.rsindex 2d1460f4..4ba37693 100644--- a/crates/application-api/src/generated/worker.rs+++ b/crates/application-api/src/generated/worker.rs@@ -239,7 +239,7 @@ pub(super) fn dependencies_discover() -> Value {"$id": "hiroute://contracts/cli/worker-dependencies-discover-request.v1.schema.json","type": "object","additionalProperties": false,- "properties": {"harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi"]}}+ "properties": {"harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi", "deepseek_harness"]}}})}@@ -251,13 +251,13 @@ pub(super) fn dependencies_select() -> Value {"additionalProperties": false,"required": ["harness", "cli_path", "expected_selection_revision"],"properties": {- "harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi"]},+ "harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi", "deepseek_harness"]},"adapter_path": {"type": "string", "minLength": 1, "maxLength": 4096},"cli_path": {"type": "string", "minLength": 1, "maxLength": 4096},"node_path": {"type": "string", "minLength": 1, "maxLength": 4096},"expected_selection_revision": {"type": "integer", "minimum": 0, "maximum": u64::MAX}},- "if": {"properties": {"harness": {"const": "qoder_cli"}}},+ "if": {"properties": {"harness": {"enum": ["qoder_cli", "deepseek_harness"]}}},"then": {"properties": {"adapter_path": false, "node_path": false}},"else": {"if": {"properties": {"harness": {"const": "pi"}}},"then": {"required": ["node_path"], "properties": {"adapter_path": false}},diff --git a/crates/application-api/src/worker.rs b/crates/application-api/src/worker.rsindex bc1a1bc2..1e451fad 100644--- a/crates/application-api/src/worker.rs+++ b/crates/application-api/src/worker.rs@@ -132,6 +132,7 @@ pub fn plan_worker_dependency_selection(WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",WorkerHarnessV1::Pi => "pi",+ WorkerHarnessV1::DeepseekHarness => "deepseek_harness",};let spec = ChangeSpecV1 {schema_version: CHANGE_SPEC_SCHEMA_V1,@@ -377,11 +378,12 @@ pub struct WorkerExecutorAvailabilityListV1 {impl WorkerExecutorAvailabilityListV1 {pub fn valid(&self) -> bool {self.schema == WORKER_EXECUTOR_AVAILABILITY_SCHEMA_V1- && self.executors.len() == 4+ && self.executors.len() == 5&& self.executors[0].harness == WorkerHarnessV1::CodexCli&& self.executors[1].harness == WorkerHarnessV1::ClaudeCode&& self.executors[2].harness == WorkerHarnessV1::QoderCli&& self.executors[3].harness == WorkerHarnessV1::Pi+ && self.executors[4].harness == WorkerHarnessV1::DeepseekHarness&& self.executors.iter()@@ -1180,6 +1182,7 @@ mod tests {executor(WorkerHarnessV1::ClaudeCode),executor(WorkerHarnessV1::QoderCli),executor(WorkerHarnessV1::Pi),+ executor(WorkerHarnessV1::DeepseekHarness),],};assert!(response.valid());diff --git a/crates/application-api/src/worker_selection_tests.rs b/crates/application-api/src/worker_selection_tests.rsindex f17263b2..d697c46c 100644--- a/crates/application-api/src/worker_selection_tests.rs+++ b/crates/application-api/src/worker_selection_tests.rs@@ -17,7 +17,11 @@ fn harness_rule<'a>() -> &'a serde_json::Value {let mut rule = schema;while let Some(condition) = rule.get("if") {- let selected = condition["properties"]["harness"]["const"] == *harness;+ let discriminator = &condition["properties"]["harness"];+ let selected = discriminator["const"] == *harness+ || discriminator["enum"]+ .as_array()+ .is_some_and(|values| values.contains(harness));rule = &rule[if selected { "then" } else { "else" }];}rule@@ -83,57 +87,60 @@ fn saved_adapter_selections_preserve_json_and_confirmation_identity() {#[test]fn native_acp_requires_only_cli_and_rejects_cross_form_fields() {- let json =- r#"{"harness":"qoder_cli","cli_path":"/opt/bin/qodercli","expected_selection_revision":0}"#;- let request: WorkerDependenciesSelectRequestV1 = serde_json::from_str(json).unwrap();- let schema = generated_schema("worker-dependencies-select-request.v1.schema.json");- assert_eq!(- schema["required"],- serde_json::json!(["harness", "cli_path", "expected_selection_revision"])- );- assert_eq!(- harness_rule(&schema, &serde_json::to_value(request.harness).unwrap())["properties"],- serde_json::json!({"adapter_path":false,"node_path":false})- );- assert_eq!(serde_json::to_string(&request).unwrap(), json);- let plan = plan_worker_dependency_selection(&request).unwrap();- assert!(matches!(- plan.change.after_selection.validated_launch().unwrap(),- hiroute_domain::delegation::WorkerLaunchFormV1::NativeAcp {- cli: "/opt/bin/qodercli"- }- ));- for (adapter, node) in [- (Some("/opt/adapter".into()), None),- (None, Some("/opt/node".into())),+ for json in [+ r#"{"harness":"qoder_cli","cli_path":"/opt/bin/qodercli","expected_selection_revision":0}"#,+ r#"{"harness":"deepseek_harness","cli_path":"/opt/bin/dsh","expected_selection_revision":0}"#,] {- let invalid = WorkerDependenciesSelectRequestV1 {- adapter_path: adapter,- node_path: node,- ..request.clone()+ let request: WorkerDependenciesSelectRequestV1 = serde_json::from_str(json).unwrap();+ let schema = generated_schema("worker-dependencies-select-request.v1.schema.json");+ assert_eq!(+ schema["required"],+ serde_json::json!(["harness", "cli_path", "expected_selection_revision"])+ );+ assert_eq!(+ harness_rule(&schema, &serde_json::to_value(request.harness).unwrap())["properties"],+ serde_json::json!({"adapter_path":false,"node_path":false})+ );+ assert_eq!(serde_json::to_string(&request).unwrap(), json);+ let plan = plan_worker_dependency_selection(&request).unwrap();+ let hiroute_domain::delegation::WorkerLaunchFormV1::NativeAcp { cli } =+ plan.change.after_selection.validated_launch().unwrap()+ else {+ panic!("native ACP CLI")};- assert!(plan_worker_dependency_selection(&invalid).is_none());- }- for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode] {- assert!(- plan_worker_dependency_selection(&WorkerDependenciesSelectRequestV1 {- harness,+ assert_eq!(cli, request.cli_path);+ for (adapter, node) in [+ (Some("/opt/adapter".into()), None),+ (None, Some("/opt/node".into())),+ ] {+ let invalid = WorkerDependenciesSelectRequestV1 {+ adapter_path: adapter,+ node_path: node,..request.clone()- })- .is_none()- );+ };+ assert!(plan_worker_dependency_selection(&invalid).is_none());+ }+ for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode] {+ assert!(+ plan_worker_dependency_selection(&WorkerDependenciesSelectRequestV1 {+ harness,+ ..request.clone()+ })+ .is_none()+ );+ }+ let invalid = WorkerDependencySelectionRecordV1 {+ harness: request.harness,+ adapter_path: Some("/opt/adapter".into()),+ cli_path: "/opt/qoder".into(),+ node_path: None,+ };+ let mut forged = plan.change;+ forged.after_selection = invalid;+ let mut spec = plan.spec;+ spec.desired_state = serde_json::to_value(&forged.after_selection).unwrap();+ assert!(TransactionPlanV1::from_worker_dependency_selection_planner(spec, forged).is_err());}- let invalid = WorkerDependencySelectionRecordV1 {- harness: WorkerHarnessV1::QoderCli,- adapter_path: Some("/opt/adapter".into()),- cli_path: "/opt/qoder".into(),- node_path: None,- };- let mut forged = plan.change;- forged.after_selection = invalid;- let mut spec = plan.spec;- spec.desired_state = serde_json::to_value(&forged.after_selection).unwrap();- assert!(TransactionPlanV1::from_worker_dependency_selection_planner(spec, forged).is_err());}#[test]@@ -141,7 +148,13 @@ fn published_worker_harnesses_match_typed_discovery_selection_and_plan_bindings(let discover = generated_schema("worker-dependencies-discover-request.v1.schema.json");let select = generated_schema("worker-dependencies-select-request.v1.schema.json");let editor = generated_schema("plan-editor.v2.schema.json");- let expected = serde_json::json!(["codex_cli", "claude_code", "qoder_cli", "pi"]);+ let expected = serde_json::json!([+ "codex_cli",+ "claude_code",+ "qoder_cli",+ "pi",+ "deepseek_harness"+ ]);for declared in [&discover["properties"]["harness"]["enum"],&select["properties"]["harness"]["enum"],diff --git a/crates/application/src/agent_connection/additional_model_journal.rs b/crates/application/src/agent_connection/additional_model_journal.rsindex 8546bb2f..9772945a 100644--- a/crates/application/src/agent_connection/additional_model_journal.rs+++ b/crates/application/src/agent_connection/additional_model_journal.rs@@ -15,12 +15,14 @@ pub fn additional_model_kind(intent: &ExternalEffectIntentV1) -> PortResult<Agenmatch intent.desired()["subject"]["agent_id"].as_str() {Some("agent_qoder_default") => Ok(AgentKindV1::Qoder),Some("agent_pi_default") => Ok(AgentKindV1::Pi),+ Some("agent_dsh_default") => Ok(AgentKindV1::DeepseekHarness),_ => Err(invalid()),}}fn schema(kind: AgentKindV1) -> &'static str {match kind {AgentKindV1::Pi => PI_SCHEMA,+ AgentKindV1::DeepseekHarness => "hiroute.settings-dsh-model-file/v1",_ => QODER_SCHEMA,}}@@ -68,7 +70,9 @@ pub fn settings_additional_model_file_intent(return Err(OperationValidationError::UnregisteredEffectPlan);}let payload = AdditionalModelFilePayload {- schema: schema(if control.subject().agent_id() == "agent_pi_default" {+ schema: schema(if control.subject().agent_id() == "agent_dsh_default" {+ AgentKindV1::DeepseekHarness+ } else if control.subject().agent_id() == "agent_pi_default" {AgentKindV1::Pi} else {AgentKindV1::Qoder@@ -107,6 +111,11 @@ pub fn decode_settings_additional_model_file(let value = intent.desired();let kind = additional_model_kind(intent)?;let (agent, profile, integration) = match kind {+ AgentKindV1::DeepseekHarness => (+ "agent_dsh_default",+ "dsh-responses-v1",+ "builtin/dsh-responses/v1",+ ),AgentKindV1::Pi => ("agent_pi_default","pi-responses-v1",@@ -147,7 +156,7 @@ pub fn decode_settings_additional_model_file(|| models.is_empty()|| models.len() > 256|| models.iter().any(|model| {- (if kind == AgentKindV1::Pi {+ (if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {model.validate_pi()} else {model.validate()@@ -195,6 +204,9 @@ pub fn settings_additional_model_file_for_operation(}| AgentModelSelectionV2::PiAdditional {allowed_plan_ids, ..+ }+ | AgentModelSelectionV2::DshAdditional {+ allowed_plan_ids, ..},},AdditionalModelFileAction::Configure {@@ -209,6 +221,12 @@ pub fn settings_additional_model_file_for_operation(settings: AgentModelSelectionV2::PiAdditional { .. }}) != (kind == AgentKindV1::Pi)+ || matches!(+ &spec.model,+ AgentFacetIntent::Configure {+ settings: AgentModelSelectionV2::DshAdditional { .. }+ }+ ) != (kind == AgentKindV1::DeepseekHarness){return Err(invalid());}@@ -239,11 +257,13 @@ fn local_endpoint(value: &str, kind: AgentKindV1) -> bool {.strip_prefix("http://127.0.0.1:").or_else(|| value.strip_prefix("http://[::1]:")).and_then(|rest| {- rest.strip_suffix(if kind == AgentKindV1::Pi {- "/v1"- } else {- hiroute_domain::QODER_MODEL_BASE_PATH- })+ rest.strip_suffix(+ if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {+ "/v1"+ } else {+ hiroute_domain::QODER_MODEL_BASE_PATH+ },+ )}).is_some_and(|port| {!port.is_empty()diff --git a/crates/application/src/agent_connection/settings.rs b/crates/application/src/agent_connection/settings.rsindex abbc03e0..31b88be4 100644--- a/crates/application/src/agent_connection/settings.rs+++ b/crates/application/src/agent_connection/settings.rs@@ -189,6 +189,7 @@ pub fn preview_agent_settings(AgentModelSelectionV2::CodexDefault { .. }| AgentModelSelectionV2::QoderAdditional { .. }| AgentModelSelectionV2::PiAdditional { .. }+ | AgentModelSelectionV2::DshAdditional { .. }) {// A short-lived isolated HTTP challenge diagnoses a native client; it is not// authorization to write a safely observed Codex configuration. Actual client@@ -235,6 +236,14 @@ pub fn preview_agent_settings({return Err(SettingsPlanningError::InvalidSelection);}+ if matches!(settings, AgentModelSelectionV2::DshAdditional { .. })+ && !model+ .common+ .available_surfaces+ .contains(&hiroute_domain::AgentModelSurfaceV2::DshCli)+ {+ return Err(SettingsPlanningError::InvalidSelection);+ }settings.validate().map_err(|_| SettingsPlanningError::InvalidSelection)?;@@ -593,7 +602,7 @@ fn validate_model_default(.then_some(name.as_str())}),},- AgentModelSelectionV2::QoderAdditional { .. } | AgentModelSelectionV2::PiAdditional { .. } => return Ok(()),+ AgentModelSelectionV2::QoderAdditional { .. } | AgentModelSelectionV2::PiAdditional { .. } | AgentModelSelectionV2::DshAdditional { .. } => return Ok(()),AgentModelSelectionV2::ClaudeLauncher { .. } => {let facts = facts.claude().ok_or_else(invalid)?;claude_presets = grantdiff --git a/crates/application/src/agent_connection/settings_input.rs b/crates/application/src/agent_connection/settings_input.rsindex e659d716..df4aa3fc 100644--- a/crates/application/src/agent_connection/settings_input.rs+++ b/crates/application/src/agent_connection/settings_input.rs@@ -126,8 +126,11 @@ impl AgentSettingsPlanningInput {settings,AgentModelSelectionV2::QoderAdditional { .. }| AgentModelSelectionV2::PiAdditional { .. }+ | AgentModelSelectionV2::DshAdditional { .. }) || matches!(settings, AgentModelSelectionV2::PiAdditional { .. })!= (*kind == hiroute_domain::AgentKindV1::Pi)+ || matches!(settings, AgentModelSelectionV2::DshAdditional { .. })+ != (*kind == hiroute_domain::AgentKindV1::DeepseekHarness){return Err(invalid());}diff --git a/crates/application/src/agent_connection/tests.rs b/crates/application/src/agent_connection/tests.rsindex a7dc5619..3322507c 100644--- a/crates/application/src/agent_connection/tests.rs+++ b/crates/application/src/agent_connection/tests.rs@@ -48,7 +48,7 @@ fn agent_connection_current_proof_allows_unlisted_version_without_version_allowlfn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {let version = match kind {- AgentKindV1::Qoder | AgentKindV1::Pi => {+ AgentKindV1::Qoder | AgentKindV1::Pi | AgentKindV1::DeepseekHarness => {panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => CODEX_VERIFIED_VERSION_V1,@@ -85,7 +85,7 @@ fn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {fn profile(kind: AgentKindV1) -> AgentProfileV1 {let precedence = kind.config_precedence().to_vec();match kind {- AgentKindV1::Qoder | AgentKindV1::Pi => {+ AgentKindV1::Qoder | AgentKindV1::Pi | AgentKindV1::DeepseekHarness => {panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => {@@ -252,7 +252,7 @@ fn facts(kind: AgentKindV1) -> AgentConnectionPlanningFactsV1 {fn spec(kind: AgentKindV1, native: bool, dynamic: bool) -> AgentConnectSpecV1 {let profile = match kind {- AgentKindV1::Qoder | AgentKindV1::Pi => {+ AgentKindV1::Qoder | AgentKindV1::Pi | AgentKindV1::DeepseekHarness => {panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => profile(AgentKindV1::Codex),@@ -263,7 +263,7 @@ fn spec(kind: AgentKindV1, native: bool, dynamic: bool) -> AgentConnectSpecV1 {agent_id: format!("agent/{}", kind.as_str()),profile_id: profile.profile_id,installed_version: match kind {- AgentKindV1::Qoder | AgentKindV1::Pi => {+ AgentKindV1::Qoder | AgentKindV1::Pi | AgentKindV1::DeepseekHarness => {panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => CODEX_VERIFIED_VERSION_V1,diff --git a/crates/application/src/delegation/tasks.rs b/crates/application/src/delegation/tasks.rsindex 8c3d2eea..cf0b98d6 100644--- a/crates/application/src/delegation/tasks.rs+++ b/crates/application/src/delegation/tasks.rs@@ -811,6 +811,7 @@ mod tests {unavailable(hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode),unavailable(hiroute_domain::delegation::WorkerHarnessV1::QoderCli),unavailable(hiroute_domain::delegation::WorkerHarnessV1::Pi),+ unavailable(hiroute_domain::delegation::WorkerHarnessV1::DeepseekHarness),],})}@@ -878,7 +879,13 @@ mod tests {.iter().map(|executor| executor["harness"].as_str().unwrap()).collect::<Vec<_>>(),- ["codex_cli", "claude_code", "qoder_cli", "pi"]+ [+ "codex_cli",+ "claude_code",+ "qoder_cli",+ "pi",+ "deepseek_harness"+ ]);let rejected = invoke_worker(diff --git a/crates/cli/src/worker/input.rs b/crates/cli/src/worker/input.rsindex 377d5d1d..b5bc147b 100644--- a/crates/cli/src/worker/input.rs+++ b/crates/cli/src/worker/input.rs@@ -26,6 +26,7 @@ pub(super) fn parse_dependencies_discover("claude_code" => WorkerHarnessV1::ClaudeCode,"qoder_cli" => WorkerHarnessV1::QoderCli,"pi" => WorkerHarnessV1::Pi,+ "deepseek_harness" => WorkerHarnessV1::DeepseekHarness,_ => return Err(ErrorCode::InvalidArguments),};harness = unique(harness, parsed)?;diff --git a/crates/cli/src/worker/render.rs b/crates/cli/src/worker/render.rsindex 9f93cf81..eb01499a 100644--- a/crates/cli/src/worker/render.rs+++ b/crates/cli/src/worker/render.rs@@ -712,6 +712,7 @@ fn worker_harness_wire_name(harness: WorkerHarnessV1) -> &'static str {WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",WorkerHarnessV1::Pi => "pi",+ WorkerHarnessV1::DeepseekHarness => "deepseek_harness",}}diff --git a/crates/client-core/tests/transport.rs b/crates/client-core/tests/transport.rsindex 28f5d3db..5efd8775 100644--- a/crates/client-core/tests/transport.rs+++ b/crates/client-core/tests/transport.rs@@ -409,7 +409,16 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {"cancel": {"state":"unavailable","reason":"installation_not_configured"},"continue_session": {"state":"unavailable","reason":"installation_not_configured"},"restricted_policy": {"state":"unavailable","reason":"installation_not_configured"}- }+ },+ {+ "harness": "deepseek_harness",+ "state": "unavailable",+ "reason": "installation_not_configured",+ "start_approve_all": {"state":"unavailable","reason":"installation_not_configured"},+ "cancel": {"state":"unavailable","reason":"installation_not_configured"},+ "continue_session": {"state":"unavailable","reason":"installation_not_configured"},+ "restricted_policy": {"state":"unavailable","reason":"installation_not_configured"}+ },]}),Some(request.request_id),@@ -434,7 +443,8 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {WorkerHarnessV1::CodexCli,WorkerHarnessV1::ClaudeCode,WorkerHarnessV1::QoderCli,- WorkerHarnessV1::Pi+ WorkerHarnessV1::Pi,+ WorkerHarnessV1::DeepseekHarness]);server.await.unwrap();diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rsindex 132f8efc..23b1f49b 100644--- a/crates/daemon/src/control/runtime.rs+++ b/crates/daemon/src/control/runtime.rs@@ -295,38 +295,31 @@ impl ProductionControlRuntime {let scanner = match overrides.scanner {Some(scanner) => scanner,None => {- let selected_claude = stores- .control()- .worker_dependency_selection(- &WorkspaceId::default(),- hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode,- )- .map_err(|error| error.to_string())?- .map(|(selection, _)| PathBuf::from(selection.cli_path));- let selected_qoder = stores- .control()- .worker_dependency_selection(- &WorkspaceId::default(),- hiroute_domain::delegation::WorkerHarnessV1::QoderCli,- )- .map_err(|error| error.to_string())?- .map(|(selection, _)| PathBuf::from(selection.cli_path));- let selected_pi = stores- .control()- .worker_dependency_selection(- &WorkspaceId::default(),- hiroute_domain::delegation::WorkerHarnessV1::Pi,- )- .map_err(|error| error.to_string())?- .map(|(selection, _)| PathBuf::from(selection.cli_path));+ use hiroute_domain::delegation::WorkerHarnessV1;+ let mut selected = Vec::new();+ for (kind, harness) in [+ (AgentKindV1::ClaudeCode, WorkerHarnessV1::ClaudeCode),+ (AgentKindV1::Qoder, WorkerHarnessV1::QoderCli),+ (AgentKindV1::Pi, WorkerHarnessV1::Pi),+ (+ AgentKindV1::DeepseekHarness,+ WorkerHarnessV1::DeepseekHarness,+ ),+ ] {+ if let Some((selection, _)) = stores+ .control()+ .worker_dependency_selection(&WorkspaceId::default(), harness)+ .map_err(|error| error.to_string())?+ {+ selected.push((kind, PathBuf::from(selection.cli_path)));+ }+ }release_agent_scanner(&home,&project,&release_catalog,overrides.codex_desktop_engine,- selected_claude,- selected_qoder,- selected_pi,+ &selected,)?}};@@ -369,11 +362,29 @@ impl ProductionControlRuntime {hiroute_integrations::PI_INTEGRATION_PROFILE_REF_V1,).map_err(|error| error.to_string())?;+ let dsh_subject = AgentConnectionTransactionSubjectV1::from_registered_profile(+ "agent_dsh_default",+ hiroute_integrations::DSH_PROFILE_ID_V1,+ hiroute_integrations::DSH_INTEGRATION_PROFILE_REF_V1,+ )+ .map_err(|e| e.to_string())?;let artifacts = stores.open_managed_artifacts_with_external_targets(storage_root.join("managed-artifacts"),storage_root.join("artifact-restores"),[+ (+ AgentConnectionEffectRoleV1::ManagedConfiguration+ .target_for(&dsh_subject)+ .map_err(|e| e.to_string())?,+ scanner.dsh_user_models_target(),+ ),+ (+ AgentConnectionEffectRoleV1::RoutingSkill+ .target_for(&dsh_subject)+ .map_err(|e| e.to_string())?,+ scanner.dsh_user_skill_target(),+ ),(AgentConnectionEffectRoleV1::ManagedConfiguration.target_for(&pi_subject)@@ -1294,9 +1305,7 @@ fn release_agent_scanner(project: &Path,catalog: &TrustedReleaseCatalog,codex_desktop_engine: Option<PathBuf>,- selected_claude: Option<PathBuf>,- selected_qoder: Option<PathBuf>,- selected_pi: Option<PathBuf>,+ selected: &[(AgentKindV1, PathBuf)],) -> Result<FilesystemAgentScannerV1, String> {// ReleaseFacts verification already validated the registered connector/model metadata.// Agent registration consumes that payload after the current rating snapshot and all@@ -1308,14 +1317,15 @@ fn release_agent_scanner(.map_err(|_| "verified Agent discovery facts are inconsistent".to_owned())?;let mut layout = AgentFilesystemLayoutV1::from_process(home, project);layout.codex_desktop_executable = codex_desktop_engine;- if let Some(executable) = selected_claude {- layout.claude_executable = executable;- }- if let Some(executable) = selected_qoder {- layout.qoder_executable = executable;- }- if let Some(executable) = selected_pi {- layout.pi_executable = executable;+ for (kind, executable) in selected {+ let target = match kind {+ AgentKindV1::Codex => &mut layout.codex_executable,+ AgentKindV1::ClaudeCode => &mut layout.claude_executable,+ AgentKindV1::Qoder => &mut layout.qoder_executable,+ AgentKindV1::Pi => &mut layout.pi_executable,+ AgentKindV1::DeepseekHarness => &mut layout.dsh_executable,+ };+ *target = executable.clone();}Ok(FilesystemAgentScannerV1::new(layout, index))}@@ -1348,6 +1358,7 @@ fn discovered_agent(AgentKindV1::ClaudeCode => "claude-messages-v1",AgentKindV1::Qoder => QODER_PROFILE_ID_V1,AgentKindV1::Pi => hiroute_integrations::PI_PROFILE_ID_V1,+ AgentKindV1::DeepseekHarness => hiroute_integrations::DSH_PROFILE_ID_V1,}.to_owned(),version.clone(),diff --git a/crates/daemon/src/control/runtime/additional_model_budget.rs b/crates/daemon/src/control/runtime/additional_model_budget.rsindex 86cd4cb6..f11395a9 100644--- a/crates/daemon/src/control/runtime/additional_model_budget.rs+++ b/crates/daemon/src/control/runtime/additional_model_budget.rs@@ -79,7 +79,10 @@ impl LocalControlAdapter {.clone().into_current().map_err(|_| shrinking())?;- let budget = (if kind == hiroute_domain::AgentKindV1::Pi {+ let budget = (if matches!(+ kind,+ hiroute_domain::AgentKindV1::Pi | hiroute_domain::AgentKindV1::DeepseekHarness+ ) {hiroute_integrations::pi_plan_token_budget(&plan.body.materialized)} else {hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rsindex a793d8f7..599d3e0d 100644--- a/crates/daemon/src/control/runtime/agent_connection.rs+++ b/crates/daemon/src/control/runtime/agent_connection.rs@@ -337,6 +337,12 @@ impl AgentConnectionControlPort for LocalControlAdapter {let cli = std::env::current_exe().map_err(|_| ControlReadError::Unavailable)?.with_file_name("hiroute");+ if agent_id == "agent_dsh_default" {+ return self+ .scanner+ .check_dsh_collaboration(&cli)+ .map_err(|_| ControlReadError::Unavailable.into());+ }if agent_id == "agent_pi_default" {return self.scannerdiff --git a/crates/daemon/src/control/runtime/agent_live_check.rs b/crates/daemon/src/control/runtime/agent_live_check.rsindex b20b795b..1ba5931c 100644--- a/crates/daemon/src/control/runtime/agent_live_check.rs+++ b/crates/daemon/src/control/runtime/agent_live_check.rs@@ -101,7 +101,9 @@ impl LocalControlAdapter {for (model, trust) in target.client_model_ids.iter().zip(&expected) {let result = match target.surface {- AgentModelSurfaceV2::PiCli => return Err(ControlReadError::Denied),+ AgentModelSurfaceV2::PiCli | AgentModelSurfaceV2::DshCli => {+ return Err(ControlReadError::Denied);+ }AgentModelSurfaceV2::QoderCli => {self.execute_qoder_live_attempt(&target.context_id, model, trust, deadline)}diff --git a/crates/daemon/src/control/runtime/collaboration_installation.rs b/crates/daemon/src/control/runtime/collaboration_installation.rsindex 9ec363f8..16bb800c 100644--- a/crates/daemon/src/control/runtime/collaboration_installation.rs+++ b/crates/daemon/src/control/runtime/collaboration_installation.rs@@ -81,7 +81,10 @@ impl LocalControlAdapter {)?;}// Only historical clients ever owned sealed collaboration credentials.- if matches!(class, SettingsAgentClass::Qoder | SettingsAgentClass::Pi) {+ if matches!(+ class,+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh+ ) {return Ok(());}let legacy = self.legacy_collaboration_artifact_path(&spec.context_id)?;@@ -109,7 +112,9 @@ impl LocalControlAdapter {self.scanner.codex_user_config_target()}SettingsAgentClass::Claude => self.scanner.claude_user_settings_target(),- SettingsAgentClass::Qoder | SettingsAgentClass::Pi => return Err(error()),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => {+ return Err(error());+ }};let home = native.parent()@@ -121,7 +126,9 @@ impl LocalControlAdapter {.join(match class {SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => "codex.sealed",SettingsAgentClass::Claude => "claude-code.sealed",- SettingsAgentClass::Qoder | SettingsAgentClass::Pi => return Err(error()),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => {+ return Err(error());+ }}))}}diff --git a/crates/daemon/src/control/runtime/compute_routing.rs b/crates/daemon/src/control/runtime/compute_routing.rsindex e406fc43..4f832c35 100644--- a/crates/daemon/src/control/runtime/compute_routing.rs+++ b/crates/daemon/src/control/runtime/compute_routing.rs@@ -62,18 +62,23 @@ impl LocalControlAdapter {.get(input_slot).cloned().ok_or(ControlReadError::NotFound)?;- if descriptor.field_selector == "pi.api-key" {- return self- .scanner- .pi_api_sources()- .map_err(|_| ControlReadError::SnapshotChanged)?- .iter()- .any(|source| {- source.credential.as_ref() == Some(&descriptor)- && &source.evidence_digest == expected_evidence- })- .then_some(())- .ok_or(ControlReadError::SnapshotChanged);+ if matches!(+ descriptor.field_selector.as_str(),+ "pi.api-key" | "dsh.api-key"+ ) {+ return (if descriptor.field_selector == "dsh.api-key" {+ self.scanner.dsh_api_sources()+ } else {+ self.scanner.pi_api_sources()+ })+ .map_err(|_| ControlReadError::SnapshotChanged)?+ .iter()+ .any(|source| {+ source.credential.as_ref() == Some(&descriptor)+ && &source.evidence_digest == expected_evidence+ })+ .then_some(())+ .ok_or(ControlReadError::SnapshotChanged);}let catalog = self.release_catalog@@ -254,7 +259,8 @@ impl ComputeFactsPort for LocalControlAdapter {.iter().map(|discovery| scan_item(catalog, discovery)).collect::<Result<Vec<_>, _>>()?;- items.extend(self.pi_compute_scan_items()?);+ items.extend(self.native_compute_scan_items(false)?);+ items.extend(self.native_compute_scan_items(true)?);// Subscription discovery has its own metadata-only API. Generic ScanCompute must not// start CPA or materialize OAuth state merely because a screen was opened.items.sort_by(|left, right| left.agent_id.cmp(&right.agent_id));diff --git a/crates/daemon/src/control/runtime/compute_routing/tests.rs b/crates/daemon/src/control/runtime/compute_routing/tests.rsindex 610797e3..3129ca3e 100644--- a/crates/daemon/src/control/runtime/compute_routing/tests.rs+++ b/crates/daemon/src/control/runtime/compute_routing/tests.rs@@ -304,8 +304,7 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot()std::fs::create_dir_all(&home).unwrap();std::fs::create_dir_all(&project).unwrap();let scanner =- super::super::release_agent_scanner(&home, &project, &catalog, None, None, None, None)- .unwrap();+ super::super::release_agent_scanner(&home, &project, &catalog, None, &[]).unwrap();assert_eq!(scanner.claude_executable_target(),std::path::PathBuf::from("claude")@@ -316,9 +315,10 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot()&project,&catalog,None,- Some(selected_claude.clone()),- None,- None,+ &[(+ hiroute_domain::AgentKindV1::ClaudeCode,+ selected_claude.clone(),+ )],).unwrap();assert_eq!(selected_scanner.claude_executable_target(), selected_claude);diff --git a/crates/daemon/src/control/runtime/delegation_task_queries.rs b/crates/daemon/src/control/runtime/delegation_task_queries.rsindex 1fc02b2f..727df065 100644--- a/crates/daemon/src/control/runtime/delegation_task_queries.rs+++ b/crates/daemon/src/control/runtime/delegation_task_queries.rs@@ -258,6 +258,7 @@ pub(super) fn run_view(task: &DelegationTaskV1, run: &DelegationRunV1) -> Delegahiroute_domain::delegation::WorkerHarnessV1::ClaudeCode => "Claude Code",hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "Qoder",hiroute_domain::delegation::WorkerHarnessV1::Pi => "Pi",+ hiroute_domain::delegation::WorkerHarnessV1::DeepseekHarness => "DeepSeek Harness",};DelegationRunViewV1 {task_id: run.task_id.clone(),diff --git a/crates/daemon/src/control/runtime/model_connections/discovered.rs b/crates/daemon/src/control/runtime/model_connections/discovered.rsindex e12fa0b2..76ef49d1 100644--- a/crates/daemon/src/control/runtime/model_connections/discovered.rs+++ b/crates/daemon/src/control/runtime/model_connections/discovered.rs@@ -138,9 +138,10 @@ impl LocalControlAdapter {// No matching Pi source still fails below; no candidate is created..unwrap_or_default().into_iter()+ .chain(self.scanner.dsh_api_sources().unwrap_or_default()).find(|source| super::pi_discovered::pi_discovery(source) == request.discovery){- return self.prepare_pi_discovered_candidate(source, &request.prepare_id);+ return self.prepare_native_api_candidate(source, &request.prepare_id);}return Err(if current_exists {ComputeManagementControlError::DiscoveryChangeddiff --git a/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs b/crates/daemon/src/control/runtime/model_connections/pi_discovered.rsindex 5da29101..e8443b6b 100644--- a/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs+++ b/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs@@ -10,14 +10,24 @@ pub(super) fn pi_discovery(source: &PiApiSource) -> ComputeDiscoveryRefV1 {}}impl LocalControlAdapter {- pub(in crate::control::runtime) fn pi_compute_scan_items(+ pub(in crate::control::runtime) fn native_compute_scan_items(&self,+ dsh: bool,) -> Result<Vec<ComputeScanItemV1>, hiroute_application::control::ControlReadError> {- let sources = match self.scanner.pi_api_sources() {+ let agent_id = if dsh {+ "agent_dsh_default"+ } else {+ "agent_pi_default"+ };+ let sources = match if dsh {+ self.scanner.dsh_api_sources()+ } else {+ self.scanner.pi_api_sources()+ } {Ok(sources) => sources,Err(_) => {return Ok(vec![ComputeScanItemV1 {- agent_id: "agent_pi_default".into(),+ agent_id: agent_id.into(),supported: false,native_provider_id: None,configuration_state: "configuration_unavailable".into(),@@ -29,7 +39,14 @@ impl LocalControlAdapter {model_configuration_id: None,inventory_eligible: false,discovery: None,- actions_required: vec!["check_pi_configuration".into()],+ actions_required: vec![+ if dsh {+ "check_dsh_configuration"+ } else {+ "check_pi_configuration"+ }+ .into(),+ ],permission_action: None,credential_import: None,}]);@@ -56,7 +73,7 @@ impl LocalControlAdapter {};let discovery = ready.then(|| pi_discovery(&source));Ok(ComputeScanItemV1 {- agent_id: "agent_pi_default".into(),+ agent_id: agent_id.into(),supported: true,native_provider_id: Some(source.provider_id),configuration_state: if ready {@@ -84,7 +101,7 @@ impl LocalControlAdapter {}).collect()}- pub(super) fn prepare_pi_discovered_candidate(+ pub(super) fn prepare_native_api_candidate(&self,source: PiApiSource,prepare_id: &str,@@ -95,10 +112,13 @@ impl LocalControlAdapter {let protocol = source.protocol.ok_or(ComputeManagementControlError::DiscoveryNotImportable)?;- let (base_url, secret) = self- .scanner- .read_pi_api_source(&source)- .map_err(|_| ComputeManagementControlError::DiscoveryChanged)?;+ let dsh = source.source_ref.starts_with("dsh-source/");+ let (base_url, secret) = (if dsh {+ self.scanner.read_dsh_api_source(&source)+ } else {+ self.scanner.read_pi_api_source(&source)+ })+ .map_err(|_| ComputeManagementControlError::DiscoveryChanged)?;let credential = source.credential.as_ref()@@ -113,7 +133,11 @@ impl LocalControlAdapter {observed_revision: credential.observed_revision,};let candidate_digest = hiroute_domain::CanonicalDigest::of(&(- "pi-discovered-candidate/v1",+ if dsh {+ "dsh-discovered-candidate/v1"+ } else {+ "pi-discovered-candidate/v1"+ },&source.evidence_digest,prepare_id,))@@ -171,7 +195,11 @@ impl LocalControlAdapter {candidate_ref: Some(candidate.candidate_ref),lineage_ref: pi_discovery(&source).discovery_ref,trusted_lineage_digest: None,- display_name: format!("Pi · {}", source.provider_id),+ display_name: format!(+ "{} · {}",+ if dsh { "DSH" } else { "Pi" },+ source.provider_id+ ),existing_source_id: None,edit_revision: source.revision,check_id: prepare_id.into(),diff --git a/crates/daemon/src/control/runtime/mutation.rs b/crates/daemon/src/control/runtime/mutation.rsindex a1c8f54f..5879603b 100644--- a/crates/daemon/src/control/runtime/mutation.rs+++ b/crates/daemon/src/control/runtime/mutation.rs@@ -132,7 +132,13 @@ impl LocalControlAdapter {return Err("protected discovery slot collision".to_owned());}}- for source in self.scanner.pi_api_sources().unwrap_or_default() {+ for source in self+ .scanner+ .pi_api_sources()+ .unwrap_or_default()+ .into_iter()+ .chain(self.scanner.dsh_api_sources().unwrap_or_default())+ {if let Some(descriptor) = source.credential {let slot = protected_input_slot(&descriptor)?;if inputs.insert(slot, descriptor).is_some() {diff --git a/crates/daemon/src/control/runtime/native_additional_model.rs b/crates/daemon/src/control/runtime/native_additional_model.rsindex c2bd8102..56c3728c 100644--- a/crates/daemon/src/control/runtime/native_additional_model.rs+++ b/crates/daemon/src/control/runtime/native_additional_model.rs@@ -15,7 +15,7 @@ pub(super) fn is_settings_additional_model(intent: &ExternalEffectIntentV1) -> b&& intent.desired()["transaction"] == "settings"&& matches!(intent.desired()["subject"]["agent_id"].as_str(),- Some("agent_qoder_default" | "agent_pi_default")+ Some("agent_qoder_default" | "agent_pi_default" | "agent_dsh_default"))}@@ -23,7 +23,7 @@ pub(super) fn additional_model_endpoint(kind: AgentKindV1,gateway_base_url: &str,) -> PortResult<String> {- if kind == AgentKindV1::Pi {+ if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {return Ok(gateway_base_url.to_owned());}let origin = gateway_base_url@@ -63,7 +63,7 @@ pub(super) fn additional_models_for_grant(if &plan.body.materialized_route_digest != semantic_digest {return Err(conflict("qoder.models.plan.digest"));}- let budget = (if kind == AgentKindV1::Pi {+ let budget = (if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {hiroute_integrations::pi_plan_token_budget(&plan.body.materialized)} else {hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)@@ -87,6 +87,24 @@ impl LocalControlAdapter {intent: &ExternalEffectIntentV1,) -> PortResult<()> {let payload = settings_additional_model_file_for_operation(operation, intent)?;+ if additional_model_kind(intent)? == AgentKindV1::DeepseekHarness {+ let models = match &payload.change {+ AdditionalModelFileAction::Configure { models, .. } => models.as_slice(),+ _ => &[],+ };+ if self+ .scanner+ .dsh_web_default_in_use(+ &hiroute_application::agent_connection::additional_model_provider_id(+ &payload.context_id,+ ),+ models,+ )+ .map_err(|_| conflict("dsh.settings.home.changed"))?+ {+ return Err(conflict("dsh.settings.default.changed"));+ }+ }if let Some(expected) = &payload.pi_settings_content {let settings = self.scannerdiff --git a/crates/daemon/src/control/runtime/settings_facts.rs b/crates/daemon/src/control/runtime/settings_facts.rsindex aa4681f8..02ee7bea 100644--- a/crates/daemon/src/control/runtime/settings_facts.rs+++ b/crates/daemon/src/control/runtime/settings_facts.rs@@ -57,6 +57,7 @@ pub(super) enum SettingsAgentClass {Claude,Qoder,Pi,+ Dsh,}impl SettingsAgentClass {@@ -70,6 +71,7 @@ impl SettingsAgentClass {Self::Claude => "agent_claude_default",Self::Qoder => "agent_qoder_default",Self::Pi => "agent_pi_default",+ Self::Dsh => "agent_dsh_default",}}@@ -79,6 +81,7 @@ impl SettingsAgentClass {Self::Claude => "claude",Self::Qoder => "qoder",Self::Pi => "pi",+ Self::Dsh => "dsh",}}@@ -89,6 +92,7 @@ impl SettingsAgentClass {Self::Claude => scanner.claude_user_settings_target(),Self::Qoder => scanner.qoder_user_config_target(),Self::Pi => scanner.pi_user_models_target(),+ Self::Dsh => scanner.dsh_user_models_target(),}}@@ -98,6 +102,7 @@ impl SettingsAgentClass {Self::Claude => "skill-root/agent_claude_default",Self::Qoder => "skill-root/agent_qoder_default",Self::Pi => "skill-root/agent_pi_default",+ Self::Dsh => "skill-root/agent_dsh_default",}}@@ -115,6 +120,10 @@ impl SettingsAgentClass {hiroute_integrations::PI_PROFILE_ID_V1,hiroute_integrations::PI_INTEGRATION_PROFILE_REF_V1,),+ Self::Dsh => (+ hiroute_integrations::DSH_PROFILE_ID_V1,+ hiroute_integrations::DSH_INTEGRATION_PROFILE_REF_V1,+ ),Self::Qoder => (hiroute_integrations::QODER_PROFILE_ID_V1,hiroute_integrations::QODER_INTEGRATION_PROFILE_REF_V1,@@ -136,6 +145,7 @@ impl LocalControlAdapter {"agent_claude_default" => SettingsAgentClass::Claude,"agent_qoder_default" => SettingsAgentClass::Qoder,"agent_pi_default" => SettingsAgentClass::Pi,+ "agent_dsh_default" => SettingsAgentClass::Dsh,_ => return None,};Some(self.settings_context(class))@@ -148,6 +158,7 @@ impl LocalControlAdapter {SettingsAgentClass::Claude,SettingsAgentClass::Qoder,SettingsAgentClass::Pi,+ SettingsAgentClass::Dsh,].into_iter().find(|class| context == self.settings_context(*class))@@ -184,7 +195,10 @@ impl LocalControlAdapter {spec: &AgentSettingsSpecV2,class: SettingsAgentClass,) -> Result<AgentSettingsPlanningInput, ControlReadError> {- if matches!(class, SettingsAgentClass::Qoder | SettingsAgentClass::Pi) {+ if matches!(+ class,+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh+ ) {return self.attach_additional_model_facts(spec,class,@@ -394,7 +408,7 @@ impl LocalControlAdapter {SettingsAgentClass::Claude}SettingsAgentClass::Claude => SettingsAgentClass::Codex,- SettingsAgentClass::Qoder | SettingsAgentClass::Pi => {+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => {return Err(ControlReadError::Denied);}};@@ -462,7 +476,7 @@ impl LocalControlAdapter {selected_collaboration_restore = Some(original.operation_id.clone());}let model = match class {- SettingsAgentClass::Qoder | SettingsAgentClass::Pi => return Err(ControlReadError::Denied),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => return Err(ControlReadError::Denied),SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => original.plan.external()@@ -598,7 +612,7 @@ impl LocalControlAdapter {None};let native_default_model = match class {- SettingsAgentClass::Qoder | SettingsAgentClass::Pi => {+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => {return Err(ControlReadError::Denied);}SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => codex_catalog_summary@@ -888,7 +902,7 @@ impl LocalControlAdapter {)).map_err(|_| ControlReadError::Corrupt)?;let model_target = match class {- SettingsAgentClass::Qoder | SettingsAgentClass::Pi => {+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => {return Err(ControlReadError::Denied);}SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => {diff --git a/crates/daemon/src/control/runtime/settings_facts/additional_model.rs b/crates/daemon/src/control/runtime/settings_facts/additional_model.rsindex b1f7b313..e97ab81f 100644--- a/crates/daemon/src/control/runtime/settings_facts/additional_model.rs+++ b/crates/daemon/src/control/runtime/settings_facts/additional_model.rs@@ -29,11 +29,14 @@ impl LocalControlAdapter {settings,AgentModelSelectionV2::QoderAdditional { .. }| AgentModelSelectionV2::PiAdditional { .. }+ | AgentModelSelectionV2::DshAdditional { .. }){return Ok(input);}- let kind = if class == SettingsAgentClass::Pi {+ let kind = if class == SettingsAgentClass::Dsh {+ hiroute_domain::AgentKindV1::DeepseekHarness+ } else if class == SettingsAgentClass::Pi {hiroute_domain::AgentKindV1::Pi} else {hiroute_domain::AgentKindV1::Qoder@@ -47,6 +50,14 @@ impl LocalControlAdapter {.check_pi_model_configuration().map_err(|_| ControlReadError::Unavailable)?;}+ #[cfg(unix)]+ if kind == hiroute_domain::AgentKindV1::DeepseekHarness+ && matches!(spec.model, AgentFacetIntent::Configure { .. })+ {+ self.scanner+ .check_dsh_model_configuration()+ .map_err(|_| ControlReadError::Unavailable)?;+ }let pi_settings = if kind == hiroute_domain::AgentKindV1::Pi {Some(self.scanner@@ -240,9 +251,20 @@ impl LocalControlAdapter {}AgentFacetIntent::Keep => unreachable!(),};- let qoder_model_conflict = if pi_settings- .as_ref()- .is_some_and(|settings| settings.removes_default(&provider_id, &models))+ let dsh_default_in_use = kind == hiroute_domain::AgentKindV1::DeepseekHarness+ && self+ .scanner+ .dsh_web_default_in_use(&provider_id, &models)+ .map_err(|_| ControlReadError::Denied)?;+ let qoder_model_conflict = if dsh_default_in_use+ || pi_settings+ .as_ref()+ .is_some_and(|settings| settings.removes_default(&provider_id, &models))+ || (kind != hiroute_domain::AgentKindV1::Qoder+ && qoder_model_conflict+ == Some(+ hiroute_application::agent_connection::SettingsBlockReason::QoderDefaultInUse,+ )){Some(hiroute_application::agent_connection::SettingsBlockReason::AdditionalDefaultInUse)} else {@@ -281,10 +303,12 @@ impl LocalControlAdapter {capabilities.push(CapabilityEvidence {capability,state: CapabilityState::Proven,- adapter_contract: if kind == hiroute_domain::AgentKindV1::Pi {- "hiroute.pi-additional-model/v1"- } else {- "hiroute.qoder-additional-model/v1"+ adapter_contract: match kind {+ hiroute_domain::AgentKindV1::Pi => "hiroute.pi-additional-model/v1",+ hiroute_domain::AgentKindV1::DeepseekHarness => {+ "hiroute.dsh-additional-model/v1"+ }+ _ => "hiroute.qoder-additional-model/v1",}.into(),observed_at_unix_ms: self.now_ms()?.max(1) as u64,@@ -298,7 +322,9 @@ impl LocalControlAdapter {input.facts.model = Some(SettingsModelFacts {common: SettingsModelCommonFacts {ingress: protocol,- available_surfaces: [if kind == hiroute_domain::AgentKindV1::Pi {+ available_surfaces: [if kind == hiroute_domain::AgentKindV1::DeepseekHarness {+ AgentModelSurfaceV2::DshCli+ } else if kind == hiroute_domain::AgentKindV1::Pi {AgentModelSurfaceV2::PiCli} else {AgentModelSurfaceV2::QoderClidiff --git a/crates/daemon/src/control/runtime/settings_facts/qoder.rs b/crates/daemon/src/control/runtime/settings_facts/qoder.rsindex d226f8e9..2a356dcf 100644--- a/crates/daemon/src/control/runtime/settings_facts/qoder.rs+++ b/crates/daemon/src/control/runtime/settings_facts/qoder.rs@@ -8,7 +8,9 @@ impl LocalControlAdapter {spec: &AgentSettingsSpecV2,class: SettingsAgentClass,) -> Result<AgentSettingsPlanningInput, ControlReadError> {- let discovery = if class == SettingsAgentClass::Pi {+ let discovery = if class == SettingsAgentClass::Dsh {+ self.scanner.dsh_settings_discovery()+ } else if class == SettingsAgentClass::Pi {self.scanner.pi_settings_discovery()} else {self.scanner.qoder_settings_discovery(matches!(diff --git a/crates/daemon/src/control/runtime/settings_retry.rs b/crates/daemon/src/control/runtime/settings_retry.rsindex cb4f2157..5363e57f 100644--- a/crates/daemon/src/control/runtime/settings_retry.rs+++ b/crates/daemon/src/control/runtime/settings_retry.rs@@ -13,7 +13,12 @@ impl LocalControlAdapter {.settings_agent_for_context(&request.context_id).is_none_or(|class| {!class.is_codex()- && !matches!(class, SettingsAgentClass::Qoder | SettingsAgentClass::Pi)+ && !matches!(+ class,+ SettingsAgentClass::Qoder+ | SettingsAgentClass::Pi+ | SettingsAgentClass::Dsh+ )}){return Err(ControlReadError::Denied);@@ -38,7 +43,7 @@ impl LocalControlAdapter {}if matches!(self.settings_agent_for_context(&request.context_id),- Some(SettingsAgentClass::Qoder | SettingsAgentClass::Pi)+ Some(SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh)) {let intent = op.plandiff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rsindex 39ad94ae..9086e4ab 100644--- a/crates/daemon/src/control/runtime/settings_status.rs+++ b/crates/daemon/src/control/runtime/settings_status.rs@@ -203,7 +203,7 @@ impl LocalControlAdapter {ModelAction::Configure => {let file_applied = if matches!(class,- SettingsAgentClass::Qoder | SettingsAgentClass::Pi+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh) {hiroute_integrations::additional_native_configuration_is_applied(&self.artifacts,@@ -326,6 +326,10 @@ impl LocalControlAdapter {hiroute_domain::AgentModelSelectionV2::PiAdditional { .. },SettingsAgentClass::Pi,) => [hiroute_domain::AgentModelSurfaceV2::PiCli].into(),+ (+ hiroute_domain::AgentModelSelectionV2::DshAdditional { .. },+ SettingsAgentClass::Dsh,+ ) => [hiroute_domain::AgentModelSurfaceV2::DshCli].into(),_ => return Err(ControlReadError::Corrupt),};// The applied revision is the installed publication this configuration was@@ -460,7 +464,8 @@ fn model_intent(super::native_claude_model::is_settings_claude_model(intent)}super::settings_facts::SettingsAgentClass::Qoder- | super::settings_facts::SettingsAgentClass::Pi => {+ | super::settings_facts::SettingsAgentClass::Pi+ | super::settings_facts::SettingsAgentClass::Dsh => {super::native_additional_model::is_settings_additional_model(intent)}})@@ -472,7 +477,7 @@ fn model_action(intent: &hiroute_domain::ExternalEffectIntentV1,) -> hiroute_domain::PortResult<ModelAction> {match class {- super::settings_facts::SettingsAgentClass::Qoder | super::settings_facts::SettingsAgentClass::Pi => {+ super::settings_facts::SettingsAgentClass::Qoder | super::settings_facts::SettingsAgentClass::Pi | super::settings_facts::SettingsAgentClass::Dsh => {match hiroute_application::agent_connection::settings_additional_model_file_for_operation(operation, intent,)?diff --git a/crates/daemon/src/delegation/acp/identity.rs b/crates/daemon/src/delegation/acp/identity.rsindex fe8077a4..e7655860 100644--- a/crates/daemon/src/delegation/acp/identity.rs+++ b/crates/daemon/src/delegation/acp/identity.rs@@ -11,6 +11,7 @@ pub enum AcpNativeIdentityContract {CodexThreadV1,ClaudeSessionV1,QoderSessionV1,+ DshSessionV1,}impl AcpNativeIdentityContract {@@ -22,7 +23,10 @@ impl AcpNativeIdentityContract {match self {Self::Unverified => Ok(None),Self::ExplicitResponseMetadata => Ok(metadata_id(response)),- Self::CodexThreadV1 | Self::ClaudeSessionV1 | Self::QoderSessionV1 => {+ Self::CodexThreadV1+ | Self::ClaudeSessionV1+ | Self::QoderSessionV1+ | Self::DshSessionV1 => {if !valid_id(acp_id) {return Err(DelegationErrorV1::ProtocolFailed);}@@ -37,7 +41,10 @@ impl AcpNativeIdentityContract {Self::ExplicitResponseMetadata => {metadata_id(response).as_ref() == binding.native_session_id.as_ref()}- Self::CodexThreadV1 | Self::ClaudeSessionV1 | Self::QoderSessionV1 => {+ Self::CodexThreadV1+ | Self::ClaudeSessionV1+ | Self::QoderSessionV1+ | Self::DshSessionV1 => {valid_id(&binding.acp_session_id)&& binding.native_session_id.as_deref() == Some(binding.acp_session_id.as_str())}diff --git a/crates/daemon/src/delegation/acp/mod.rs b/crates/daemon/src/delegation/acp/mod.rsindex 8218d766..1c90e711 100644--- a/crates/daemon/src/delegation/acp/mod.rs+++ b/crates/daemon/src/delegation/acp/mod.rs@@ -4,7 +4,7 @@ use agent_client_protocol::schema::v1::{AuthenticateRequest, CancelNotification, ClientCapabilities, InitializeRequest,LoadSessionRequest, NewSessionRequest, PermissionOptionKind, PromptRequest,RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse,- SelectedPermissionOutcome, SessionNotification, SetSessionModeRequest,+ ResumeSessionRequest, SelectedPermissionOutcome, SessionNotification, SetSessionModeRequest,};use agent_client_protocol::{Agent, ConnectionTo};use hiroute_domain::delegation::DelegationErrorV1;@@ -32,6 +32,7 @@ pub use hiroute_domain::delegation::DelegationSessionBindingV1 as AcpSessionBindpub enum AcpSessionStart {New,Load(AcpSessionBinding),+ Resume(AcpSessionBinding),}/// Internal profile output, never a raw Local Control payload. Authentication can contain@@ -262,6 +263,39 @@ async fn run_session(response.config_options,)}+ AcpSessionStart::Resume(expected) => {+ if initialized+ .agent_capabilities+ .session_capabilities+ .resume+ .is_none()+ || input.identity_contract != AcpNativeIdentityContract::DshSessionV1+ || expected.native_session_id.as_deref() != Some(expected.acp_session_id.as_str())+ || expected.acp_session_id.is_empty()+ {+ return Err(DelegationErrorV1::ResumeUnavailable);+ }+ updates.lock().unwrap_or_else(|e| e.into_inner()).session =+ Some(expected.acp_session_id.clone());+ let request: ResumeSessionRequest = serde_json::from_value(json!({+ "sessionId":expected.acp_session_id,"cwd":input.cwd,"mcpServers":[],+ }))+ .map_err(|_| DelegationErrorV1::InvalidArguments)?;+ let response = phase(+ &input.cancellation,+ input.deadline,+ connection.send_request(request).block_task(),+ )+ .await+ .map_err(|error| {+ if error == DelegationErrorV1::ProtocolFailed {+ DelegationErrorV1::ResumeUnavailable+ } else {+ error+ }+ })?;+ (expected, response.modes, response.config_options)+ }AcpSessionStart::Load(expected) => {let prerequisites_ready = initialized.agent_capabilities.load_session&& expected.native_session_id.is_some()diff --git a/crates/daemon/src/delegation/acp/tests.rs b/crates/daemon/src/delegation/acp/tests.rsindex ba46e436..ef68a20c 100644--- a/crates/daemon/src/delegation/acp/tests.rs+++ b/crates/daemon/src/delegation/acp/tests.rs@@ -550,3 +550,64 @@ async fn pi_bridge_failure_preserves_the_failed_operation_without_replay() {);}}++#[tokio::test]+async fn dsh_continue_uses_exact_native_resume_and_never_falls_back_to_new() {+ for capable in [true, false] {+ let (client, server) = tokio::io::duplex(16_384);+ let server = tokio::spawn(async move {+ let (reader, mut writer) = tokio::io::split(server);+ let mut lines = BufReader::new(reader).lines();+ let mut methods = vec![];+ while let Some(line) = lines.next_line().await.unwrap() {+ let request: Value = serde_json::from_str(&line).unwrap();+ let method = request["method"].as_str().unwrap();+ methods.push(method.to_owned());+ let result = match method {+ "initialize" => json!({"protocolVersion":1,"agentCapabilities":{+ "sessionCapabilities":if capable { json!({"resume":{}}) } else { json!({}) }+ }}),+ "session/resume" => {+ assert_eq!(request["params"]["sessionId"], "exact-native-session");+ assert_eq!(+ request["params"]["cwd"],+ serde_json::to_value(std::env::temp_dir()).unwrap()+ );+ json!({})+ }+ "session/prompt" => json!({"stopReason":"end_turn"}),+ other => panic!("unexpected DSH method: {other}"),+ };+ writer+ .write_all(+ format!(+ "{}\n",+ json!({"jsonrpc":"2.0","id":request["id"],"result":result})+ )+ .as_bytes(),+ )+ .await+ .unwrap();+ }+ methods+ });+ let mut request = input();+ request.identity_contract = AcpNativeIdentityContract::DshSessionV1;+ request.session = AcpSessionStart::Resume(AcpSessionBinding {+ acp_session_id: "exact-native-session".into(),+ native_session_id: Some("exact-native-session".into()),+ });+ let (read, write) = tokio::io::split(client);+ let result = run_acp(read, write, request, Arc::new(Journal::default())).await;+ if capable {+ assert!(result.is_ok());+ assert_eq!(+ server.await.unwrap(),+ ["initialize", "session/resume", "session/prompt"]+ );+ } else {+ assert_eq!(result.err(), Some(DelegationErrorV1::ResumeUnavailable));+ assert_eq!(server.await.unwrap(), ["initialize"]);+ }+ }+}diff --git a/crates/daemon/src/delegation/executor.rs b/crates/daemon/src/delegation/executor.rsindex 76547fe2..3acd83d4 100644--- a/crates/daemon/src/delegation/executor.rs+++ b/crates/daemon/src/delegation/executor.rs@@ -325,7 +325,12 @@ impl DelegationRunExecutor {(Some(previous), Some(binding))if previous != &run.run_id && binding.native_session_id.is_some() =>{- AcpSessionStart::Load(binding.clone())+ if task.plan.harness == hiroute_domain::delegation::WorkerHarnessV1::DeepseekHarness+ {+ AcpSessionStart::Resume(binding.clone())+ } else {+ AcpSessionStart::Load(binding.clone())+ }}_ => return Err(DelegationErrorV1::ResumeUnavailable),};@@ -446,7 +451,8 @@ impl DelegationRunExecutor {}let identity_contract = profile.identity_contract.clone();let session_meta = profile.session_meta.clone();- let native_session_mode = Some(profile.native_session_mode().to_owned());+ let native_session_mode = (!profile.native_session_mode().is_empty())+ .then(|| profile.native_session_mode().to_owned());let expected_model = Some(profile.native_selected_model_id().to_owned());let cwd = profile.cwd.clone();let launch = WorkerLaunchRequest {diff --git a/crates/daemon/src/delegation/installation.rs b/crates/daemon/src/delegation/installation.rsindex bddac9d9..f82ebbf4 100644--- a/crates/daemon/src/delegation/installation.rs+++ b/crates/daemon/src/delegation/installation.rs@@ -30,11 +30,12 @@ pub(crate) use discovery::{validate_selection,};-const WORKER_HARNESSES: [WorkerHarnessV1; 4] = [+const WORKER_HARNESSES: [WorkerHarnessV1; 5] = [WorkerHarnessV1::CodexCli,WorkerHarnessV1::ClaudeCode,WorkerHarnessV1::QoderCli,WorkerHarnessV1::Pi,+ WorkerHarnessV1::DeepseekHarness,];#[derive(Clone, Debug)]@@ -304,7 +305,7 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {)?;if matches!(installation.harness,- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness) && input.run.configuration.permission_policy!= hiroute_domain::delegation::WorkerPermissionPolicyV1::ApproveAll{@@ -453,7 +454,7 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {}None if matches!(installation.harness,- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness) =>{return Err(DelegationErrorV1::ResumeUnavailable);@@ -486,10 +487,13 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {}let qoder_budget = (matches!(installation.harness,- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness)).then(|| {- if installation.harness == WorkerHarnessV1::Pi {+ if matches!(+ installation.harness,+ WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness+ ) {hiroute_integrations::agents::pi_plan_token_budget(&input.compiled_plan.body.materialized,)diff --git a/crates/daemon/src/delegation/installation/discovery.rs b/crates/daemon/src/delegation/installation/discovery.rsindex 30bb2d16..3d7664bc 100644--- a/crates/daemon/src/delegation/installation/discovery.rs+++ b/crates/daemon/src/delegation/installation/discovery.rs@@ -478,7 +478,9 @@ impl HarnessScan {package_root: &Path,source: WorkerDependencyCandidateSourceV1,) {- let adapter = if self.harness == WorkerHarnessV1::Pi {+ let adapter = if self.harness == WorkerHarnessV1::DeepseekHarness {+ "dsh"+ } else if self.harness == WorkerHarnessV1::Pi {"pi"} else {let Some(adapter) = names(self.harness).1 else {@@ -498,7 +500,10 @@ impl HarnessScan {}};self.add_discovered(- if self.harness == WorkerHarnessV1::Pi {+ if matches!(+ self.harness,+ WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness+ ) {WorkerDependencyComponentV1::Cli} else {WorkerDependencyComponentV1::Adapter@@ -567,8 +572,10 @@ impl HarnessScan {WorkerDependencyComponentV1::Adapter,WorkerDependencyComponentV1::Node,] {- if (self.harness == WorkerHarnessV1::QoderCli- && component != WorkerDependencyComponentV1::Cli)+ if (matches!(+ self.harness,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::DeepseekHarness+ ) && component != WorkerDependencyComponentV1::Cli)|| (self.harness == WorkerHarnessV1::Pi&& component == WorkerDependencyComponentV1::Adapter){@@ -582,9 +589,15 @@ impl HarnessScan {harness: self.harness,component,platform: platform().to_owned(),- command: (self.harness == WorkerHarnessV1::Pi- && component == WorkerDependencyComponentV1::Cli)- .then(|| "npm install -g @earendil-works/pi-coding-agent".into()),+ command: if self.harness == WorkerHarnessV1::DeepseekHarness+ && component == WorkerDependencyComponentV1::Cli+ {+ Some("npm install -g @deepseek-ai/dsh".into())+ } else {+ (self.harness == WorkerHarnessV1::Pi+ && component == WorkerDependencyComponentV1::Cli)+ .then(|| "npm install -g @earendil-works/pi-coding-agent".into())+ },reason_code: "worker.dependencies.install_required".to_owned(),});}@@ -719,6 +732,7 @@ fn names(harness: WorkerHarnessV1) -> (&'static [&'static str], Option<&'staticWorkerHarnessV1::ClaudeCode => (&["claude"], Some("claude-agent-acp")),WorkerHarnessV1::QoderCli => (&["qoder", "qodercli"], None),WorkerHarnessV1::Pi => (&["pi"], None),+ WorkerHarnessV1::DeepseekHarness => (&["dsh"], None),}}@@ -728,6 +742,7 @@ fn package_name(harness: WorkerHarnessV1) -> Option<&'static Path> {WorkerHarnessV1::ClaudeCode => Some(Path::new("@agentclientprotocol/claude-agent-acp")),WorkerHarnessV1::QoderCli => None,WorkerHarnessV1::Pi => Some(Path::new("@earendil-works/pi-coding-agent")),+ WorkerHarnessV1::DeepseekHarness => Some(Path::new("@deepseek-ai/dsh")),}}diff --git a/crates/daemon/src/delegation/installation/installation_probe.rs b/crates/daemon/src/delegation/installation/installation_probe.rsindex 5c744d2b..981bf5af 100644--- a/crates/daemon/src/delegation/installation/installation_probe.rs+++ b/crates/daemon/src/delegation/installation/installation_probe.rs@@ -258,7 +258,9 @@ fn harness_kind(harness: WorkerHarnessV1) -> HarnessKind {WorkerHarnessV1::CodexCli => HarnessKind::Codex,WorkerHarnessV1::ClaudeCode => HarnessKind::Claude,// This historical adapter-only, private-HOME probe is not Qoder acceptance.- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => HarnessKind::Unknown,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness => {+ HarnessKind::Unknown+ }}}diff --git a/crates/daemon/src/delegation/installation/probe_server.rs b/crates/daemon/src/delegation/installation/probe_server.rsindex 9f758c67..b94ded61 100644--- a/crates/daemon/src/delegation/installation/probe_server.rs+++ b/crates/daemon/src/delegation/installation/probe_server.rs@@ -327,7 +327,7 @@ fn serve_probe_request(let response = match endpoint.harness {WorkerHarnessV1::CodexCli => responses_stream(endpoint.model),WorkerHarnessV1::ClaudeCode => messages_stream(endpoint.model),- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => {+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness => {return Err(DelegationErrorV1::CapabilityUnavailable);}};diff --git a/crates/daemon/src/delegation/lifecycle.rs b/crates/daemon/src/delegation/lifecycle.rsindex 77770fa3..a7244304 100644--- a/crates/daemon/src/delegation/lifecycle.rs+++ b/crates/daemon/src/delegation/lifecycle.rs@@ -40,7 +40,8 @@ impl ClaudeHistoryCheckpoint {}let baseline = match &input.session {super::acp::AcpSessionStart::New => HistoryBaseline::New,- super::acp::AcpSessionStart::Load(binding) => binding+ super::acp::AcpSessionStart::Load(binding)+ | super::acp::AcpSessionStart::Resume(binding) => binding.native_session_id.as_deref().and_then(|id| claude_history_len(&profile.session_root, id))diff --git a/crates/daemon/src/delegation/profile/capabilities.rs b/crates/daemon/src/delegation/profile/capabilities.rsindex 6607b480..650def80 100644--- a/crates/daemon/src/delegation/profile/capabilities.rs+++ b/crates/daemon/src/delegation/profile/capabilities.rs@@ -5,7 +5,7 @@ pub(super) fn identity_contract() -> Result<AcpNativeIdentityContract, DelegationErrorV1> {if matches!(input.harness,- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness) && !input.native_context.is_borrowed(){return Err(DelegationErrorV1::CapabilityUnavailable);@@ -14,7 +14,10 @@ pub(super) fn identity_contract(// modes have no proven permission contract; neither client may silently upgrade them.if matches!(input.harness,- WorkerHarnessV1::CodexCli | WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ WorkerHarnessV1::CodexCli+ | WorkerHarnessV1::QoderCli+ | WorkerHarnessV1::Pi+ | WorkerHarnessV1::DeepseekHarness) && input.permission_policy != WorkerPermissionPolicyV1::ApproveAll{return Err(DelegationErrorV1::CapabilityUnavailable);@@ -24,5 +27,6 @@ pub(super) fn identity_contract(WorkerHarnessV1::ClaudeCode => AcpNativeIdentityContract::ClaudeSessionV1,WorkerHarnessV1::QoderCli => AcpNativeIdentityContract::QoderSessionV1,WorkerHarnessV1::Pi => AcpNativeIdentityContract::ExplicitResponseMetadata,+ WorkerHarnessV1::DeepseekHarness => AcpNativeIdentityContract::DshSessionV1,})}diff --git a/crates/daemon/src/delegation/profile/dsh.rs b/crates/daemon/src/delegation/profile/dsh.rsnew file mode 100644index 00000000..ff7d423f--- /dev/null+++ b/crates/daemon/src/delegation/profile/dsh.rs@@ -0,0 +1,83 @@+//! DSH's public CLI/configuration and ACP transport; no native SDK or history decoder.+use super::*;++pub(super) fn render(+ input: &ProfileInput<'_>,+) -> Result<RenderedHarnessProfile, DelegationErrorV1> {+ let context = input+ .context_window_tokens+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;+ let output = input+ .max_output_tokens+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;+ if output == 0 || context <= output || context > (1 << 53) - 1 {+ return Err(DelegationErrorV1::CapabilityUnavailable);+ }+ let provider = "hiroute-worker";+ let (api, endpoint) = hiroute_integrations::agents::pi_native_provider_api(+ input.protocol,+ &format!("http://{}/v1", input.gateway),+ )+ .map(|(api, endpoint)| (api, endpoint.to_owned()))+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;+ let state = input.session_root.path().join("native-dsh");+ // JSON is a YAML subset. Only public stock-composition IDs are overridden;+ // secret values are referenced by name, never persisted in this overlay.+ let mut patch = vec![+ json!({"id":"llm-pi-ai","config":{"providers":{provider:{+ "apiKeyEnv":"HIROUTE_RUN_TOKEN","api":api,"baseURL":endpoint,+ "models":[{"id":input.alias,"contextWindow":context,"maxTokens":output,"input":["text"]}]+ }}}}),+ json!({"id":"acp","config":{"provider":provider,"model":input.alias}}),+ json!({"id":"agent-default-model","config":{"provider":provider,"model":input.alias}}),+ json!({"id":"session-persistence-jsonl","config":{"root":state.join("sessions"),"compression":"none"}}),+ json!({"id":"attachment-local","config":{"dshHome":state}}),+ // Keep native Skill roots and customSkillDirs from the borrowed composition.+ json!({"id":"tool-bash","config":{"enableRunInBackground":false,"promoteOnTimeout":false}}),+ json!({"id":"tool-terminal","config":{"enableRunInBackground":false}}),+ json!({"id":"session-log-deepseek","config":{"enabled":false}}),+ ];+ for id in [+ "llm-deepseek",+ "llm-deepseek-account",+ "session-telemetry-otel",+ "session-title-llm",+ "tool-subagent",+ "tool-subagent-fork",+ "tool-subagent-control",+ "tool-subagent-list-agents",+ "tool-workflow",+ "tool-goal",+ "tool-ralph",+ "tool-web",+ ] {+ patch.push(json!({"id":id,"disabled":true}));+ }+ let relative = PathBuf::from("dsh-worker.patch.yml");+ let mut rendered = RenderedHarnessProfile {+ native_model_id: json!([provider, input.alias]).to_string(),+ native_args: vec![+ "--profile".into(),+ "acp".into(),+ "--patch".into(),+ input.private_root.join(&relative),+ ],+ files: vec![RunMaterialFile {+ relative_path: relative,+ contents: Zeroizing::new(+ serde_json::to_vec(&patch).map_err(|_| DelegationErrorV1::InvalidArguments)?,+ ),+ executable: false,+ }],+ ..Default::default()+ };+ for (name, value) in [+ ("DSH_HOME", path_string(input.native_context.config_root())?),+ ("DSH_PERMISSION_MODE", "danger-full-access".into()),+ ("DSH_TELEMETRY_DISABLED", "1".into()),+ ("HIROUTE_RUN_TOKEN", secret_string(&input.token)?),+ ] {+ rendered.env.insert(name.into(), Zeroizing::new(value));+ }+ Ok(rendered)+}diff --git a/crates/daemon/src/delegation/profile/materials.rs b/crates/daemon/src/delegation/profile/materials.rsindex 18da8478..5f69b07b 100644--- a/crates/daemon/src/delegation/profile/materials.rs+++ b/crates/daemon/src/delegation/profile/materials.rs@@ -380,7 +380,10 @@ fn legacy_native_history(native_session_id: &str,) -> Result<Vec<String>, DelegationErrorV1> {// Qoder has only the borrowed-context contract, never a private legacy reader.- if matches!(harness, WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi) {+ if matches!(+ harness,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness+ ) {return Err(DelegationErrorV1::ResumeUnavailable);}if native_session_id.is_empty()@@ -406,7 +409,7 @@ fn legacy_native_history(let durable_root = root.join(match harness {WorkerHarnessV1::CodexCli => "sessions",WorkerHarnessV1::ClaudeCode => "projects",- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => {+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness => {return Err(DelegationErrorV1::ResumeUnavailable);}});@@ -449,7 +452,9 @@ fn legacy_native_history(let matches_session = match harness {WorkerHarnessV1::CodexCli => file_name.ends_with(&codex_suffix),WorkerHarnessV1::ClaudeCode => file_name == claude_name,- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => {+ WorkerHarnessV1::QoderCli+ | WorkerHarnessV1::Pi+ | WorkerHarnessV1::DeepseekHarness => {return Err(DelegationErrorV1::ResumeUnavailable);}};diff --git a/crates/daemon/src/delegation/profile/mod.rs b/crates/daemon/src/delegation/profile/mod.rsindex a322c220..7789ad72 100644--- a/crates/daemon/src/delegation/profile/mod.rs+++ b/crates/daemon/src/delegation/profile/mod.rs@@ -17,6 +17,7 @@ mod capabilities;mod claude;mod claude_runtime;mod codex;+mod dsh;mod native_context;mod pi;mod qoder;@@ -161,6 +162,10 @@ impl CandidateWorkerProfile {(WorkerHarnessV1::QoderCli, WorkerPermissionPolicyV1::ApproveAll) => "yolo",(WorkerHarnessV1::Pi, WorkerPermissionPolicyV1::ApproveAll) => "approve-all",(WorkerHarnessV1::Pi, _) => return Err(DelegationErrorV1::CapabilityUnavailable),+ (WorkerHarnessV1::DeepseekHarness, WorkerPermissionPolicyV1::ApproveAll) => "",+ (WorkerHarnessV1::DeepseekHarness, _) => {+ return Err(DelegationErrorV1::CapabilityUnavailable);+ }(WorkerHarnessV1::QoderCli, _) => return Err(DelegationErrorV1::CapabilityUnavailable),};let mut env = BTreeMap::new();@@ -202,6 +207,7 @@ impl CandidateWorkerProfile {WorkerHarnessV1::ClaudeCode => claude::render(&input, &projected_tools)?,WorkerHarnessV1::QoderCli => qoder::render(&input, &private_root)?,WorkerHarnessV1::Pi => pi::render(&input)?,+ WorkerHarnessV1::DeepseekHarness => dsh::render(&input)?,};env.extend(rendered.env);let (executable, args) = match launch {diff --git a/crates/daemon/src/delegation/profile/native_context.rs b/crates/daemon/src/delegation/profile/native_context.rsindex 44a2bdb1..47f948b6 100644--- a/crates/daemon/src/delegation/profile/native_context.rs+++ b/crates/daemon/src/delegation/profile/native_context.rs@@ -27,6 +27,7 @@ impl NativeWorkerContext {WorkerHarnessV1::CodexCli => ("CODEX_HOME", ".codex"),WorkerHarnessV1::ClaudeCode => ("CLAUDE_CONFIG_DIR", ".claude"),WorkerHarnessV1::Pi => ("PI_CODING_AGENT_DIR", ".pi/agent"),+ WorkerHarnessV1::DeepseekHarness => ("DSH_HOME", ".dsh"),WorkerHarnessV1::QoderCli => {let selected = lookup("QODER_CONFIG_DIR").map(PathBuf::from);let context = hiroute_integrations::agents::QoderNativeContext::from_selected(diff --git a/crates/daemon/src/delegation/profile/native_history.rs b/crates/daemon/src/delegation/profile/native_history.rsindex 35b128d4..c5e31116 100644--- a/crates/daemon/src/delegation/profile/native_history.rs+++ b/crates/daemon/src/delegation/profile/native_history.rs@@ -117,7 +117,12 @@ pub(super) fn read_context(return match fs::symlink_metadata(root.join(SESSION_FILE)) {Err(error)if error.kind() == std::io::ErrorKind::NotFound- && !matches!(harness, WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi) =>+ && !matches!(+ harness,+ WorkerHarnessV1::QoderCli+ | WorkerHarnessV1::Pi+ | WorkerHarnessV1::DeepseekHarness+ ) =>{Ok(None)}diff --git a/crates/daemon/src/delegation/profile/tests.rs b/crates/daemon/src/delegation/profile/tests.rsindex 4fbeb2d6..620cd640 100644--- a/crates/daemon/src/delegation/profile/tests.rs+++ b/crates/daemon/src/delegation/profile/tests.rs@@ -207,7 +207,9 @@ fn try_request_in_context(WorkerHarnessV1::CodexCli | WorkerHarnessV1::ClaudeCode => {Some(Path::new("/trusted/adapter"))}- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => None,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness => {+ None+ }},harness_binary,node_binary,diff --git a/crates/daemon/src/delegation/run_authority.rs b/crates/daemon/src/delegation/run_authority.rsindex 669826c3..f23e7c23 100644--- a/crates/daemon/src/delegation/run_authority.rs+++ b/crates/daemon/src/delegation/run_authority.rs@@ -281,6 +281,7 @@ fn build_entry(hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode => "claude",hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "qoder",hiroute_domain::delegation::WorkerHarnessV1::Pi => "pi",+ hiroute_domain::delegation::WorkerHarnessV1::DeepseekHarness => "dsh",},task.session.as_ref()diff --git a/crates/daemon/tests/support/additional_model_fixture.py b/crates/daemon/tests/support/additional_model_fixture.pyindex 857d7c8b..f85c22ed 100644--- a/crates/daemon/tests/support/additional_model_fixture.py+++ b/crates/daemon/tests/support/additional_model_fixture.py@@ -1,4 +1,4 @@-"""Owned native settings and reads for Qoder/Pi persisted-model product journeys.+"""Owned native settings and reads for Qoder/Pi/DSH persisted-model product journeys.Only this leaf may write the explicitly selected MODEL context. It never readsauthentication, and it never supplies native provider/settings/credential overrides.@@ -27,6 +27,10 @@ def select_model_context(product, harness="qoder"):config.mkdir(mode=0o700, parents=True)product.env["PI_CODING_AGENT_DIR"] = str(config)return config+ if harness == "dsh":+ config = Path(product.env["DSH_HOME"])+ (config / 'profiles/web').mkdir(mode=0o700, parents=True, exist_ok=True)+ return confighome = selected_directory('HIROUTE_QODER_MODEL_CONTEXT_HOME')config = selected_directory('HIROUTE_QODER_MODEL_CONFIG_DIR')assert home != Path.home().resolve() and config.is_relative_to(home), \@@ -36,6 +40,11 @@ def select_model_context(product, harness="qoder"):class OwnedModelSettings:+ def __new__(cls, config, foreign_endpoint, harness="qoder"):+ if harness == 'dsh':+ from dsh_native_context import DshModelSettings+ return DshModelSettings(config, foreign_endpoint)+ return super().__new__(cls)"""Seed a synthetic user baseline; undo only our unchanged final baseline."""def __init__(self, config, foreign_endpoint, harness="qoder"):self.harness = harness@@ -102,7 +111,7 @@ class OwnedModelSettings:actual['providers'].pop(name)expected = deepcopy(self.baseline)if selected_default is not None:- if self.harness == 'qoder':+ if self.harness in ('qoder','dsh'):expected['model']['name'] = selected_defaultif self.harness == 'pi':default = dict(self.default_baseline)@@ -225,13 +234,20 @@ def successful_native_result(stdout, receipt, harness='qoder'):def read_persisted_route(product, binary, selector, source, oracle, label):prompt = oracle.arm(label)before = len(oracle.calls)- command = native_command(product, binary, selector, prompt)# Product already strips inherited provider/auth variables. Only its selected# native config root and private runtime/receipt roots enter this process.harness = getattr(product, 'additional_harness', 'qoder')- stdout = run_native_command(product, command, timeout=60, label=f'ordinary {harness} model invocation')+ if harness == 'dsh':+ from native_acp_client import prompt as acp_prompt+ saved = Path(product.env['DSH_HOME']) / 'profiles/web/cordis.patch.yml'+ stdout, native_session_id = acp_prompt(product,+ [str(binary),'--profile','acp','--patch',str(saved)], prompt, selector)+ assert stdout.decode().strip() == oracle.receipt, 'native DSH result lost source receipt'+ else:+ stdout = run_native_command(product, native_command(product,binary,selector,prompt),+ timeout=60,label=f'ordinary {harness} model invocation')+ native_session_id = successful_native_result(stdout, oracle.receipt, harness)assert oracle.calls[before:] == [label], f'ordinary {harness} did not make one actual persisted-route request'- native_session_id = successful_native_result(stdout, oracle.receipt, harness)from native_context_boundaries import source_eventsobserved_protocol = source_events(source)[-1]['protocol']if hasattr(source, 'expected_protocol'):diff --git a/crates/daemon/tests/support/additional_model_product.py b/crates/daemon/tests/support/additional_model_product.pyindex d8386f28..3403ce14 100644--- a/crates/daemon/tests/support/additional_model_product.py+++ b/crates/daemon/tests/support/additional_model_product.py@@ -79,7 +79,7 @@ def assert_saved_aliases(settings, provider, aliases):models = [model for name, value in settings.read()['providers'].items() if name == provider or name.startswith(provider + '-') for model in value['models']]for alias in aliases:assert len(settings.read()['providers'][persisted_plan_provider(settings, provider, alias)]['models']) == 1- assert len(models) == len(aliases) and {item['id' if HARNESS == 'pi' else 'model'] for item in models} == set(aliases), \+ assert len(models) == len(aliases) and {item['id' if HARNESS in ('pi','dsh') else 'model'] for item in models} == set(aliases), \'persisted native choices do not match the selected routes'@@ -110,7 +110,7 @@ def reject_gateway_request(product, token, alias, protocol, sources, expected_coif protocol == 'responses' else {'model': alias, 'messages': [{'role':'user','content':'Untrusted removed route'}],'max_tokens':16, 'stream':True})client.request('POST', TAIL + '/' + protocol, body=encoded(body),- headers={'Content-Type': 'application/json', **({'X-HiRoute-Token':token} if HARNESS == 'pi'+ headers={'Content-Type': 'application/json', **({'X-HiRoute-Token':token} if HARNESS in ('pi','dsh')else {'Authorization':'Bearer ' + token})})response = client.getresponse()error = json.loads(response.read())@@ -133,7 +133,7 @@ def assert_default_blocks_removal(product, context, settings, provider, plans, scommand = 'agents restore' if spec['model']['intent'] == 'restore' else 'agents connect'preview = product.preview(command + ' preview', {'spec': spec})assert not preview['applicable'] and any(- item['reason'] == ('additional_default_in_use' if HARNESS == 'pi' else 'qoder_default_in_use') for item in preview['blockers']), \+ item['reason'] == ('additional_default_in_use' if HARNESS in ('pi','dsh') else 'qoder_default_in_use') for item in preview['blockers']), \'removing the selected native default must fail closed'assert digest(settings.path) == before and digest(skill) == skill_before, 'blocked removal changed files'assert settings_status(product, context) == status, 'blocked removal changed settings authority'@@ -158,10 +158,10 @@ def run(repository, candidate):global HARNESS, AGENT, MODE, TAILPLAN_PROTOCOLS.clear()HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS', 'qoder')- assert HARNESS in ('qoder', 'pi')+ assert HARNESS in ('qoder', 'pi', 'dsh')AGENT = 'agent_' + HARNESS + '_default'MODE = HARNESS + '_additional'- TAIL = '/v1' if HARNESS == 'pi' else '/_hiroute/qoder/v1'+ TAIL = '/v1' if HARNESS in ('pi','dsh') else '/_hiroute/qoder/v1'repo = Path(repository).resolve()assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidateproduct = Product(repo)@@ -236,7 +236,7 @@ def run(repository, candidate):stage = 'independent-model-and-skill'(config / 'skills').mkdir(mode=0o700, exist_ok=True)- skill = (config / 'skills/hiroute-collaboration/SKILL.md' if HARNESS == 'pi' else+ skill = (config / 'skills/hiroute-collaboration/SKILL.md' if HARNESS in ('pi','dsh') elseqoder_native_context.prepare_collaboration_target(product))before_skill = skill.read_bytes() if skill.exists() else Nonecheck_collaboration(product, 'model-skill-preflight')diff --git a/crates/daemon/tests/support/agent_product_support.py b/crates/daemon/tests/support/agent_product_support.pyindex e79d4e02..1308b1d7 100644--- a/crates/daemon/tests/support/agent_product_support.py+++ b/crates/daemon/tests/support/agent_product_support.py@@ -7,9 +7,13 @@ from pathlib import Pathdef expose_native_installation(product, harness, binary, node=None):"""Expose selected native entries in the fixture's private PATH, never the host PATH."""- assert harness in ('pi', 'qoder')+ assert harness in ('pi', 'qoder', 'dsh')assert harness != 'pi' or node is not None, 'Pi fixture requires its selected Node'- entries = [('pi' if harness == 'pi' else 'qodercli', binary)]+ entries = [({'pi':'pi','qoder':'qodercli','dsh':'dsh'}[harness], binary)]+ if harness == 'dsh':+ import shutil+ runtime = Path(shutil.which('node')).resolve(strict=True)+ entries.append(('node',runtime))if harness == 'pi':entries.append(('node', node))for name, path in entries:diff --git a/crates/daemon/tests/support/collaboration_fixture.py b/crates/daemon/tests/support/collaboration_fixture.pyindex f3461908..631a083a 100644--- a/crates/daemon/tests/support/collaboration_fixture.py+++ b/crates/daemon/tests/support/collaboration_fixture.py@@ -51,6 +51,9 @@ def worker_decision(fixture, body):return actioncommand = ('/usr/bin/printf "%s\\n" ' + shlex.quote(artifact['receipt']) + ' > ' +shlex.quote(artifact['path']) + ' && /bin/cat ' + shlex.quote(artifact['path']))+ if fixture.get('harness') == 'dsh':+ return dict(kind='tool',id='delegated_artifact',name='bash',+ arguments={'command':command,'description':'Write delegated receipt','timeoutMs':10000})return dict(kind='tool', id='delegated_artifact', name='bash' if fixture.get('harness') == 'pi' else 'Bash',arguments={'command': command, 'timeout': 10 if fixture.get('harness') == 'pi' else 10000})@@ -75,12 +78,20 @@ class MainAgentOracle:assert self.fixture['main_marker'] in rendered, 'Worker request reached the main Agent source'results = tool_results(body, self.fixture.get('harness', 'qoder'))names = {item.get('name') for item in body.get('tools', [])}- if self.fixture.get('harness') == 'pi':+ if self.fixture.get('harness') == 'dsh':+ assert {'skill','bash'} <= names, 'native DSH Skill/bash tools unavailable'+ if 'main_skill' not in results:+ assert 'hiroute-collaboration' in rendered, 'installed user collaboration Skill not discovered'+ return dict(kind='tool',id='main_skill',name='skill',arguments={'name':'hiroute-collaboration'})+ loaded = results['main_skill']+ assert 'Base directory for this skill: '+str(self.skill.parent) in loaded, 'native Skill loaded a different directory'+ assert all(line in loaded for line in self.skill_body.splitlines() if line.strip()), 'actual user Skill body was not loaded'+ elif self.fixture.get('harness') == 'pi':assert {'read','bash'} <= names, 'native Pi read/bash tools unavailable'if 'main_skill' not in results:- assert 'hiroute-collaboration' in rendered and str(self.skill) in rendered- return dict(kind='tool', id='main_skill', name='read', arguments={'path':str(self.skill)})- assert self.skill_body in results['main_skill'], 'actual user Skill body was not read'+ assert 'hiroute-collaboration' in rendered and str(self.skill) in rendered, 'installed collaboration Skill summary/path unavailable'+ return dict(kind='tool', id='main_skill', name='read', arguments={('file_path' if self.fixture.get('harness')=='dsh' else 'path'):str(self.skill)})+ assert all(line in results['main_skill'] for line in self.skill_body.splitlines() if line.strip()), 'actual user Skill body was not read'else:assert {'Skill', 'Bash'} <= names, 'native main Agent Skill/Bash tools unavailable'if 'main_skill' not in results:@@ -97,7 +108,7 @@ class MainAgentOracle:return self.bash('main_plans', shlex.quote(self.cli) + ' worker plans --output json')directory = output_envelope(results['main_plans'])plans = [plan for plan in directory['plans'] if plan['agent_plan_id'] == self.fixture['plan_id']]- assert len(plans) == 1 and plans[0]['harness'] == ('pi' if self.fixture.get('harness') == 'pi' else 'qoder_cli') and plans[0]['availability'] == 'ready', \+ assert len(plans) == 1 and plans[0]['harness'] == {'pi':'pi','dsh':'deepseek_harness','qoder':'qoder_cli'}[self.fixture.get('harness','qoder')] and plans[0]['availability'] == 'ready', \'the public directory did not offer the published Qoder Worker Plan'if 'main_exec' not in results:prompt = 'Use ' + ' and '.join(item['name'] for item in self.fixture['skills']) + \@@ -155,6 +166,9 @@ class MainAgentOracle:'public observation switched the accepted Worker identity'def bash(self, call_id, command, timeout=10000):+ if self.fixture.get("harness") == "dsh":+ return dict(kind="tool",id=call_id,name="bash",+ arguments={"command":command,"description":"Use public HiRoute CLI","timeoutMs":timeout})pi = self.fixture.get("harness") == "pi"return dict(kind="tool", id=call_id, name="bash" if pi else "Bash",arguments={"command":command,"timeout":timeout / 1000 if pi else timeout})diff --git a/crates/daemon/tests/support/collaboration_product.py b/crates/daemon/tests/support/collaboration_product.pyindex 4d44b4a8..4355d622 100644--- a/crates/daemon/tests/support/collaboration_product.py+++ b/crates/daemon/tests/support/collaboration_product.py@@ -43,6 +43,16 @@ def apply_collaboration(product, context, intent, key):def run_main_agent(product, binary, upstream, fixture):+ if HARNESS == 'dsh':+ from dsh_native_context import main_route_patch+ from native_acp_client import prompt+ patch = main_route_patch(product,upstream.base_url,upstream.model)+ stdout,_ = prompt(product,[str(binary),'--profile','acp','--patch',str(patch)],+ fixture['main_marker']+': Read hiroute-collaboration and delegate the native receipt task.',+ 'hiroute-main-acceptance/'+upstream.model,+ env=dict(product.env,HIROUTE_DSH_MAIN_TOKEN=upstream.token))+ assert ('MAIN-AGENT-COMPLETED-'+fixture['artifact']['receipt']).encode() in stdout+ returnif HARNESS == 'pi':config = Path(fixture['config'])models = json.loads((config / 'models.json').read_text())@@ -131,7 +141,7 @@ def finish_collaboration(product, sources, restore, report, stage, primary_failudef run(repository, candidate):global HARNESS, AGENTHARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','qoder')- assert HARNESS in ('qoder','pi')+ assert HARNESS in ('qoder','pi','dsh')AGENT = 'agent_' + HARNESS + '_default'repo = Path(repository).resolve()assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate@@ -156,7 +166,7 @@ def run(repository, candidate):fixture, worker_source = prepare_product(product, HARNESS)report['source_context_tokens'] = fixture['source_context_tokens']sources.append(worker_source)- configure_worker_installation(product, 'pi' if HARNESS == 'pi' else 'qoder_cli', None, binary, node)+ configure_worker_installation(product, {'pi':'pi','qoder':'qoder_cli','dsh':'deepseek_harness'}[HARNESS], None, binary, node)if HARNESS == 'pi':# Main CLI follows native auth behavior; the Worker-only helper trap is# covered by the core journey, not executed by the main Agent fixture.@@ -169,7 +179,7 @@ def run(repository, candidate):receipt='QODER-WORKER-' + secrets.token_hex(16))(product.root / 'native-context.json').write_text(json.dumps(fixture))worker_source.reply = worker_decision- skill = (Path(fixture['config']) / 'skills/hiroute-collaboration/SKILL.md' if HARNESS == 'pi' else+ skill = (Path(fixture['config']) / 'skills/hiroute-collaboration/SKILL.md' if HARNESS in ('pi','dsh') elseqoder_native_context.prepare_collaboration_target(product))assert not skill.is_symlink(), 'user collaboration Skill is a symlink'before_skill = skill.read_bytes() if skill.exists() else None@@ -206,7 +216,7 @@ def run(repository, candidate):wait_for_resumable_task(product, oracle.accepted['task_id'], oracle.accepted['run_id'])report.update(task_id=oracle.accepted['task_id'], run_id=oracle.accepted['run_id'],native_session_id=(__import__('pi_native_context').exact_history(dict(fixture, receipt=fixture['artifact']['receipt']))[1] if HARNESS == 'pi'- else qoder_native_context.task_binding(fixture)),+ else __import__('dsh_native_context').exact_history(dict(fixture,receipt=fixture['artifact']['receipt']))[1] if HARNESS == 'dsh' else qoder_native_context.task_binding(fixture)),main_requests=len(source_events(main_source)), worker_requests=len(source_events(worker_source)),actual_user_skill_sha256=digest(skill), artifact_sha256=digest(fixture['artifact']['path']),main_worker_distinct_sources=True,diff --git a/crates/daemon/tests/support/dsh_native_context.py b/crates/daemon/tests/support/dsh_native_context.pynew file mode 100644index 00000000..6d4a4317--- /dev/null+++ b/crates/daemon/tests/support/dsh_native_context.py@@ -0,0 +1,147 @@+"""DSH's fixture-owned public patch and opaque history; common journeys own assertions."""+import json+import os+from pathlib import Path+from native_context_fixture import write_new, protect_configuration++def read_patch(path):+ # The fixture produces the public JSON subset of YAML. This is deliberately+ # not a second parser for arbitrary user YAML or a DSH package-layout reader.+ text = Path(path).read_text()+ if text.strip() in ('', '[]'): return []+ rows, current = [], []+ for line in text.splitlines():+ if line.startswith('- '):+ if current: rows.append(json.loads('\n'.join(current)))+ current = [line[2:]]+ elif line.startswith(' '): current.append(line[2:])+ elif line.strip() and not line.startswith('#'): raise AssertionError('unexpected fixture YAML')+ if current: rows.append(json.loads('\n'.join(current)))+ return rows++def encode_patch(rows):+ return ''.join('- '+json.dumps(row,indent=2).replace('\n','\n ')+'\n' for row in rows) or '[]\n'++def source_credentials(config, token):+ """The active native store differs from a valid, private default decoy."""+ config = Path(config)+ variant = os.environ.get('HIROUTE_PRODUCT_DSH_CREDENTIAL_SOURCE', 'path')+ assert variant in ('path', 'dsh-home'), 'select a known static credential override'+ directory = config/'source-credentials'+ active = directory/('current.yaml' if variant == 'path' else '.credentials.yaml')+ default, home_patch = config/'.credentials.yaml', config/'cordis.patch.yml'+ write_new(default, json.dumps({'version':1,'refs':{'IMPORT_KEY':'inactive-dsh-key'}}))+ write_new(active, json.dumps({'version':1,'refs':{'IMPORT_KEY':token}}))+ settings = {'dshHome':str(directory)}+ if variant == 'path':+ settings.update(path=str(active), dshHome=str(config))+ write_new(home_patch, encode_patch([{'id':'credentials','config':settings}]))+ return active, (default, home_patch)++def prepare_context(product, fixture):+ root = Path(fixture['config'])+ fixture['product_storage'] = str(product.storage)+ write_new(root/'cordis.patch.yml','[]\n')+ write_new(root/'profiles/acp/cordis.patch.yml',encode_patch([+ {'id':'agent-default-model','config':{'provider':'ambient','model':'wrong-native-model'}},+ {'id':'llm-pi-ai','config':{'providers':{'ambient':{'api':'openai-responses',+ 'baseURL':'http://127.0.0.1:9/v1','models':[{'id':'wrong-native-model'}]}}}},+ ]))+ protect_configuration(fixture,[root/'cordis.patch.yml',root/'profiles/acp/cordis.patch.yml'])++def history_directory(fixture):+ return Path(fixture['product_storage'])/'delegation-workers/sessions'++def exact_history(fixture, cancelled_session_id=None):+ found = []+ for marker in history_directory(fixture).glob('*/.hiroute-native-root-v1.json'):+ value = json.loads(marker.read_text())+ if value['task_id'] != fixture['task_id']: continue+ assert value['harness'] == 'deepseek_harness'+ native_id = cancelled_session_id or json.loads((marker.parent/'native-session-binding.json').read_text())['native_session_id']+ paths = list((marker.parent/'native-dsh/sessions').rglob('*.jsonl'))+ assert len(paths) == 1 and paths[0].is_file() and not paths[0].is_symlink()+ # Only synthetic bytes are inspected. Production delegates format interpretation to ACP.+ assert fixture['receipt'] in paths[0].read_text() or fixture.get('boundary'), 'missing task receipt'+ found.append((str(paths[0]),native_id))+ assert len(found) == 1, 'expected one task-owned DSH history'+ return found[0]++def cancelled_history(fixture, run_id):+ from native_task_witness import cancelled_session+ return exact_history(fixture, cancelled_session(fixture,run_id,'deepseek_harness'))++class DshModelSettings:+ """Fixture leaf for DSH's public Web composition; shared journey owns behavior."""+ def __init__(self, config, foreign_endpoint):+ import secrets+ self.harness, self.auth_owned = 'dsh', None+ self.path = Path(config)/'profiles/web/cordis.patch.yml'+ assert not self.path.exists(), 'model fixture requires its own empty DSH context'+ self.original = None+ self.native_default = 'fixture-native/native-default'+ self.baseline = {'providers':{'fixture-native':{'api':'openai-responses',+ 'baseURL':foreign_endpoint,'models':[{'id':'native-default','input':['text'],+ 'contextWindow':100000,'maxTokens':4096}],+ 'fixtureUnknownProviderKey':{'preserve':['native','user']}}},+ 'model':{'name':self.native_default},+ 'hirouteAcceptance':{'unknown':['preserve',secrets.token_hex(8)]}}+ self.write(self.baseline)++ def read(self):+ assert self.path.is_file() and not self.path.is_symlink()+ value = {}+ for row in read_patch(self.path):+ if row['id']=='llm-pi-ai': value['providers']=row['config']['providers']+ elif row['id']=='agent-default-model':+ value['model']={'name':row['config']['provider']+'/'+row['config']['model']}+ elif row['id']=='fixture-preserved': value.update(row['config'])+ return value++ def write(self, value):+ provider,model = value['model']['name'].split('/',1)+ rows = [{'id':'llm-pi-ai','config':{'providers':value['providers']}},+ {'id':'agent-default-model','config':{'provider':provider,'model':model}},+ {'id':'fixture-preserved','config':{k:v for k,v in value.items() if k not in ('providers','model')}}]+ self.path.write_text(encode_patch(rows))+ self.path.chmod(0o600)++ def assert_preserved(self, provider_id, selected_default=None):+ from additional_model_fixture import OwnedModelSettings+ return OwnedModelSettings.assert_preserved(self,provider_id,selected_default)++ def add_user_edit(self, provider_id):+ import secrets+ self.assert_preserved(provider_id)+ rows = read_patch(self.path)+ row = next(r for r in rows if r['id']=='fixture-preserved')+ row['config']['hirouteLaterEdit']={'edited_after_apply':secrets.token_hex(8)}+ # Replace only the unrelated row: managed provider bytes remain untouched.+ old = encode_patch([next(r for r in read_patch(self.path) if r['id']=='fixture-preserved')])+ self.path.write_text(self.path.read_text().replace(old,encode_patch([row]),1))+ self.baseline['hirouteLaterEdit']=row['config']['hirouteLaterEdit']++ def select_default(self, expected, replacement):+ rows = read_patch(self.path)+ row = next(r for r in rows if r['id']=='agent-default-model')+ assert row['config']['provider']+'/'+row['config']['model']==expected+ old = encode_patch([row])+ row['config']['provider'],row['config']['model']=replacement.split('/',1)+ self.path.write_text(self.path.read_text().replace(old,encode_patch([row]),1))++ def close(self):+ from additional_model_fixture import OwnedModelSettings+ return OwnedModelSettings.close(self)+++def main_route_patch(product, endpoint, model):+ """Only the independent main Agent source is seeded; Worker uses production overlay."""+ rows = [{'id':'llm-pi-ai','config':{'providers':{'hiroute-main-acceptance':{+ 'api':'openai-responses','baseURL':endpoint,'apiKeyEnv':'HIROUTE_DSH_MAIN_TOKEN',+ 'models':[{'id':model,'input':['text'],'contextWindow':100000,'maxTokens':2048}]}}}},+ {'id':'agent-default-model','config':{'provider':'hiroute-main-acceptance','model':model}},+ {'id':'session-log-deepseek','config':{'enabled':False}},+ {'id':'session-telemetry-otel','disabled':True}]+ patch = product.root/'dsh-main.patch.yml'+ write_new(patch,encode_patch(rows))+ return patchdiff --git a/crates/daemon/tests/support/native_acp_client.py b/crates/daemon/tests/support/native_acp_client.pynew file mode 100644index 00000000..ce04bedf--- /dev/null+++ b/crates/daemon/tests/support/native_acp_client.py@@ -0,0 +1,60 @@+"""Test-only native ACP consumer. Native defaults/providers are never fabricated by this client."""+import json+import os+import select+import signal+import subprocess+import time+import tempfile++def prompt(product, command, text, selector=None, env=None, timeout=190):+ stderr = tempfile.TemporaryFile()+ process = subprocess.Popen(command,cwd=product.project,env=env or product.env,+ stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=stderr,start_new_session=True,umask=0o077)+ pending = bytearray()+ deadline, updates, counter = time.monotonic()+timeout, [], 0+ def request(method,params):+ nonlocal counter+ counter += 1+ process.stdin.write((json.dumps({'jsonrpc':'2.0','id':counter,'method':method,'params':params})+'\n').encode())+ process.stdin.flush()+ while True:+ remaining = deadline-time.monotonic()+ while b'\n' not in pending:+ assert remaining>0 and select.select([process.stdout],[],[],remaining)[0], 'native ACP request timeout'+ chunk = os.read(process.stdout.fileno(),65536)+ assert chunk, 'native ACP closed before reply'+ pending.extend(chunk)+ assert len(pending)<=4*1024*1024, 'native ACP message limit'+ remaining = deadline-time.monotonic()+ line, _, tail = pending.partition(b'\n')+ pending[:] = tail+ product.outputs.append(line)+ message = json.loads(line)+ if message.get('method') == 'session/update': updates.append(message['params']['update'])+ if message.get('id') == counter:+ assert 'error' not in message, 'native ACP rejected selected operation'+ return message['result']+ try:+ initialized = request('initialize',{'protocolVersion':1,'clientCapabilities':{},'clientInfo':{'name':'hiroute-acceptance','version':'1'}})+ assert initialized['protocolVersion']==1+ session = request('session/new',{'cwd':str(product.project),'mcpServers':[]})+ if selector is not None:+ provider,model = selector.split('/',1)+ selected = json.dumps([provider,model],separators=(',',':'))+ option = next(o for o in session['configOptions'] if o.get('category')=='model' or o.get('id')=='model')+ request('session/set_config_option',{'sessionId':session['sessionId'],'configId':option['id'],'value':selected})+ result = request('session/prompt',{'sessionId':session['sessionId'],'prompt':[{'type':'text','text':text}]})+ assert result['stopReason']=='end_turn', 'native ACP did not complete normally'+ output = ''.join(u.get('content',{}).get('text','') for u in updates if u.get('sessionUpdate')=='agent_message_chunk')+ return output.encode(),session['sessionId']+ finally:+ if process.poll() is None:+ os.killpg(process.pid,signal.SIGTERM)+ try: process.wait(timeout=3)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid,signal.SIGKILL)+ process.wait(timeout=3)+ stderr.seek(0)+ product.outputs.append(stderr.read(2*1024*1024))+ stderr.close()diff --git a/crates/daemon/tests/support/native_context_boundaries.py b/crates/daemon/tests/support/native_context_boundaries.pyindex 12c89bbe..ff484b20 100644--- a/crates/daemon/tests/support/native_context_boundaries.py+++ b/crates/daemon/tests/support/native_context_boundaries.py@@ -5,6 +5,7 @@ edits, deletion API, or private execution port. This entry never builds binaries"""import qoder_native_contextimport pi_native_context+import dsh_native_contextimport argparsefrom concurrent.futures import ThreadPoolExecutorimport copy@@ -85,6 +86,9 @@ def boundary_decision(fixture, body):if fixture['harness'] in ('claude', 'qoder'):assert 'Bash' in names, 'native Bash tool unavailable'name, arguments = 'Bash', {'command': command, 'timeout': 120000}+ elif fixture['harness'] == 'dsh':+ assert 'bash' in names+ name,arguments='bash',{'command':command,'description':'Run the owned heartbeat script','timeoutMs':120000}elif fixture['harness'] == 'pi':assert 'bash' in namesname, arguments = 'bash', {'command': command, 'timeout': 120}@@ -144,7 +148,7 @@ def assert_source_routing(upstream):def transcript_snapshot(fixture):root = (qoder_native_context.history_directory(fixture) if fixture['harness'] == 'qoder'- else pi_native_context.history_directory(fixture) if fixture['harness'] == 'pi' else Path(fixture['config']) / ('sessions' if fixture['harness'] == 'codex' else 'projects'))+ else dsh_native_context.history_directory(fixture) if fixture['harness'] == 'dsh' else pi_native_context.history_directory(fixture) if fixture['harness'] == 'pi' else Path(fixture['config']) / ('sessions' if fixture['harness'] == 'codex' else 'projects'))paths = list(root.rglob('*.jsonl'))assert all(not path.is_symlink() for path in paths), 'unexpected linked fixture history'return {str(path): digest(path) for path in paths if path.is_file()}@@ -241,6 +245,9 @@ def run(repository, candidate, harness):install_oracle(neighbor_source, neighbor)neighbor_plan = publish_neighbor(product, neighbor_source)binary, adapter, node = selected_installation(harness)+ if harness=='dsh':+ from agent_product_support import expose_native_installation+ expose_native_installation(product,harness,binary)configure_worker_installation(product, product.worker_work['harness'], adapter, binary, node)# This standalone journey creates its own native roots. No core journey,# native initialization, or completed Worker may warm them before these requests.@@ -276,7 +283,8 @@ def run(repository, candidate, harness):assert_preserved(fixture)cancelled = dict(target, receipt=target['boundary']['marker'])target_history = (qoder_native_context.cancelled_history(cancelled, runs[0]['run_id'])- if harness == 'qoder' else exact_history(cancelled))+ if harness == 'qoder' else dsh_native_context.cancelled_history(cancelled,runs[0]['run_id'])+ if harness == 'dsh' else exact_history(cancelled))wait_for_resumable_task(product, runs[1]['task_id'], runs[1]['run_id'])neighbor_history = exact_history(neighbor)assert target_history[1] != neighbor_history[1], 'concurrent tasks shared a native session'@@ -321,6 +329,6 @@ if __name__ == '__main__':parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('repository')parser.add_argument('candidate')- parser.add_argument('--harness', choices=('codex', 'claude', 'qoder', 'pi'), required=True)+ parser.add_argument('--harness', choices=('codex', 'claude', 'qoder', 'pi', 'dsh'), required=True)args = parser.parse_args()run(args.repository, args.candidate, args.harness)diff --git a/crates/daemon/tests/support/native_context_fixture.py b/crates/daemon/tests/support/native_context_fixture.pyindex f2f5d792..e8abce46 100644--- a/crates/daemon/tests/support/native_context_fixture.py+++ b/crates/daemon/tests/support/native_context_fixture.py@@ -54,7 +54,7 @@ def prepare_skill(parent, name, scope, writer=write_new):def prepare(home, config, project, harness, suffix='', owned_files=None):"""Add only new fixture-owned skills and neighbors; never replace existing files."""- assert harness in ('codex', 'claude', 'qoder', 'pi')+ assert harness in ('codex', 'claude', 'qoder', 'pi', 'dsh')home, config, project = map(lambda path: Path(path).resolve(), (home, config, project))def owned_write(path, text, executable=False):write_new(path, text, executable)@@ -64,7 +64,7 @@ def prepare(home, config, project, harness, suffix='', owned_files=None):skills = []for scope, parent in (('user', home / '.agents/skills' if harness == 'codex' else config / 'skills'),- ('project', project / {'codex': '.agents/skills', 'claude': '.claude/skills', 'qoder': '.qoder/skills', 'pi': '.pi/skills'}[harness]),+ ('project', project / {'codex': '.agents/skills', 'claude': '.claude/skills', 'qoder': '.qoder/skills', 'pi': '.pi/skills', 'dsh': '.dsh/skills'}[harness]),):skills.append(prepare_skill(parent, 'native-context-' + scope + suffix, scope, owned_write))neighbor = config / ('native-context-neighbor' + suffix + '.txt')@@ -182,6 +182,9 @@ def decision(fixture, body):'expected native Skill directory was not loaded'assert 'Bash' in names, 'native Bash tool unavailable'name = 'Bash'+ elif harness == 'dsh':+ assert 'bash' in names and 'read' in names, 'native DSH tools unavailable'+ return dict(kind='tool',id='native_context_execute',name='bash', arguments={'command':' && '.join('/bin/cat '+shlex.quote(skill['skill'])+' && /bin/sh '+shlex.quote(skill['script']) for skill in fixture['skills']), 'description':'Read native Skills and run receipt scripts','timeoutMs':10000})elif harness == 'pi':assert 'bash' in names and 'read' in names, 'native Pi tools unavailable'name = 'bash'@@ -255,6 +258,10 @@ def handle(handler, body, controls, lock, reply=decision):try:action = reply(fixture, body)except AssertionError as error:+ # Bounded controlled-source evidence stays private for native protocol diagnosis.+ failed = controls / 'last-failed-request.json'+ failed.write_text(json.dumps(body))+ failed.chmod(0o600)with lock, (controls / 'native-context-events.jsonl').open('a') as stream:stream.write(json.dumps({'state': 'red', 'reason': str(error)}) + '\n')handler.send({'error': {'message': str(error), 'type': 'invalid_request_error'}}, 400)diff --git a/crates/daemon/tests/support/native_context_product.py b/crates/daemon/tests/support/native_context_product.pyindex ea631d03..17e6ef59 100644--- a/crates/daemon/tests/support/native_context_product.py+++ b/crates/daemon/tests/support/native_context_product.py@@ -22,6 +22,7 @@ from publication_product import Productfrom publication_process import plan_changeimport qoder_native_contextimport pi_native_context+import dsh_native_contextdef save_context_source(product, upstream, variant='', context_tokens=None, protocol=None):@@ -43,7 +44,7 @@ def native_context_budget(product):def selected_installation(harness):binary = Path(os.environ['HIROUTE_WORKER_' + harness.upper() + '_BINARY']).resolve(strict=True)- if harness == 'qoder':+ if harness in ('qoder','dsh'):return binary, None, Noneif harness == 'pi':return binary, None, Path(os.environ['HIROUTE_WORKER_NODE']).resolve(strict=True)@@ -55,19 +56,21 @@ def selected_installation(harness):def prepare_product(product, harness, context_tokens=None):"""Prepare a normal API source/Plan; Desktop can take over after product.stop()."""product.enable_debug_diagnostics()- roots = {'codex': 'CODEX_HOME', 'claude': 'CLAUDE_CONFIG_DIR', 'qoder': 'QODER_CONFIG_DIR', 'pi': 'PI_CODING_AGENT_DIR'}+ roots = {'codex': 'CODEX_HOME', 'claude': 'CLAUDE_CONFIG_DIR', 'qoder': 'QODER_CONFIG_DIR', 'pi': 'PI_CODING_AGENT_DIR', 'dsh':'DSH_HOME'}if harness == 'qoder':qoder_native_context.select_context(product)fixture = qoder_native_context.prepare_context(product)else:fixture = prepare(Path(product.env['HOME']), Path(product.env[roots[harness]]),product.project, harness)+ if harness == 'dsh':+ dsh_native_context.prepare_context(product,fixture)if harness == 'pi':pi_native_context.prepare_context(product, fixture)native = Path(product.env[roots[harness]])product.worker_work = {'harness': {'codex': 'codex_cli', 'claude': 'claude_code',- 'qoder': 'qoder_cli', 'pi': 'pi'}[harness],- 'protocol': 'messages' if harness == 'claude' else (os.environ.get('HIROUTE_PRODUCT_AGENT_PROTOCOL', 'responses') if harness in ('pi', 'qoder') else 'responses')}+ 'qoder': 'qoder_cli', 'pi': 'pi', 'dsh':'deepseek_harness'}[harness],+ 'protocol': 'messages' if harness == 'claude' else (os.environ.get('HIROUTE_PRODUCT_AGENT_PROTOCOL', 'responses') if harness in ('pi', 'qoder', 'dsh') else 'responses')}assert product.worker_work['protocol'] in ('responses', 'messages')fixture['source_context_tokens'] = (context_tokens if context_tokens is not Noneelse native_context_budget(product))@@ -91,7 +94,7 @@ def prepare_product(product, harness, context_tokens=None):product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change': change}, 'native-worker-plan')product.plan_id = preview['plan_head']['reference']['plan_id']product.model_alias = preview['plan_head']['model_alias']- configuration = native / ('config.toml' if harness == 'codex' else 'settings.json')+ configuration = native / ('config.toml' if harness == 'codex' else 'cordis.patch.yml' if harness == 'dsh' else 'settings.json')if harness == 'codex':configuration.write_text('model = "gpt-5.5"\nmodel_provider = "native_context_ambient"\n''[model_providers.native_context_ambient]\nname = "Unreachable synthetic source"\n'@@ -99,7 +102,7 @@ def prepare_product(product, harness, context_tokens=None):'env_key = "NATIVE_CONTEXT_UNUSED_TOKEN"\nrequires_openai_auth = false\n')elif harness == 'qoder':qoder_native_context.install_project_conflict(fixture, upstream)- elif harness == 'pi':+ elif harness in ('pi','dsh'):pass # Pi's conflict files and package resource receipt are prepared by its leaf.elif harness == 'claude':configuration.write_text(json.dumps({'env': {'ANTHROPIC_BASE_URL': 'http://127.0.0.1:9',@@ -128,7 +131,7 @@ def publish_replacement_route(product, fixture):upstream.token = 'synthetic-replacement-native-context-source-token'try:replacement_work = dict(product.worker_work)- if fixture['harness'] in ('qoder', 'pi'):+ if fixture['harness'] in ('qoder', 'pi', 'dsh'):replacement_work['protocol'] = 'messages' if replacement_work['protocol'] == 'responses' else 'responses'upstream.plan_protocol = replacement_work['protocol']saved = save_context_source(product, upstream, variant='native-context-replacement', protocol=upstream.plan_protocol)@@ -161,6 +164,8 @@ def assert_frozen_route(original_events, before, replacement, protocol=None):def exact_history(fixture):"""Inspect only this synthetic context's native transcript directory, never auth."""+ if fixture['harness'] == 'dsh':+ return dsh_native_context.exact_history(fixture)if fixture['harness'] == 'pi':return pi_native_context.exact_history(fixture)if fixture['harness'] == 'qoder':@@ -234,12 +239,12 @@ def run(repository, candidate):repo = Path(repository).resolve()assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidateharness = os.environ['HIROUTE_PRODUCT_WORKER_HARNESS']- assert harness in ('codex', 'claude', 'qoder', 'pi')+ assert harness in ('codex', 'claude', 'qoder', 'pi', 'dsh')product = Product(repo)# Headless services may explicitly select a non-default native configuration.# Mac Pilot intentionally uses its documented HOME/.codex and HOME/.claude roots.if harness != 'qoder':- product.env['CODEX_HOME' if harness == 'codex' else 'PI_CODING_AGENT_DIR' if harness == 'pi' else 'CLAUDE_CONFIG_DIR'] = str(+ product.env['CODEX_HOME' if harness == 'codex' else 'PI_CODING_AGENT_DIR' if harness == 'pi' else 'DSH_HOME' if harness == 'dsh' else 'CLAUDE_CONFIG_DIR'] = str(Path(product.env['HOME']) / ('selected-' + harness + '-config'))upstream = replacement = Nonestage = 'prepare-native-context'@@ -250,6 +255,9 @@ def run(repository, candidate):for case in BUSINESS_CASES if case not in CORE_CASES])try:binary, adapter, node = selected_installation(harness)+ if harness=='dsh':+ from agent_product_support import expose_native_installation+ expose_native_installation(product,harness,binary)stage = 'real-daemon-and-plan'fixture, upstream = prepare_product(product, harness,context_tokens=16_384 if harness == 'pi' else 32_768 if harness == 'qoder' else None)diff --git a/crates/daemon/tests/support/native_task_witness.py b/crates/daemon/tests/support/native_task_witness.pynew file mode 100644index 00000000..e2c8c70b--- /dev/null+++ b/crates/daemon/tests/support/native_task_witness.py@@ -0,0 +1,29 @@+"""Exact fixture-owned cancelled task identity; never a production recovery reader."""+import json+from pathlib import Path+import sqlite3+++def cancelled_session(fixture, run_id, harness):+ """Cancellation has no successful-Continue binding. Observe its exact stored identity."""+ database = Path(fixture['product_storage']) / 'live/runtime.db'+ assert not database.is_symlink() and database.is_file()+ with sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) as connection:+ task_row = connection.execute(+ 'SELECT record_json FROM delegation_tasks WHERE workspace_id=? AND task_id=?',+ ('personal/default', fixture['task_id'])).fetchone()+ run_row = connection.execute(+ 'SELECT record_json FROM delegation_runs WHERE workspace_id=? AND run_id=?',+ ('personal/default', run_id)).fetchone()+ assert task_row is not None and run_row is not None, 'exact cancelled task/run record is missing'+ task, run = json.loads(task_row[0]), json.loads(run_row[0])+ assert (task['task_id'] == run['task_id'] == fixture['task_id']+ and task['latest_run_id'] == run['run_id'] == run_id+ and task['plan']['harness'] == harness+ and run['progress']['state'] == 'cancelled'+ and run['progress']['cleanup'] == 'complete'), 'exact cancelled task identity or cleanup mismatch'+ session = task['session']+ assert (session and isinstance(session.get('native_session_id'), str)+ and session['native_session_id'] == session['acp_session_id']), \+ 'cancelled native task lacks one exact native session identity'+ return session['native_session_id']diff --git a/crates/daemon/tests/support/pi_discovery_product.py b/crates/daemon/tests/support/pi_discovery_product.pyindex 42cbf3f9..5f63a470 100644--- a/crates/daemon/tests/support/pi_discovery_product.py+++ b/crates/daemon/tests/support/pi_discovery_product.py@@ -1,4 +1,4 @@-"""Import Pi's effective static source through real Scan → Prepare → Save.+"""Import a native Agent's effective static source through real Scan → Prepare → Save.Only native configuration and the deterministic upstream are fixtures. Protectedinput, candidate state, save conflict and restart all use public product entries.@@ -19,6 +19,8 @@ from publication_process import plan_changefrom agent_product_support import apply_settings, expose_native_installationfrom additional_model_fixture import PersistedRouteOracle, read_persisted_route+HARNESS = 'pi'+NATIVE_PREFIX = '\ufeff// Native effective endpoint differs from provider default\n'CASES = ('agent.sources.effective-static-import', 'agent.sources.changed-source-rejected',@@ -27,8 +29,8 @@ CASES = ('agent.sources.effective-static-import', 'agent.sources.changed-source-def use_imported_route(product, binary, source, saved):"""The saved source must reach Plan authoring and an ordinary native call."""- product.editor = {'schema':'hiroute.plan-editor/v2', 'display_name':'Imported Pi route',- 'purpose':'Use the static API imported from Pi', 'mode':'fixed_model',+ product.editor = {'schema':'hiroute.plan-editor/v2', 'display_name':'Imported '+HARNESS+' route',+ 'purpose':'Use the imported static API', 'mode':'fixed_model','candidates':[{'binding_id':saved['binding_id'], 'reasoning':{'kind':'toggle','enabled':False}}],'delegation_enabled':False,'smart':{'economy':[],'primary':[],'primary_fallback':False,'reselect_on_user_message':False,@@ -39,11 +41,11 @@ def use_imported_route(product, binary, source, saved):preview = product.preview('routing preview', {'change':change})product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change':change}, 'pi-imported-route')plan = preview['plan_head']- agent = next(row for row in product.preview('agents scan')['agents'] if row['agent_id']=='agent_pi_default')+ agent = next(row for row in product.preview('agents scan')['agents'] if row['agent_id']=='agent_'+HARNESS+'_default')product.agent_connection = 'agent-connection/' + agent['context_id']- product.additional_harness = 'pi'+ product.additional_harness = HARNESSspec = {'schema_version':{'major':2,'minor':0}, 'context_id':agent['context_id'],- 'model':{'intent':'configure','settings':{'mode':'pi_additional','allowed_plan_ids':[plan['reference']['plan_id']]}},+ 'model':{'intent':'configure','settings':{'mode':HARNESS+'_additional','allowed_plan_ids':[plan['reference']['plan_id']]}},'collaboration':{'intent':'keep'}, 'access_token':{'intent':'keep'}}configured, status = apply_settings(product, spec, 'pi-imported-model-route', 'model')product.bearer(product.agent_connection)@@ -51,7 +53,12 @@ def use_imported_route(product, binary, source, saved):source.reply = oracle.replytry:namespace = configured['model_effect']['provider_id']- providers = json.loads((Path(product.env['PI_CODING_AGENT_DIR']) / 'models.json').read_text().removeprefix(NATIVE_PREFIX))['providers']+ if HARNESS=='dsh':+ from dsh_native_context import read_patch+ providers = next(r['config']['providers'] for r in read_patch(+ Path(product.env['DSH_HOME'])/'profiles/web/cordis.patch.yml') if r['id']=='llm-pi-ai')+ else:+ providers = json.loads((Path(product.env['DSH_HOME' if HARNESS=='dsh' else 'PI_CODING_AGENT_DIR']) / 'models.json').read_text().removeprefix(NATIVE_PREFIX))['providers']ids = [name for name, provider in providers.items() if name.startswith(namespace + '-') and any(m.get('id') == plan['model_alias'] for m in provider.get('models', []))]assert len(ids) == 1selector = ids[0] + '/' + plan['model_alias']@@ -71,40 +78,54 @@ def prepare(product, discovery, identity):def scan(product):items = control(product, 'ScanCompute', {})['data']['items']- sources = [item for item in items if item['agent_id'] == 'agent_pi_default'+ sources = [item for item in items if item['agent_id'] == 'agent_'+HARNESS+'_default'and item.get('native_provider_id') == 'native-source']assert len(sources) == 1 and sources[0]['inventory_eligible'], 'static native source not importable'return sources[0]['discovery']def run(repository, candidate):+ global HARNESS+ HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','pi')+ assert HARNESS in ('pi','dsh')repo = Path(repository).resolve()assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidateproduct = Product(repo)source = Nonestage = 'native-static-source'- report = dict(scenario='pi-static-source-import', candidate=candidate, worker_harness='pi',+ report = dict(scenario=HARNESS+'-static-source-import', candidate=candidate, worker_harness=HARNESS,required_cases=list(CASES), selected_cases=list(CASES), cases=[],evidence_limit='Real static import/save/restart followed by ordinary native routing; deterministic source; no OAuth')try:product.enable_debug_diagnostics()- binary, _, node = selected_installation('pi')- expose_native_installation(product, 'pi', binary, node)- config = Path(product.env['HOME']) / 'selected-pi-config'+ binary, _, node = selected_installation(HARNESS)+ expose_native_installation(product, HARNESS, binary, node)+ config = Path(product.env['HOME']) / ('selected-'+HARNESS+'-config')config.mkdir(mode=0o700)- product.env['PI_CODING_AGENT_DIR'] = str(config)+ product.env['DSH_HOME' if HARNESS=='dsh' else 'PI_CODING_AGENT_DIR'] = str(config)controls = product.root / 'source'controls.mkdir(mode=0o700)write_new(controls / 'native-context.json', '{}')source = NativeContextUpstream(controls)- provider = {'api':'openai-responses','baseUrl':'http://127.0.0.1:9/v1','apiKey':'provider-fallback',- 'models':[{'id':source.model,'baseUrl':source.base_url,'contextWindow':16384,'maxTokens':4096,'input':['text']}]}- write_new(config / 'models.json', NATIVE_PREFIX +- json.dumps({'providers':{'native-source':provider}}))- write_new(config / 'auth.json', json.dumps({'native-source':{'type':'api_key',- 'key':'${IMPORT_KEY}','env':{'IMPORT_KEY':source.token}}}))- before = {name:digest(config / name) for name in ('models.json','auth.json')}- original_auth = (config / 'auth.json').read_bytes()+ credential_context_paths = ()+ if HARNESS=='dsh':+ from dsh_native_context import encode_patch, source_credentials+ models_path = config/'profiles/web/cordis.patch.yml'+ provider = {'api':'openai-responses','baseURL':source.base_url,'apiKeyEnv':'IMPORT_KEY',+ 'models':[{'id':source.model,'contextWindow':16384,'maxTokens':4096,'input':['text']}]}+ write_new(models_path,encode_patch([{'id':'llm-pi-ai','config':{'providers':{'native-source':provider}}}]))+ auth_path, credential_context_paths = source_credentials(config, source.token)+ product.env.pop('IMPORT_KEY', None)+ changed_auth = json.dumps({'version':1,'refs':{'IMPORT_KEY':'changed-native-key'}})+ else:+ models_path,auth_path = config/'models.json',config/'auth.json'+ provider = {'api':'openai-responses','baseUrl':'http://127.0.0.1:9/v1','apiKey':'provider-fallback',+ 'models':[{'id':source.model,'baseUrl':source.base_url,'contextWindow':16384,'maxTokens':4096,'input':['text']}]}+ write_new(models_path,NATIVE_PREFIX+json.dumps({'providers':{'native-source':provider}}))+ write_new(auth_path,json.dumps({'native-source':{'type':'api_key','key':'${IMPORT_KEY}','env':{'IMPORT_KEY':source.token}}}))+ changed_auth = json.dumps({'native-source':{'type':'api_key','key':'changed-native-key'}})+ before = {path:digest(path) for path in (models_path,auth_path,*credential_context_paths)}+ original_auth = auth_path.read_bytes()product.secrets.update((source.token, 'provider-fallback'))product.start()stage = 'public-scan-prepare-save'@@ -114,7 +135,7 @@ def run(repository, candidate):models = candidate_view['models']assert len(models) == 1 and models[0]['upstream_model_id'] == source.model and models[0]['selectable']saved = save_compute_candidate(product, candidate_view, models[0]['model_ref'], 'pi-source-save')- assert {name:digest(config / name) for name in before} == before, 'import rewrote native user files'+ assert {path:digest(path) for path in before} == before, 'import rewrote native user files'product.stop()product.start()snapshot = control(product, 'ListCompute', {})['data']@@ -127,17 +148,17 @@ def run(repository, candidate):'subject':{'kind':'candidate','candidate':prepared['candidate']},'expected_revisions':revision,'selected_model_refs':[prepared['models'][0]['model_ref']], 'intent':'save_ready','key_edits':[]}preview = control(product, 'PreviewComputeSave', {'change':change})['data']- (config / 'auth.json').write_text(json.dumps({'native-source':{'type':'api_key','key':'changed-native-key'}}))+ auth_path.write_text(changed_auth)control(product, 'ApplyComputeSave', {'spec':preview['spec'],'accept_digest':preview['accept_digest'],'expected_revisions':preview['expected_revisions'],'idempotency_key':'pi-source-stale-save'},expected_error='CHANGE_PREVIEW_STALE')assert source.request_count() == 0, 'passive discovery/save issued an inference request'report['cases'].append({'id':CASES[1],'state':'green'})- (config / 'auth.json').write_bytes(original_auth)+ auth_path.write_bytes(original_auth)stage = 'use-imported-source'report['native_route'] = use_imported_route(product, binary, source, saved)assert source.request_count() == 1, 'imported route did not make exactly one native model request'- assert {name:digest(config / name) for name in before} == before, 'model route restore changed borrowed files'+ assert {path:digest(path) for path in before} == before, 'model route restore changed borrowed files'report['cases'].append({'id':CASES[2],'state':'green'})product.stop()report.update(state='green', diagnostics=product.diagnostics_snapshot(), passive_model_posts=0, model_posts=1,diff --git a/crates/daemon/tests/support/publication_product.py b/crates/daemon/tests/support/publication_product.pyindex 409500c6..b70a73f8 100644--- a/crates/daemon/tests/support/publication_product.py+++ b/crates/daemon/tests/support/publication_product.py@@ -3,13 +3,17 @@Fixtures are user-owned Agent files only; no test writes business database rows."""import hashlib+import errno+import fcntlimport http.clientimport jsonimport osfrom pathlib import Pathimport select+import secretsimport shutilimport socket+import statimport subprocessimport sysimport tempfile@@ -49,6 +53,44 @@ def startup_frame(process, timeout):previous = index+def fixture_listener_port():+ """Lease an explicit address outside the host's outbound ephemeral-port range.++ Closing a bind(0) probe lets concurrent clients claim that ephemeral port before+ the daemon binds it. A per-address file lease also separates parallel fixtures+ and survives this Product's daemon restarts; the real daemon still owns its socket.+ """+ if sys.platform == 'darwin':+ bounds = subprocess.check_output([+ 'sysctl', '-n', 'net.inet.ip.portrange.first', 'net.inet.ip.portrange.last',+ ], text=True, timeout=2).split()+ else:+ bounds = Path('/proc/sys/net/ipv4/ip_local_port_range').read_text().split()+ first, last = map(int, bounds)+ candidates = [port for port in range(10000, 30000) if not first <= port <= last]+ # Runner TMPDIRs differ even on one host. A UID-owned stable namespace must+ # coordinate their addresses; a per-run lease directory cannot do that.+ directory = Path('/tmp') / f'hiroute-product-listener-ports-{os.getuid()}'+ directory.mkdir(mode=0o700, exist_ok=True)+ metadata = directory.lstat()+ if (not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != os.getuid()+ or stat.S_IMODE(metadata.st_mode) != 0o700):+ raise RuntimeError('fixture listener lease directory is not private and owned')+ for port in secrets.SystemRandom().sample(candidates, min(128, len(candidates))):+ fd = os.open(directory / f'{port}.lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)+ lease = os.fdopen(fd, 'r+b')+ try:+ fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)+ with socket.socket() as probe:+ probe.bind(('127.0.0.1', port))+ return lease, port+ except OSError as error:+ lease.close()+ if error.errno not in (errno.EADDRINUSE, errno.EAGAIN, errno.EACCES):+ raise+ raise RuntimeError('no unoccupied fixture listener address available')++class Product:def __init__(self, repository, project_source=False, root=None):self.repo = Path(repository)@@ -147,13 +189,12 @@ finally:CLAUDE_CONFIG_DIR=str(home / '.claude'),QODER_CONFIG_DIR=str(home / '.qoder'),PI_CODING_AGENT_DIR=str(home / '.pi/agent'),+ DSH_HOME=str(home / '.dsh'),PATH=str(bin_dir) + ':/usr/bin:/bin',HIROUTE_RUNTIME_DIR=str(self.root / 'runtime'),HIROUTE_WORKER_RECEIPT_DIR=str(self.root / 'worker-receipts'),HIROUTE_REPLAY_ROOT=str(self.root / 'replay'))- with socket.socket() as sock:- sock.bind(('127.0.0.1', 0))- self.port = sock.getsockname()[1]+ self.listener_port_lease, self.port = fixture_listener_port()self.process = Noneself.outputs = []self.secrets = {SENTINEL, 'fixture.id.token', 'fixture-refresh-sentinel'}@@ -601,6 +642,7 @@ finally:assert all(secret.encode() not in output for secret in self.secretsfor output in self.outputs), 'public secret leak'finally:+ self.listener_port_lease.close()if failed and self.temporary is not None:# Keep failed frames, stderr and data private; do not replace the original# assertion with a shutdown error or erase the evidence in finally.diff --git a/crates/daemon/tests/support/qoder_native_context.py b/crates/daemon/tests/support/qoder_native_context.pyindex ebef9882..80b5ce73 100644--- a/crates/daemon/tests/support/qoder_native_context.py+++ b/crates/daemon/tests/support/qoder_native_context.py@@ -9,7 +9,6 @@ import osfrom pathlib import Pathimport reimport secrets-import sqlite3import statfrom native_context_fixture import NativeProxyTrap, digest, prepare, protect_configuration, write_new@@ -165,27 +164,8 @@ def cancelled_history(fixture, run_id):status exposes observation session links, not the opaque native session ID."""task_session_root(fixture) # Verify the task-owned descriptor and borrowed context.- database = Path(fixture['product_storage']) / 'live/runtime.db'- assert not database.is_symlink() and database.is_file()- with sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) as connection:- task_row = connection.execute(- 'SELECT record_json FROM delegation_tasks WHERE workspace_id=? AND task_id=?',- ('personal/default', fixture['task_id'])).fetchone()- run_row = connection.execute(- 'SELECT record_json FROM delegation_runs WHERE workspace_id=? AND run_id=?',- ('personal/default', run_id)).fetchone()- assert task_row is not None and run_row is not None, 'exact cancelled task/run record is missing'- task, run = json.loads(task_row[0]), json.loads(run_row[0])- assert (task['task_id'] == run['task_id'] == fixture['task_id']- and task['latest_run_id'] == run['run_id'] == run_id- and task['plan']['harness'] == 'qoder_cli'- and run['progress']['state'] == 'cancelled'- and run['progress']['cleanup'] == 'complete'), 'exact cancelled task identity or cleanup mismatch'- session = task['session']- assert (session and isinstance(session.get('native_session_id'), str)- and session['native_session_id'] == session['acp_session_id']), \- 'cancelled Qoder task lacks one exact native session identity'- return history_for_session(fixture, session['native_session_id'])+ from native_task_witness import cancelled_session+ return history_for_session(fixture, cancelled_session(fixture, run_id, 'qoder_cli'))def assert_restricted_modes_unavailable(product, upstream):diff --git a/crates/domain/src/agents/model_grant.rs b/crates/domain/src/agents/model_grant.rsindex 1617bfb8..bbe5986a 100644--- a/crates/domain/src/agents/model_grant.rs+++ b/crates/domain/src/agents/model_grant.rs@@ -81,7 +81,8 @@ impl AgentModelGrantV2 {(AgentModelSelectionV2::CodexDefault { .. }| AgentModelSelectionV2::QoderAdditional { .. }- | AgentModelSelectionV2::PiAdditional { .. },+ | AgentModelSelectionV2::PiAdditional { .. }+ | AgentModelSelectionV2::DshAdditional { .. },AgentIngressProtocolV1::Responses) | (AgentModelSelectionV2::ClaudeLauncher { .. },@@ -297,7 +298,8 @@ impl AgentModelGrantV2 {(AgentModelSelectionV2::CodexDefault { .. }| AgentModelSelectionV2::QoderAdditional { .. }- | AgentModelSelectionV2::PiAdditional { .. },+ | AgentModelSelectionV2::PiAdditional { .. }+ | AgentModelSelectionV2::DshAdditional { .. },AgentIngressProtocolV1::Responses) | (AgentModelSelectionV2::ClaudeLauncher { .. },diff --git a/crates/domain/src/agents/profile.rs b/crates/domain/src/agents/profile.rsindex 54751a4b..811e6efd 100644--- a/crates/domain/src/agents/profile.rs+++ b/crates/domain/src/agents/profile.rs@@ -15,6 +15,7 @@ pub enum AgentKindV1 {ClaudeCode,Qoder,Pi,+ DeepseekHarness,}impl AgentKindV1 {@@ -36,7 +37,7 @@ impl AgentKindV1 {ConfigLayerV1::Project,ConfigLayerV1::User,],- Self::Pi => &[+ Self::Pi | Self::DeepseekHarness => &[ConfigLayerV1::Process,ConfigLayerV1::Launch,ConfigLayerV1::Project,@@ -57,6 +58,7 @@ impl AgentKindV1 {Self::ClaudeCode => "claude_code",Self::Qoder => "qoder",Self::Pi => "pi",+ Self::DeepseekHarness => "deepseek_harness",}}}@@ -213,12 +215,14 @@ impl AgentProfileV1 {if self.config_precedence.as_slice() != self.kind.config_precedence() {return Err(AgentProfileError::InvalidConfigPrecedence);}- if matches!(self.kind, AgentKindV1::Qoder | AgentKindV1::Pi)- && (self.dynamic_catalog- || self.static_catalog_fallback- || self.native_subagent_routing- || self.spawn_guidance.is_some()- || self.managed_launch.is_some())+ if matches!(+ self.kind,+ AgentKindV1::Qoder | AgentKindV1::Pi | AgentKindV1::DeepseekHarness+ ) && (self.dynamic_catalog+ || self.static_catalog_fallback+ || self.native_subagent_routing+ || self.spawn_guidance.is_some()+ || self.managed_launch.is_some()){return Err(AgentProfileError::InvalidCatalogCapability);}@@ -255,7 +259,10 @@ impl AgentProfileV1 {}match (self.kind, self.ingress_protocol) {(- AgentKindV1::Codex | AgentKindV1::Qoder | AgentKindV1::Pi,+ AgentKindV1::Codex+ | AgentKindV1::Qoder+ | AgentKindV1::Pi+ | AgentKindV1::DeepseekHarness,Some(AgentIngressProtocolV1::Responses),)| (AgentKindV1::ClaudeCode, Some(AgentIngressProtocolV1::Messages)) => Ok(()),diff --git a/crates/domain/src/agents/settings.rs b/crates/domain/src/agents/settings.rsindex 216ff96a..23f71b21 100644--- a/crates/domain/src/agents/settings.rs+++ b/crates/domain/src/agents/settings.rs@@ -20,6 +20,11 @@ pub enum AgentFacetIntent<T> {#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]pub enum AgentModelSelectionV2 {+ DshAdditional {+ allowed_plan_ids: BTreeSet<AgentPlanId>,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ plan_protocols: BTreeMap<AgentPlanId, crate::AgentIngressProtocolV1>,+ },CodexDefault {native_model_mode: CodexNativeModelModeV2,fixed_models: Vec<AgentFixedModelSelectionV2>,@@ -58,6 +63,7 @@ pub enum AgentModelSurfaceV2 {ClaudeCli,QoderCli,PiCli,+ DshCli,}#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]@@ -109,6 +115,9 @@ impl AgentModelSelectionV2 {| Self::PiAdditional { plan_protocols, .. } => {plan_protocols.get(id).copied().unwrap_or(fallback)}+ Self::DshAdditional { plan_protocols, .. } => {+ plan_protocols.get(id).copied().unwrap_or(fallback)+ }_ => fallback,}}@@ -118,7 +127,9 @@ impl AgentModelSelectionV2 {Self::CodexDefault { fixed_models, .. } | Self::ClaudeLauncher { fixed_models, .. } => {fixed_models}- Self::QoderAdditional { .. } | Self::PiAdditional { .. } => &[],+ Self::QoderAdditional { .. }+ | Self::PiAdditional { .. }+ | Self::DshAdditional { .. } => &[],}}@@ -132,6 +143,9 @@ impl AgentModelSelectionV2 {}| Self::PiAdditional {allowed_plan_ids, ..+ }+ | Self::DshAdditional {+ allowed_plan_ids, ..} => allowed_plan_ids.clone(),Self::ClaudeLauncher {preset_mappings, ..@@ -182,7 +196,8 @@ impl AgentModelSelectionV2 {_ => return Err(invalid),},Self::QoderAdditional { plan_protocols, .. }- | Self::PiAdditional { plan_protocols, .. } => {+ | Self::PiAdditional { plan_protocols, .. }+ | Self::DshAdditional { plan_protocols, .. } => {if plan_protocols.keys().any(|id| !plans.contains(id)) {return Err(crate::AgentConnectionError::InvalidGrant);}diff --git a/crates/domain/src/delegation/installation.rs b/crates/domain/src/delegation/installation.rsindex 71f44d55..b648f7d2 100644--- a/crates/domain/src/delegation/installation.rs+++ b/crates/domain/src/delegation/installation.rs@@ -39,10 +39,12 @@ impl<'a> WorkerLaunchFormV1<'a> {cli,node,}),- WorkerHarnessV1::QoderCli if adapter.is_none() && node.is_none() => {+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::DeepseekHarness+ if adapter.is_none() && node.is_none() =>+ {Ok(Self::NativeAcp { cli })}- WorkerHarnessV1::QoderCli => Err(invalid()),+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::DeepseekHarness => Err(invalid()),WorkerHarnessV1::Pi if adapter.is_none() => Ok(Self::NativeSdk {cli,node: node.ok_or_else(invalid)?,diff --git a/crates/domain/src/delegation/mod.rs b/crates/domain/src/delegation/mod.rsindex 3fb2a558..40f5fa93 100644--- a/crates/domain/src/delegation/mod.rs+++ b/crates/domain/src/delegation/mod.rs@@ -49,6 +49,7 @@ pub enum WorkerHarnessV1 {ClaudeCode,QoderCli,Pi,+ DeepseekHarness,}#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]diff --git a/crates/domain/src/operation/mod.rs b/crates/domain/src/operation/mod.rsindex 1ff1654c..b6d767ae 100644--- a/crates/domain/src/operation/mod.rs+++ b/crates/domain/src/operation/mod.rs@@ -842,6 +842,9 @@ impl TransactionPlanV1 {let resource = match harness {crate::delegation::WorkerHarnessV1::QoderCli => "worker-dependency-selection/qoder_cli",crate::delegation::WorkerHarnessV1::Pi => "worker-dependency-selection/pi",+ crate::delegation::WorkerHarnessV1::DeepseekHarness => {+ "worker-dependency-selection/deepseek_harness"+ }crate::delegation::WorkerHarnessV1::CodexCli => "worker-dependency-selection/codex_cli",crate::delegation::WorkerHarnessV1::ClaudeCode => {"worker-dependency-selection/claude_code"diff --git a/crates/gateway/src/core_runtime.rs b/crates/gateway/src/core_runtime.rsindex b1ff849d..6a7ee3ad 100644--- a/crates/gateway/src/core_runtime.rs+++ b/crates/gateway/src/core_runtime.rs@@ -1429,6 +1429,24 @@ fn inbound_authorization<'a>(}return Some(std::borrow::Cow::Owned(format!("Bearer {token}")));}+ // Native Anthropic clients may send a run credential through x-api-key.+ // Only the issued run-model namespace uses this carrier; ordinary native keys,+ // model grants and control credentials still cannot authenticate this way.+ if path == "/v1/messages" && !headers.contains_key(AUTHORIZATION) {+ if headers.get_all("x-api-key").iter().count() != 1 {+ return None;+ }+ let token = headers.get("x-api-key")?.to_str().ok()?;+ if !token.starts_with("hr_run_model_")+ || token+ .bytes()+ .any(|byte| byte.is_ascii_whitespace() || byte == b',')+ {+ return None;+ }+ // The run authority must still verify the signed token, live run and frozen protocol.+ return Some(std::borrow::Cow::Owned(format!("Bearer {token}")));+ }if headers.get_all(AUTHORIZATION).iter().count() != 1 {return None;}diff --git a/crates/gateway/src/core_runtime/inbound_auth_tests.rs b/crates/gateway/src/core_runtime/inbound_auth_tests.rsindex d893df98..3ffcf382 100644--- a/crates/gateway/src/core_runtime/inbound_auth_tests.rs+++ b/crates/gateway/src/core_runtime/inbound_auth_tests.rs@@ -59,7 +59,7 @@ fn qoder_model_entry_is_explicit_and_never_adopts_worker_or_mixed_credentials()}#[test]-fn x_api_key_never_authenticates_and_bearer_wins_when_both_are_present() {+fn ordinary_x_api_key_never_authenticates_and_bearer_wins_when_both_are_present() {let mut headers = HeaderMap::new();headers.insert("x-api-key", HeaderValue::from_static("not-an-agent-grant"));assert_eq!(inbound_authorization("/v1/messages", &headers), None);@@ -74,6 +74,52 @@ fn x_api_key_never_authenticates_and_bearer_wins_when_both_are_present() {);}+#[test]+fn native_messages_api_key_carrier_is_limited_to_run_model_authority() {+ let mut headers = HeaderMap::new();+ for token in [+ "native-key",+ "local-model-grant",+ "hr_run_control_fixture",+ "hr_run_model_first,second",+ "hr_run_model_first second",+ ] {+ headers.insert("x-api-key", HeaderValue::from_str(token).unwrap());+ assert!(+ inbound_authorization("/v1/messages", &headers).is_none(),+ "{token}"+ );+ }+ headers.insert(+ "x-api-key",+ HeaderValue::from_static("hr_run_model_fixture"),+ );+ assert_eq!(+ inbound_authorization("/v1/messages", &headers).as_deref(),+ Some("Bearer hr_run_model_fixture")+ );+ for path in [+ "/v1/models",+ "/v1/responses",+ "/v1/messages/extra",+ "/qoder/messages",+ ] {+ assert!(inbound_authorization(path, &headers).is_none(), "{path}");+ }+ headers.append("x-api-key", HeaderValue::from_static("hr_run_model_second"));+ assert!(inbound_authorization("/v1/messages", &headers).is_none());+ headers.remove("x-api-key");+ headers.insert(+ "x-api-key",+ HeaderValue::from_static("hr_run_model_fixture"),+ );+ headers.insert(+ "x-hiroute-token",+ HeaderValue::from_static("hr_run_model_fixture"),+ );+ assert!(inbound_authorization("/v1/messages", &headers).is_none());+}+#[test]fn model_entry_uses_independent_grant_without_native_bearer_fallback() {let mut headers = HeaderMap::new();diff --git a/crates/gateway/src/dispatch/run.rs b/crates/gateway/src/dispatch/run.rsindex 427efb5a..b6876771 100644--- a/crates/gateway/src/dispatch/run.rs+++ b/crates/gateway/src/dispatch/run.rs@@ -64,7 +64,7 @@ impl RunObservationMetadata {|| !valid_observation_reference(&value.publication_ref)|| !matches!(value.harness_id.as_str(),- "codex" | "claude" | "qoder" | "pi"+ "codex" | "claude" | "qoder" | "pi" | "dsh")|| [&value.native_session_id,diff --git a/crates/integrations/Cargo.toml b/crates/integrations/Cargo.tomlindex bf3af8f8..1b865129 100644--- a/crates/integrations/Cargo.toml+++ b/crates/integrations/Cargo.toml@@ -15,6 +15,7 @@ http.workspace = truereqwest = { version = "=0.13.4", features = ["blocking"] }serde.workspace = trueserde_json.workspace = true+serde_yaml.workspace = truethiserror.workspace = truetoml_edit = "=0.25.13"zeroize.workspace = truediff --git a/crates/integrations/src/agents/additional_native.rs b/crates/integrations/src/agents/additional_native.rsindex 5027305b..82a2aa96 100644--- a/crates/integrations/src/agents/additional_native.rs+++ b/crates/integrations/src/agents/additional_native.rs@@ -54,7 +54,7 @@ pub(super) fn validate_declaration() -> Result<(), QoderNativeError> {if kind == AgentKindV1::Qoder {qoder_provider::validate_model_route(provider_id, endpoint)?;- } else if kind != AgentKindV1::Pi+ } else if !matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness)|| !endpoint.starts_with("http://")|| !endpoint.ends_with("/v1"){@@ -76,7 +76,7 @@ pub(super) fn validate_declaration(return Err(qoder_error("additional models"));}for model in models {- (if kind == AgentKindV1::Pi {+ (if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {model.validate_pi()} else {model.validate()@@ -93,11 +93,15 @@ fn document(current: Option<&[u8]>) -> Result<Document<'_>, QoderNativeError> {Document::parse(current.unwrap_or(b"{}"))}-fn owned<'a>(- document: &'a Document<'_>,- provider: &str,-) -> Result<Option<&'a Value>, QoderNativeError> {- let Some(providers) = document.root.value.get("providers") else {+fn native_root(kind: AgentKindV1, current: Option<&[u8]>) -> Result<Value, QoderNativeError> {+ if kind == AgentKindV1::DeepseekHarness {+ super::dsh_config::Patch::parse(current)?.model_root()+ } else {+ Ok(document(current)?.root.value)+ }+}+fn owned<'a>(root: &'a Value, provider: &str) -> Result<Option<&'a Value>, QoderNativeError> {+ let Some(providers) = root.get("providers") else {return Ok(None);};Ok(providers@@ -105,6 +109,26 @@ fn owned<'a>(.ok_or_else(|| qoder_error("native providers object"))?.get(provider))}+fn edit_provider(+ kind: AgentKindV1,+ bytes: &[u8],+ id: &str,+ provider: Option<&Value>,+) -> Result<Zeroizing<Vec<u8>>, QoderNativeError> {+ if kind == AgentKindV1::DeepseekHarness {+ return super::dsh_config::Patch::parse(Some(bytes))?.edit_provider(id, provider);+ }+ let document = document(Some(bytes))?;+ if let Some(providers) = document.object(&document.root, "providers")? {+ document.edit(&providers, id, provider)+ } else {+ document.edit(+ &document.root,+ "providers",+ Some(&serde_json::json!({(id):provider})),+ )+ }+}pub(super) fn validate_configuration(kind: AgentKindV1,@@ -115,7 +139,7 @@ pub(super) fn validate_configuration(previous: Option<&Restore>,) -> Result<(), QoderNativeError> {validate_declaration(kind, provider_id, endpoint, models)?;- let document = document(current)?;+ let document = native_root(kind, current)?;let desired: BTreeSet<_> = models.iter().map(|m| hiroute_domain::additional_model_provider_for(provider_id, models, m))@@ -152,11 +176,11 @@ pub(super) fn validate_configuration(}fn default_not_removed(- document: &Document<'_>,+ document: &Value,provider: &str,retain: &BTreeSet<String>,) -> Result<(), QoderNativeError> {- let Some(model) = document.root.value.get("model") else {+ let Some(model) = document.get("model") else {return Ok(());};let model = model@@ -203,26 +227,25 @@ pub(super) fn configure(.push(model.clone());}let mut bytes = base.as_deref().map_or_else(- || Zeroizing::new(b"{}".to_vec()),+ || {+ Zeroizing::new(if kind == AgentKindV1::DeepseekHarness {+ b"[]\n".to_vec()+ } else {+ b"{}".to_vec()+ })+ },|b| Zeroizing::new(b.to_vec()),);let mut digests = std::collections::BTreeMap::new();for (id, models) in groups {let provider = render_provider(kind, endpoint, credential, &models)?;digests.insert(id.clone(), digest(&provider)?);- let document = document(Some(&bytes))?;- bytes = if let Some(providers) = document.object(&document.root, "providers")? {- document.edit(&providers, &id, Some(&provider))?- } else {- document.edit(- &document.root,- "providers",- Some(&serde_json::json!({(id):provider})),- )?- };+ bytes = edit_provider(kind, &bytes, &id, Some(&provider))?;}let restore = Restore {- schema: if kind == AgentKindV1::Pi {+ schema: if kind == AgentKindV1::DeepseekHarness {+ "hiroute.dsh-native-restore/v2"+ } else if kind == AgentKindV1::Pi {"hiroute.pi-native-restore/v2"} else {"hiroute.qoder-native-restore/v2"@@ -274,8 +297,15 @@ fn render_provider(// Pi's saved auth can replace its Bearer. The scoped custom header remains authoritative.let (api, base_url) = super::pi_native_provider_api(protocol, endpoint).map_err(|_| qoder_error("Pi native endpoint"))?;- serde_json::json!({"api":api,"baseUrl":base_url,"apiKey":credential,+ if kind == AgentKindV1::DeepseekHarness {+ // A unique custom route has no ambient catalog auth. Both public wire implementations+ // accept explicit Authorization; X-HiRoute-Token binds the independent local grant.+ serde_json::json!({"api":api,"baseURL":base_url,+ "headers":{"Authorization":format!("Bearer {credential}"),"X-HiRoute-Token":credential},"models":models})+ } else {+ serde_json::json!({"api":api,"baseUrl":base_url,"apiKey":credential,"headers":{"X-HiRoute-Token":credential},"models":models})+ }})}@@ -286,6 +316,7 @@ impl Restore {Ok(AgentKindV1::Qoder)}"hiroute.pi-native-restore/v1" | "hiroute.pi-native-restore/v2" => Ok(AgentKindV1::Pi),+ "hiroute.dsh-native-restore/v2" => Ok(AgentKindV1::DeepseekHarness),_ => Err(qoder_error("restore schema")),}}@@ -340,7 +371,10 @@ impl Restore {}CanonicalDigest::parse(record.rendered_digest.as_str()).map_err(|_| qoder_error("restore digest"))?;- let original = document(record.original_exists.then_some(record.original.as_slice()))?;+ let original = native_root(+ record.kind()?,+ record.original_exists.then_some(record.original.as_slice()),+ )?;for (id, digest) in record.owned_providers() {if !legacy&& id@@ -371,7 +405,7 @@ impl Restore {}pub fn applied(&self, current: Option<&[u8]>) -> Result<bool, QoderNativeError> {- let document = document(current)?;+ let document = native_root(self.kind()?, current)?;for (id, expected) in self.owned_providers() {if owned(&document, &id)?.map(digest).transpose()?.as_ref() != Some(&expected) {return Ok(false);@@ -396,7 +430,7 @@ impl Restore {current: Option<&[u8]>,check_default: bool,) -> Result<Option<Zeroizing<Vec<u8>>>, QoderNativeError> {- let document = document(current)?;+ let document = native_root(self.kind()?, current)?;if check_default {for id in self.owned_providers().keys() {default_not_removed(&document, id, &BTreeSet::new())?;@@ -420,11 +454,7 @@ impl Restore {.to_vec(),);for id in self.owned_providers().keys() {- let document = Document::parse(&bytes)?;- let providers = document- .object(&document.root, "providers")?- .ok_or_else(|| qoder_error("owned provider missing"))?;- bytes = document.edit(&providers, id, None)?;+ bytes = edit_provider(self.kind()?, &bytes, id, None)?;}Ok(Some(bytes))}diff --git a/crates/integrations/src/agents/additional_native/README.md b/crates/integrations/src/agents/additional_native/README.mdindex d24bbddc..34815faa 100644--- a/crates/integrations/src/agents/additional_native/README.md+++ b/crates/integrations/src/agents/additional_native/README.md@@ -1,17 +1,18 @@# Additional native model routes-The shared adapter owns one `providers.hiroute-main-<context digest>` entry. The+The shared adapter owns one provider per selected Plan, identified by the context+namespace and model alias. Theapplication owns authorization, grants, publication and restore ordering; nativeleaves own effective configuration, model budgets and result interpretation.See the [Agent map](../../../../../docs/code-map/README.md) before changing owners.-| Native boundary | Qoder | Pi |-| --- | --- | --- |-| Selected user target | `QODER_CONFIG_DIR/settings.json` | `PI_CODING_AGENT_DIR/models.json` (effective HOME fallback) |-| Model declaration / budget | [Qoder provider](../qoder_provider.rs), [Plan budget](../qoder_budget.rs) | [Shared provider renderer](../additional_native.rs), [Pi Plan budget](../qoder_budget.rs) |-| Separate default dependency | `model.name` in the target file | `defaultProvider/defaultModel` in user `settings.json` |-| Ordinary Gateway authentication | Dedicated `/_hiroute/qoder/v1` bearer channel | `/v1`, fixed `X-HiRoute-Token` header; saved native auth may override ordinary Bearer |-| Actual native acceptance | [Qoder journeys](../../../../../tools/product-e2e/tests/QODER_DELEGATION.md) | [Pi journeys](../../../../../tools/product-e2e/tests/PI_INTEGRATION.md) |+| Native boundary | Qoder | Pi | DSH |+| --- | --- | --- | --- |+| Selected user target | `QODER_CONFIG_DIR/settings.json` | `PI_CODING_AGENT_DIR/models.json` (effective HOME fallback) | `DSH_HOME/profiles/web/cordis.patch.yml` |+| Model declaration / budget | [Qoder provider](../qoder_provider.rs), [Plan budget](../qoder_budget.rs) | [Shared provider renderer](../additional_native.rs), [Pi Plan budget](../qoder_budget.rs) | [Public YAML leaf](../dsh_config.rs), [shared budget](../qoder_budget.rs) |+| Separate default dependency | `model.name` in the target file | `defaultProvider/defaultModel` in user `settings.json` | `agent-default-model` in Web and home patches; home provider shadowing is refused |+| Ordinary Gateway authentication | Dedicated `/_hiroute/qoder/v1` bearer channel | `/v1`, fixed `X-HiRoute-Token` header; saved native auth may override ordinary Bearer | Fixed `X-HiRoute-Token` header; Responses base ends in `/v1`, Messages base does not |+| Actual native acceptance | [Qoder journeys](../../../../../tools/product-e2e/tests/QODER_DELEGATION.md) | [Pi journeys](../../../../../tools/product-e2e/tests/PI_INTEGRATION.md) | [DSH journeys](../../../../../tools/product-e2e/tests/DSH_INTEGRATION.md) |Main-Agent configuration adds only selected Plan aliases. It leaves native defaults,purpose routing, extensions, hooks, MCP and Skills to their existing owners. The@@ -23,7 +24,8 @@ A native provider name alone never grants ownership of an existing user entry.- [Native edits](../additional_native.rs) enforce the independent namespace,semantic ownership, default reference and encrypted restore binding.- [JSONC edits](../qoder_jsonc.rs) preserve unrelated bytes and comments. The name- is historical; it is the single bounded parser/editor shared by both adapters.+ is historical; it is the single bounded parser/editor for Qoder/Pi. DSH uses+ its static YAML leaf below.Ambiguous duplicate keys, invalid JSON and oversized files fail closed. Linecomments accept LF/CRLF; standalone CR and Unicode line separators are rejectedbecause native readers disagree about where such comments end.@@ -45,7 +47,9 @@ The prepared local grant is written only to the private native provider, mode0600. Public journals contain no bearer or original native settings. Status readsuse the protected artifact port; restoration can still remove an owned secretfollowing permission drift. Preserve existing Qoder journal/restore wire strings-as registered recovery contracts; new Pi writes use its current closed kind.+as registered recovery contracts; Pi/DSH use their current closed kinds. Current+multi-provider writes produce V2 restore records; V1 remains a registered reader+for historical single-provider writes.## Adjustment and recovery@@ -70,3 +74,11 @@ arguments, rotates its grant, rejects removed routes, and restores model/Skillfacets separately. Unit fixtures do not prove native model calls. Neither nativeprotocol differences nor backend capability evidence require an extra user-facingverification button or status badge.++DSH uses the same per-provider ownership, protected grant, stale-preview and+restore engine. Its leaf is [dsh_config.rs](../dsh_config.rs): bounded static YAML+patch sequences, one affected `llm-pi-ai` row, public `baseURL` and+`agent-default-model` references. Unrelated rows retain their bytes.+[DSH native admission](../dsh_native.rs) rejects a higher-priority global provider+row that would shadow the managed standard Web profile. It never evaluates JS,+includes, plugins or credential helpers. See [the DSH code map](../../../../../docs/code-map/dsh.md).diff --git a/crates/integrations/src/agents/additional_native_effects.rs b/crates/integrations/src/agents/additional_native_effects.rsindex 5d7ebb83..d89277a7 100644--- a/crates/integrations/src/agents/additional_native_effects.rs+++ b/crates/integrations/src/agents/additional_native_effects.rs@@ -144,6 +144,7 @@ fn stage(let kind = match intent.desired()["subject"]["agent_id"].as_str() {Some("agent_qoder_default") => AgentKindV1::Qoder,Some("agent_pi_default") => AgentKindV1::Pi,+ Some("agent_dsh_default") => AgentKindV1::DeepseekHarness,_ => return Err(error(PortErrorCode::InvalidData, "additional.native.kind")),};let edit = additional_native::configure(diff --git a/crates/integrations/src/agents/dsh_config.rs b/crates/integrations/src/agents/dsh_config.rsnew file mode 100644index 00000000..96cff083--- /dev/null+++ b/crates/integrations/src/agents/dsh_config.rs@@ -0,0 +1,236 @@+//! Bounded, passive DSH public patch documents. No YAML expressions or plugins are executed.+use super::pi_sources::clear_native_value;+use super::{QoderNativeError, qoder_error};+use serde_json::{Value, json};+use zeroize::Zeroizing;++pub(super) struct Patch {+ rows: Vec<Value>,+ bytes: Zeroizing<Vec<u8>>,+ spans: Vec<std::ops::Range<usize>>,+}+impl Drop for Patch {+ fn drop(&mut self) {+ self.rows.iter_mut().for_each(clear_native_value);+ }+}+impl Patch {+ pub fn parse(bytes: Option<&[u8]>) -> Result<Self, QoderNativeError> {+ let bytes = bytes.unwrap_or(b"[]\n");+ if bytes.len() > 2 * 1024 * 1024 {+ return Err(qoder_error("DSH patch bound"));+ }+ let text = std::str::from_utf8(bytes).map_err(|_| qoder_error("DSH patch encoding"))?;+ // serde_yaml normalizes unknown secondary tags (e.g. !!js) to scalars.+ // Refuse the executable public extensions before any such normalization.+ if text+ .lines()+ .filter(|l| !l.trim_start().starts_with('#'))+ .any(|l| l.contains("!!js") || l.contains("!include"))+ {+ return Err(qoder_error("DSH static patch required"));+ }+ let value: Value = if text.trim().is_empty() {+ json!([])+ } else {+ let yaml: serde_yaml::Value =+ serde_yaml::from_str(text).map_err(|_| qoder_error("DSH static patch required"))?;+ fn static_value(value: &serde_yaml::Value, depth: usize) -> bool {+ if depth > 32 {+ return false;+ }+ match value {+ serde_yaml::Value::Tagged(_) => false,+ serde_yaml::Value::Sequence(values) => {+ values.iter().all(|v| static_value(v, depth + 1))+ }+ serde_yaml::Value::Mapping(values) => values.iter().all(|(k, v)| {+ k.as_str().is_some_and(|k| k != "<<") && static_value(v, depth + 1)+ }),+ _ => true,+ }+ }+ if !static_value(&yaml, 0) {+ return Err(qoder_error("DSH static patch required"));+ }+ serde_json::to_value(yaml).map_err(|_| qoder_error("DSH static patch required"))?+ };+ let rows = value+ .as_array()+ .ok_or_else(|| qoder_error("DSH patch sequence"))?+ .clone();+ let mut offset = 0;+ let mut starts = Vec::new();+ for line in text.split_inclusive('\n') {+ if line.starts_with("- ") || line.trim_end() == "-" {+ starts.push(offset);+ }+ offset += line.len();+ }+ let spans = starts+ .iter()+ .enumerate()+ .map(|(i, start)| *start..starts.get(i + 1).copied().unwrap_or(bytes.len()))+ .collect();+ let mut ids = std::collections::BTreeSet::new();+ for row in &rows {+ if !row.is_object() {+ return Err(qoder_error("DSH patch row"));+ }+ if let Some(id) = row.get("id").and_then(Value::as_str)+ && !ids.insert(id)+ {+ return Err(qoder_error("DSH duplicate patch row"));+ }+ }+ Ok(Self {+ rows,+ bytes: Zeroizing::new(bytes.to_vec()),+ spans,+ })+ }+ pub fn config(&self, id: &str) -> Result<Option<&Value>, QoderNativeError> {+ let row = self.rows.iter().find(|r| r["id"] == id);+ if row.is_some_and(|r| {+ r.get("remove").is_some() || r.get("disabled").is_some_and(|v| v != false)+ }) {+ return Err(qoder_error("DSH disabled target"));+ }+ Ok(row.and_then(|r| r.get("config")))+ }+ pub fn credentials_config(&self) -> Result<Option<&Value>, QoderNativeError> {+ // Nested insert/remove operations can replace the module. Do not infer+ // the default store from a composition this passive reader cannot prove.+ if self.rows.iter().any(|r| {+ r["id"].as_str().is_none()+ || r.as_object().expect("validated row").keys().any(|k| {+ !matches!(k.as_str(), "id" | "name" | "config" | "disabled" | "remove")+ })+ }) {+ return Err(qoder_error("DSH static credentials composition required"));+ }+ if let Some(row) = self.rows.iter().find(|r| r["id"] == "credentials")+ && row+ .get("name")+ .is_some_and(|v| v != "@deepseek-ai/dsh-credentials-local")+ {+ return Err(qoder_error("DSH standard credentials module required"));+ }+ self.config("credentials")+ }+ pub fn providers(&self) -> Result<Value, QoderNativeError> {+ let providers = self+ .config("llm-pi-ai")?+ .and_then(|c| c.get("providers"))+ .cloned()+ .unwrap_or_else(|| json!({}));+ if !providers.is_object() {+ return Err(qoder_error("DSH providers object"));+ }+ Ok(providers)+ }+ pub fn model_root(&self) -> Result<Value, QoderNativeError> {+ let mut value = json!({"providers":self.providers()?});+ if let Some(default) = self.config("agent-default-model")?+ && let (Some(provider), Some(model)) =+ (default["provider"].as_str(), default["model"].as_str())+ {+ value["model"] = json!({"name":format!("{provider}/{model}")});+ }+ Ok(value)+ }+ pub fn edit_provider(+ &self,+ id: &str,+ provider: Option<&Value>,+ ) -> Result<Zeroizing<Vec<u8>>, QoderNativeError> {+ // Static flow documents are readable, but only block sequences have safe edit spans.+ // An empty sequence has no foreign rows to preserve.+ if self.spans.len() != self.rows.len() {+ return Err(qoder_error("DSH block patch required"));+ }+ if let Some(first) = self.spans.first() {+ let prefix = std::str::from_utf8(&self.bytes[..first.start])+ .map_err(|_| qoder_error("DSH patch encoding"))?;+ if prefix.lines().any(|line| {+ let line = line.trim();+ !line.is_empty() && !line.starts_with('#') && line != "---"+ }) {+ return Err(qoder_error("DSH block patch required"));+ }+ // A dash inside a multiline string is not a top-level row. Prove each span+ // independently represents the corresponding semantic row before editing it.+ for (span, row) in self.spans.iter().zip(&self.rows) {+ let fragment = Self::parse(Some(&self.bytes[span.clone()]))?;+ if fragment.rows.as_slice() != std::slice::from_ref(row) {+ return Err(qoder_error("DSH block patch required"));+ }+ }+ }+ let index = self.rows.iter().position(|r| r["id"] == "llm-pi-ai");+ let mut row = index+ .map(|i| self.rows[i].clone())+ .unwrap_or_else(|| json!({"id":"llm-pi-ai","config":{"providers":{}}}));+ if row.get("config").is_none() {+ row["config"] = json!({});+ }+ if !row["config"].is_object() {+ return Err(qoder_error("DSH provider config"));+ }+ let mut providers = self.providers()?;+ let map = providers.as_object_mut().expect("validated providers");+ match provider {+ Some(value) => {+ map.insert(id.into(), value.clone());+ }+ None => {+ map.remove(id);+ }+ }+ row["config"]["providers"] = providers;+ // JSON is a public YAML subset; only the affected row is reformatted.+ let rendered =+ serde_json::to_string_pretty(&row).map_err(|_| qoder_error("DSH patch encoding"))?;+ let rendered = format!("- {}\n", rendered.replace('\n', "\n "));+ let mut output = Zeroizing::new(Vec::new());+ if let Some(index) = index {+ let span = &self.spans[index];+ output.extend_from_slice(&self.bytes[..span.start]);+ output.extend_from_slice(rendered.as_bytes());+ output.extend_from_slice(&self.bytes[span.end..]);+ } else {+ if !self.rows.is_empty() || self.bytes.contains(&b'#') {+ // Preserve leading comments, omitting the empty sequence syntax.+ for line in self.bytes.split_inclusive(|b| *b == b'\n') {+ if line.starts_with(b"#") || line.iter().all(u8::is_ascii_whitespace) {+ output.extend_from_slice(line);+ }+ }+ if !self.rows.is_empty() {+ output = Zeroizing::new(self.bytes.to_vec());+ }+ }+ if !output.is_empty() && !output.ends_with(b"\n") {+ output.push(b'\n');+ }+ output.extend_from_slice(rendered.as_bytes());+ }+ Self::parse(Some(&output))?;+ Ok(output)+ }+}++/// Native composition files are public-readable; credentials keep the private reader.+pub(super) fn read_patch_bytes(+ path: &std::path::Path,+) -> Result<Zeroizing<Vec<u8>>, super::AgentFilesystemScanError> {+ let observed = super::filesystem_config::read_system_config_bytes(path)?;+ #[cfg(unix)]+ if let Some((_, metadata)) = &observed {+ use std::os::unix::fs::MetadataExt;+ if metadata.uid() != nix::unistd::geteuid().as_raw() {+ return Err(super::AgentFilesystemScanError::WrongOwner);+ }+ }+ Ok(observed.map(|(bytes, _)| bytes).unwrap_or_default())+}diff --git a/crates/integrations/src/agents/dsh_native.rs b/crates/integrations/src/agents/dsh_native.rsnew file mode 100644index 00000000..b7101804--- /dev/null+++ b/crates/integrations/src/agents/dsh_native.rs@@ -0,0 +1,276 @@+//! DSH standard Web model target and native Skill resources; no internal SDK or history reader.+use super::*;+use hiroute_domain::{AgentCapability, CapabilityState};++impl FilesystemAgentScannerV1 {+ /// Higher-priority home configuration is independent of the managed Web file.+ /// Recheck it on configure and restore, without requiring an installed CLI.+ pub fn dsh_web_default_in_use(+ &self,+ namespace: &str,+ models: &[hiroute_domain::AdditionalAgentModelV1],+ ) -> Result<bool, AgentFilesystemScanError> {+ let bytes = super::super::dsh_config::read_patch_bytes(+ &self.layout.dsh_config_root.join("cordis.patch.yml"),+ )?;+ let patch = super::super::dsh_config::Patch::parse(Some(&bytes))+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?;+ let invalid = |_| AgentFilesystemScanError::InvalidConfig;+ if patch.config("llm-pi-ai").map_err(invalid)?.is_some() {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ let Some(default) = patch.config("agent-default-model").map_err(invalid)? else {+ return Ok(false);+ };+ let provider = default["provider"]+ .as_str()+ .ok_or(AgentFilesystemScanError::InvalidConfig)?;+ let model = default["model"]+ .as_str()+ .ok_or(AgentFilesystemScanError::InvalidConfig)?;+ let owned = provider == namespace+ || provider+ .strip_prefix(&format!("{namespace}-"))+ .is_some_and(|s| s.len() == 32 && s.bytes().all(|b| b.is_ascii_hexdigit()));+ Ok(owned+ && !models.iter().any(|m| {+ m.alias == model+ && hiroute_domain::additional_model_provider_for(namespace, models, m)+ == provider+ }))+ }+ pub fn dsh_user_models_target(&self) -> PathBuf {+ self.layout+ .dsh_config_root+ .join("profiles/web/cordis.patch.yml")+ }+ pub fn dsh_user_skill_target(&self) -> PathBuf {+ self.layout+ .dsh_config_root+ .join("skills/hiroute-collaboration/SKILL.md")+ }+ pub fn dsh_executable_target(&self) -> Option<PathBuf> {+ super::super::executable::resolve(&self.layout.dsh_executable)+ .ok()+ .flatten()+ }+ fn dsh_native_contract(+ &self,+ models: bool,+ ) -> Result<CanonicalDigest, AgentFilesystemScanError> {+ let mut dependencies = Vec::new();+ let profiles: &[&str] = if models {+ &["cordis.patch.yml", "profiles/web/cordis.patch.yml"]+ } else {+ &[+ "cordis.patch.yml",+ "profiles/web/cordis.patch.yml",+ "profiles/acp/cordis.patch.yml",+ ]+ };+ for relative in profiles {+ let path = self.layout.dsh_config_root.join(relative);+ let document = super::super::dsh_config::read_patch_bytes(&path)?;+ let bytes = document.as_slice();+ let patch = super::super::dsh_config::Patch::parse(Some(bytes))+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?;+ if models+ && *relative == "cordis.patch.yml"+ && patch+ .config("llm-pi-ai")+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?+ .is_some()+ {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ if models {+ dependencies.push(CanonicalDigest::of_bytes(bytes));+ } else {+ let resources = [+ "skill-filesystem",+ "tool-skill",+ "tool-fs",+ "tool-bash",+ "skill",+ ]+ .map(|id| patch.config(id))+ .into_iter()+ .collect::<Result<Vec<_>, _>>()+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?;+ if let Some(config) = resources[0]+ && (config+ .get("dshHome")+ .is_some_and(|v| v.as_str() != self.layout.dsh_config_root.to_str())+ || config["includeDefaultRoots"] == false)+ {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ // Model-only changes cannot revoke a still-valid collaboration resource proof.+ dependencies.push(+ CanonicalDigest::of(&resources)+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?,+ );+ }+ }+ let executable = self+ .dsh_executable_target()+ .ok_or(AgentFilesystemScanError::SourceUnavailable)?;+ let metadata = std::fs::metadata(&executable)+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?;+ CanonicalDigest::of(&(+ executable,+ metadata.len(),+ metadata.modified().ok(),+ dependencies,+ ))+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)+ }+ pub fn dsh_settings_discovery(&self) -> FilesystemAgentDiscoveryV1 {+ let Some(executable) = self.dsh_executable_target() else {+ return probe_report(+ "agent_dsh_default",+ AgentKindV1::DeepseekHarness,+ ExecutableProbe::NotFound,+ );+ };+ let version = match executable_probe(&executable) {+ ExecutableProbe::Installed(value) => value.version,+ _ => String::new(),+ };+ let mut outcome = resolve_agent_observation(base_observation(+ "agent_dsh_default",+ AgentKindV1::DeepseekHarness,+ version,+ ));+ if let AgentDiscoveryOutcomeV1::Supported { installation } = &mut outcome {+ super::super::observed_capabilities::attach_file_capabilities(+ installation,+ &executable,+ &self.dsh_user_skill_target(),+ );+ if let Ok(digest) = self.dsh_native_contract(false) {+ installation.observation_digest =+ CanonicalDigest::of(&(&installation.observation_digest, &digest))+ .expect("native contract");+ let checked = self+ .dsh_collaboration_cli+ .lock()+ .ok()+ .and_then(|v| v.clone());+ for proof in &mut installation.capability_evidence {+ proof.dependency_digest = installation.observation_digest.clone();+ if matches!(+ proof.capability,+ AgentCapability::SkillLoading | AgentCapability::TrustedCliExecution+ ) && checked.as_ref().is_some_and(|(cli, recorded)| {+ *recorded == digest+ && super::super::executable::resolve(cli)+ .ok()+ .flatten()+ .as_ref()+ == Some(cli)+ }) {+ proof.state = CapabilityState::Proven;+ proof.reason = None;+ proof.adapter_contract = "hiroute.dsh-public-native-resources/v1".into();+ }+ }+ }+ }+ FilesystemAgentDiscoveryV1 {+ outcome,+ configuration_issue: None,+ claude_configuration: None,+ discovered_credential: None,+ permission_hardening: None,+ managed_launch: None,+ }+ }+ #[cfg(unix)]+ pub fn check_dsh_model_configuration(&self) -> Result<(), AgentFilesystemScanError> {+ self.dsh_native_contract(true)?;+ self.check_dsh_public_cli(&["llm-pi-ai"])+ }+ #[cfg(unix)]+ pub fn check_dsh_collaboration(&self, cli: &Path) -> Result<(), AgentFilesystemScanError> {+ *self+ .dsh_collaboration_cli+ .lock()+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)? = None;+ let before = self.dsh_native_contract(false)?;+ self.check_dsh_public_cli(&[+ "skill-filesystem",+ "tool-skill",+ "tool-fs",+ "tool-bash",+ "skill",+ ])?;+ let cli = super::super::executable::resolve(cli)+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?+ .ok_or(AgentFilesystemScanError::SourceUnavailable)?;+ if before != self.dsh_native_contract(false)? {+ return Err(AgentFilesystemScanError::SourceChanged);+ }+ *self+ .dsh_collaboration_cli+ .lock()+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)? = Some((cli, before));+ Ok(())+ }+ #[cfg(unix)]+ fn check_dsh_public_cli(&self, required: &[&str]) -> Result<(), AgentFilesystemScanError> {+ use std::os::unix::process::CommandExt;+ use std::process::{Command, Stdio};+ let root = tempfile::tempdir().map_err(|_| AgentFilesystemScanError::SourceUnavailable)?;+ let output = root.path().join("config");+ let file = std::fs::File::create(&output)+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?;+ // Dumping the shipped composition is public and does not activate plugins or model calls.+ // Its profile initialization is contained here; the real HOME and settings stay intact.+ let child = Command::new(+ self.dsh_executable_target()+ .ok_or(AgentFilesystemScanError::SourceUnavailable)?,+ )+ .args(["--profile", "acp", "--dump-default-config"])+ .env("DSH_HOME", root.path())+ .stdin(Stdio::null())+ .stdout(file)+ .stderr(Stdio::null())+ .process_group(0)+ .spawn()+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?;+ let mut child = super::super::NativeProbeProcess::new(child);+ let started = std::time::Instant::now();+ loop {+ match child+ .observe()+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?+ {+ Some(true) => break,+ Some(false) => return Err(AgentFilesystemScanError::InvalidConfig),+ None if started.elapsed() > std::time::Duration::from_secs(15) => {+ return Err(AgentFilesystemScanError::SourceUnavailable);+ }+ None => std::thread::sleep(std::time::Duration::from_millis(20)),+ }+ if std::fs::metadata(&output).is_ok_and(|m| m.len() > 2 * 1024 * 1024) {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ }+ child+ .stop()+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?;+ let bytes = super::super::native_probe_process::read_bounded(&output, 2 * 1024 * 1024)+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?;+ let text =+ std::str::from_utf8(&bytes).map_err(|_| AgentFilesystemScanError::InvalidConfig)?;+ if required.iter().any(|id| {+ !text+ .lines()+ .any(|line| line.trim() == format!("- id: {id}"))+ }) {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ Ok(())+ }+}diff --git a/crates/integrations/src/agents/dsh_sources.rs b/crates/integrations/src/agents/dsh_sources.rsnew file mode 100644index 00000000..32dabdaf--- /dev/null+++ b/crates/integrations/src/agents/dsh_sources.rs@@ -0,0 +1,274 @@+//! Passive explicit DSH API routes. Catalog/OAuth discovery and dynamic compositions are excluded.+use super::{+ AgentFilesystemScanError as Error, DiscoveredAuthSource, DiscoveredCredentialRefV1,+ FILESYSTEM_AGENT_SCANNER_ID_V1, FILESYSTEM_AGENT_SCANNER_VERSION_V1, FilesystemAgentScannerV1,+ NativeApiSource,+};+use hiroute_domain::{CanonicalDigest, ProtectedSecret, UpstreamProtocol};+use serde_json::{Value, json};+use zeroize::Zeroizing;+type Snapshot = (+ Vec<NativeApiSource>,+ Option<(Zeroizing<String>, ProtectedSecret)>,+);++fn read_credentials(path: &std::path::Path) -> Result<Zeroizing<Vec<u8>>, Error> {+ let Some((bytes, metadata)) = super::filesystem_config::read_validated_config_bytes(path)?+ else {+ return Ok(Zeroizing::new(Vec::new()));+ };+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if metadata.permissions().mode() & 0o077 != 0 {+ return Err(Error::UnsafePermissions);+ }+ }+ Ok(bytes)+}++fn credentials_path(+ root: &std::path::Path,+ home: &super::dsh_config::Patch,+ profile: &super::dsh_config::Patch,+) -> Result<std::path::PathBuf, Error> {+ let profile = profile+ .credentials_config()+ .map_err(|_| Error::InvalidConfig)?;+ let home = home+ .credentials_config()+ .map_err(|_| Error::InvalidConfig)?;+ // Home follows Web; each supplied config replaces the whole earlier object.+ let config = home.or(profile);+ if config.is_some_and(|c| {+ !c.is_object()+ || c.as_object().is_some_and(|o| {+ o.keys()+ .any(|k| !matches!(k.as_str(), "path" | "dshHome" | "watch" | "debounceMs"))+ })+ }) {+ return Err(Error::InvalidConfig);+ }+ let configured = config.and_then(|c| c.get("path").or_else(|| c.get("dshHome")));+ let path = if let Some(configured) = configured {+ let path = configured+ .as_str()+ .filter(|s| !s.is_empty() && s.len() <= 4096 && !s.contains('\0'))+ .ok_or(Error::InvalidConfig)?;+ let path = std::path::Path::new(path);+ // Native relative/tilde resolution depends on invocation context; reject+ // instead of borrowing HiRoute's cwd or HOME to guess a different file.+ if !path.is_absolute() {+ return Err(Error::InvalidConfig);+ }+ if config.is_some_and(|c| c.get("path").is_some()) {+ path.to_path_buf()+ } else {+ path.join(".credentials.yaml")+ }+ } else {+ root.join(".credentials.yaml")+ };+ if !path.is_absolute() {+ return Err(Error::InvalidConfig);+ }+ // Match Node's lexical resolve, including `..` before following symlinks.+ let mut resolved = std::path::PathBuf::new();+ for component in path.components() {+ match component {+ std::path::Component::CurDir => {}+ std::path::Component::ParentDir => {+ resolved.pop();+ }+ _ => resolved.push(component.as_os_str()),+ }+ }+ Ok(resolved)+}+impl FilesystemAgentScannerV1 {+ pub fn dsh_api_sources(&self) -> Result<Vec<NativeApiSource>, Error> {+ Ok(self.dsh_sources_inner(None)?.0)+ }+ pub fn read_dsh_api_source(+ &self,+ selected: &NativeApiSource,+ ) -> Result<(Zeroizing<String>, ProtectedSecret), Error> {+ let (sources, material) = self.dsh_sources_inner(Some(&selected.source_ref))?;+ if !sources.contains(selected) || !self.dsh_api_sources()?.contains(selected) {+ return Err(Error::SourceChanged);+ }+ material.ok_or(Error::SourceUnavailable)+ }+ pub(super) fn read_dsh_secret(+ &self,+ descriptor: &DiscoveredCredentialRefV1,+ ) -> Result<ProtectedSecret, Error> {+ let source = self+ .dsh_api_sources()?+ .into_iter()+ .find(|s| s.credential.as_ref() == Some(descriptor))+ .ok_or(Error::SourceChanged)?;+ Ok(self.read_dsh_api_source(&source)?.1)+ }+ fn dsh_sources_inner(&self, selected: Option<&str>) -> Result<Snapshot, Error> {+ let home = super::dsh_config::read_patch_bytes(+ &self.layout.dsh_config_root.join("cordis.patch.yml"),+ )?;+ let profile = super::dsh_config::read_patch_bytes(&self.dsh_user_models_target())?;+ let home_patch =+ super::dsh_config::Patch::parse(Some(&home)).map_err(|_| Error::InvalidConfig)?;+ let profile_patch =+ super::dsh_config::Patch::parse(Some(&profile)).map_err(|_| Error::InvalidConfig)?;+ let providers = super::pi_sources::Document(+ if home_patch+ .config("llm-pi-ai")+ .map_err(|_| Error::InvalidConfig)?+ .is_some()+ {+ home_patch.providers()+ } else {+ profile_patch.providers()+ }+ .map_err(|_| Error::InvalidConfig)?,+ );+ let credentials_path =+ credentials_path(&self.layout.dsh_config_root, &home_patch, &profile_patch)?;+ let credentials = read_credentials(&credentials_path)?;+ let credentials_value = super::pi_sources::Document(if credentials.is_empty() {+ json!({"version":1})+ } else {+ serde_yaml::from_slice::<Value>(&credentials).map_err(|_| Error::InvalidConfig)?+ });+ if credentials_value.0["version"] != 1 {+ return Err(Error::InvalidConfig);+ }+ let mut sources = Vec::new();+ let mut material = None;+ for (provider_id, provider) in providers.0.as_object().ok_or(Error::InvalidConfig)? {+ if provider_id.starts_with("hiroute-") {+ continue;+ }+ if sources.len() >= 256 {+ return Err(Error::ConfigTooLarge);+ }+ let reference = provider["apiKeyEnv"].as_str().filter(|r| {+ r.bytes()+ .next()+ .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')+ && r.len() <= 256+ && r.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')+ });+ let secret = reference+ .and_then(|r| {+ std::env::var(r)+ .ok()+ .filter(|v| !v.is_empty())+ .or_else(|| credentials_value.0["refs"][r].as_str().map(str::to_owned))+ })+ .map(Zeroizing::new);+ let protocol = match provider["api"].as_str() {+ Some("openai-responses") => Some(UpstreamProtocol::Responses),+ Some("anthropic-messages") => Some(UpstreamProtocol::Messages),+ Some("openai-completions") => Some(UpstreamProtocol::ChatCompletions),+ _ => None,+ };+ let endpoint = provider["baseURL"].as_str().filter(|s| s.len() <= 4096);+ let supported = endpoint.is_some()+ && provider.get("compat").is_none()+ && provider.get("modelOverrides").is_none()+ && provider+ .get("headers")+ .is_none_or(|h| h.as_object().is_some_and(|o| o.is_empty()));+ let Some(models) = provider+ .get("models")+ .map(|m| m.as_array().ok_or(Error::InvalidConfig))+ .transpose()?+ else {+ // Native catalog inheritance is not an explicit, portable model declaration.+ continue;+ };+ let mut seen = std::collections::BTreeSet::new();+ for model in models {+ if sources.len() >= 256 {+ return Err(Error::ConfigTooLarge);+ }+ let id = model["id"]+ .as_str()+ .filter(|s| !s.is_empty() && s.len() <= 256)+ .ok_or(Error::InvalidConfig)?;+ if !seen.insert(id) {+ return Err(Error::InvalidConfig);+ }+ let supported = supported && model.get("compat").is_none();+ let digest = CanonicalDigest::of(&(+ "dsh-api-source/v1",+ &self.layout.dsh_config_root,+ provider_id,+ id,+ ))+ .map_err(|_| Error::InvalidConfig)?;+ let source_ref = format!("dsh-source/{}", &digest.as_str()[7..]);+ let evidence_digest = CanonicalDigest::of(&(+ "dsh-api-evidence/v1",+ &source_ref,+ CanonicalDigest::of_bytes(&home),+ CanonicalDigest::of_bytes(&profile),+ &credentials_path,+ CanonicalDigest::of_bytes(&credentials),+ secret+ .as_ref()+ .map(|s| CanonicalDigest::of_bytes(s.as_bytes())),+ ))+ .map_err(|_| Error::InvalidConfig)?;+ let revision = u64::from_str_radix(&evidence_digest.as_str()[7..23], 16)+ .map_err(|_| Error::InvalidConfig)?+ .max(1);+ let credential = secret+ .as_ref()+ .filter(|s| supported && !s.is_empty())+ .map(|_| DiscoveredCredentialRefV1 {+ source: "discovered_config".into(),+ scanner_id: FILESYSTEM_AGENT_SCANNER_ID_V1.into(),+ scanner_version: FILESYSTEM_AGENT_SCANNER_VERSION_V1.into(),+ discovered_source_ref: source_ref.clone(),+ field_selector: "dsh.api-key".into(),+ observed_revision: revision,+ });+ if selected == Some(source_ref.as_str())+ && supported+ && let (Some(endpoint), Some(secret)) = (endpoint, secret.as_ref())+ {+ material = Some((+ Zeroizing::new(endpoint.to_owned()),+ ProtectedSecret::new(secret.as_bytes().to_vec())+ .map_err(|_| Error::InvalidConfig)?,+ ));+ }+ sources.push(NativeApiSource {+ provider_id: provider_id.clone(),+ model_id: id.into(),+ protocol,+ display_name: model["name"].as_str().unwrap_or(id).into(),+ context_tokens: model["contextWindow"].as_u64(),+ max_output_tokens: model["maxTokens"].as_u64(),+ vision: model["input"]+ .as_array()+ .filter(|a| !a.is_empty())+ .map(|a| a.iter().any(|v| v == "image")),+ reasoning: None,+ authentication: if secret.is_some() {+ DiscoveredAuthSource::InlineToken+ } else {+ DiscoveredAuthSource::Missing+ },+ source_ref,+ evidence_digest,+ revision,+ credential,+ supported_auth: supported,+ });+ }+ }+ Ok((sources, material))+ }+}diff --git a/crates/integrations/src/agents/dsh_tests.rs b/crates/integrations/src/agents/dsh_tests.rsnew file mode 100644index 00000000..f89cbf85--- /dev/null+++ b/crates/integrations/src/agents/dsh_tests.rs@@ -0,0 +1,163 @@+use super::additional_native::{Restore, configure};+use super::dsh_config::Patch;+use hiroute_domain::{+ AdditionalAgentModelV1, AgentAccessGrantMaterial, AgentIngressProtocolV1, AgentKindV1,+};+const OWNER: &str = "hiroute-main-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";++#[test]+fn dsh_additional_routes_preserve_foreign_configuration_and_restore_after_user_edits() {+ let original = b"# user's configuration\n- id: llm-pi-ai\n config:\n providers:\n native:\n api: openai-responses\n baseURL: https://native.invalid/v1\n models: [{id: original}]\n- id: agent-default-model\n config: {provider: native, model: original}\n- id: unrelated\n config: {keep: true}\n";+ let models: Vec<_> = [+ AgentIngressProtocolV1::Responses,+ AgentIngressProtocolV1::Messages,+ ]+ .into_iter()+ .enumerate()+ .map(|(i, protocol)| AdditionalAgentModelV1 {+ alias: format!("hiroute/{i:016x}"),+ protocol,+ context_window_tokens: 32768,+ max_output_tokens: 4096,+ })+ .collect();+ let token = AgentAccessGrantMaterial::from_csprng_entropy([4; 32]);+ let edit = configure(+ AgentKindV1::DeepseekHarness,+ Some(original),+ OWNER,+ "http://127.0.0.1:4321/v1",+ &models,+ &token,+ None,+ )+ .unwrap();+ let root = Patch::parse(Some(&edit.bytes))+ .unwrap()+ .model_root()+ .unwrap();+ assert_eq!(+ root["providers"]["native"]["baseURL"],+ "https://native.invalid/v1"+ );+ assert_eq!(root["model"]["name"], "native/original");+ assert!(+ std::str::from_utf8(&edit.bytes)+ .unwrap()+ .contains("- id: unrelated\n config: {keep: true}\n")+ );+ for model in &models {+ let id = hiroute_domain::additional_model_provider_for(OWNER, &models, model);+ assert_eq!(+ root["providers"][&id]["api"],+ if model.protocol == AgentIngressProtocolV1::Responses {+ "openai-responses"+ } else {+ "anthropic-messages"+ }+ );+ assert_eq!(+ root["providers"][&id]["baseURL"],+ if model.protocol == AgentIngressProtocolV1::Responses {+ "http://127.0.0.1:4321/v1"+ } else {+ "http://127.0.0.1:4321"+ }+ );+ assert!(root["providers"][&id].get("apiKeyEnv").is_none());+ assert_eq!(+ root["providers"][&id]["headers"]["X-HiRoute-Token"],+ std::str::from_utf8(token.expose()).unwrap()+ );+ }+ let restore = Restore::decode(&edit.restore.encode().unwrap()).unwrap();+ assert_eq!(+ restore+ .restore(Some(&edit.bytes))+ .unwrap()+ .unwrap()+ .as_slice(),+ original+ );+ let edited = [+ edit.bytes.as_slice(),+ b"- id: later-edit\n config: {keep: later}\n",+ ]+ .concat();+ let restored = restore.restore(Some(&edited)).unwrap().unwrap();+ assert!(+ std::str::from_utf8(&restored)+ .unwrap()+ .contains("- id: later-edit\n config: {keep: later}\n")+ );+ assert_eq!(+ Patch::parse(Some(&restored))+ .unwrap()+ .providers()+ .unwrap()+ .as_object()+ .unwrap()+ .len(),+ 1+ );+ let id = hiroute_domain::additional_model_provider_for(OWNER, &models, &models[0]);+ let selected = [+ edit.bytes.as_slice(),+ format!(+ "- id: agent-default-model2\n config: {{provider: '{id}', model: '{}'}}\n",+ models[0].alias+ )+ .as_bytes(),+ ]+ .concat();+ // A real native default reference blocks removal; it never silently selects a replacement.+ let selected = String::from_utf8(selected)+ .unwrap()+ .replace("- id: agent-default-model\n", "- id: old-default\n")+ .replace("agent-default-model2", "agent-default-model");+ assert!(restore.restore(Some(selected.as_bytes())).is_err());+}++#[test]+fn dsh_dynamic_or_ambiguous_configuration_is_rejected_without_evaluation() {+ for bytes in [+ b"- id: llm-pi-ai\n config: !!js 'run()'\n".as_slice(),+ b"- id: llm-pi-ai\n config: {}\n- id: llm-pi-ai\n config: {}\n",+ b"- id: llm-pi-ai\n config: {<<: {providers: {}}}\n",+ ] {+ assert!(+ Patch::parse(Some(bytes)).is_err(),+ "accepted unsafe patch: {}",+ String::from_utf8_lossy(bytes)+ );+ }+}++#[test]+fn dsh_flow_configuration_is_readable_but_not_edited_without_safe_row_spans() {+ for bytes in [+ br#"[{"id":"llm-pi-ai","config":{"providers":{"native":{"api":"openai-responses"}}}},{"id":"agent-default-model","config":{"provider":"native","model":"original"}}]"#.as_slice(),+ b"[{id: llm-pi-ai, config: {providers: {native: {api: openai-responses}}}}, {id: agent-default-model, config: {provider: native, model: original}}]\n".as_slice(),+ b"[\n {id: llm-pi-ai, config: {providers: {native: {api: openai-responses}}}},\n {id: agent-default-model, config: {provider: native, model: original, note: \"first\n- one\n- two\nlast\"}}\n]\n".as_slice(),+ ] {+ let patch = Patch::parse(Some(bytes)).unwrap();+ assert_eq!(patch.providers().unwrap()["native"]["api"], "openai-responses");+ assert_eq!(patch.model_root().unwrap()["model"]["name"], "native/original");+ assert!(patch.edit_provider("owned", Some(&serde_json::json!({}))).is_err());+ assert!(patch.edit_provider("native", None).is_err());+ }+}++#[test]+fn dsh_native_bootstrap_comment_is_not_an_executable_expression() {+ let patch = b"# overrides and inserts; `!!js` expressions allowed.\n[]\n";+ assert!(+ Patch::parse(Some(patch))+ .unwrap()+ .providers()+ .unwrap()+ .as_object()+ .unwrap()+ .is_empty()+ );+}diff --git a/crates/integrations/src/agents/filesystem.rs b/crates/integrations/src/agents/filesystem.rsindex 2a21c5b6..ecd536f3 100644--- a/crates/integrations/src/agents/filesystem.rs+++ b/crates/integrations/src/agents/filesystem.rs@@ -31,6 +31,8 @@ use super::{#[path = "filesystem/claude_settings.rs"]mod claude_settings;+#[path = "dsh_native.rs"]+mod dsh_native;#[path = "claude_observation.rs"]mod main_observation;#[path = "pi_native.rs"]@@ -128,6 +130,8 @@ pub struct AgentFilesystemLayoutV1 {pub qoder_executable: PathBuf,pub pi_executable: PathBuf,pub pi_config_root: PathBuf,+ pub dsh_executable: PathBuf,+ pub dsh_config_root: PathBuf,pub qoder_home: PathBuf,pub qoder_config_root: PathBuf,pub codex_user_config: PathBuf,@@ -172,6 +176,11 @@ impl AgentFilesystemLayoutV1 {claude_executable: PathBuf::from("claude"),qoder_executable: PathBuf::from("qoder"),pi_executable: PathBuf::from("pi"),+ dsh_executable: PathBuf::from("dsh"),+ dsh_config_root: std::env::var_os("DSH_HOME")+ .filter(|v| !v.is_empty())+ .map(PathBuf::from)+ .unwrap_or_else(|| home.join(".dsh")),pi_config_root: std::env::var_os("PI_CODING_AGENT_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)@@ -207,6 +216,7 @@ impl AgentFilesystemLayoutV1 {pub struct FilesystemAgentScannerV1 {pi_collaboration_cli:std::sync::Arc<std::sync::Mutex<Option<(PathBuf, hiroute_domain::CanonicalDigest)>>>,+ dsh_collaboration_cli: std::sync::Arc<std::sync::Mutex<Option<(PathBuf, CanonicalDigest)>>>,pub(super) layout: AgentFilesystemLayoutV1,registry: ClaudeRegistrationIndexV1,legacy_recovery_version: Option<String>,@@ -275,6 +285,7 @@ impl FilesystemAgentScannerV1 {#[cfg(unix)]qoder_collaboration: Default::default(),pi_collaboration_cli: Default::default(),+ dsh_collaboration_cli: Default::default(),}}@@ -382,6 +393,7 @@ impl FilesystemAgentScannerV1 {self.scan_codex(),self.qoder_settings_discovery(false),self.pi_settings_discovery(),+ self.dsh_settings_discovery(),];match executable_probe(&self.layout.claude_executable) {ExecutableProbe::Installed(executable) => {@@ -416,7 +428,7 @@ impl FilesystemAgentScannerV1 {);self.layout.claude_executable.clone()}- AgentKindV1::Qoder | AgentKindV1::Pi => continue,+ AgentKindV1::Qoder | AgentKindV1::Pi | AgentKindV1::DeepseekHarness => continue,};#[cfg(unix)]if installation.profile.kind == AgentKindV1::Codex@@ -487,6 +499,9 @@ impl FilesystemAgentScannerV1 {if descriptor.field_selector == "pi.api-key" {return self.read_pi_secret(descriptor);}+ if descriptor.field_selector == "dsh.api-key" {+ return self.read_dsh_secret(descriptor);+ }validate_descriptor(descriptor)?;let source = self.claude_sources()@@ -551,7 +566,8 @@ impl FilesystemAgentScannerV1 {}hiroute_domain::AgentModelSurfaceV2::ClaudeCli| hiroute_domain::AgentModelSurfaceV2::QoderCli- | hiroute_domain::AgentModelSurfaceV2::PiCli => None,+ | hiroute_domain::AgentModelSurfaceV2::PiCli+ | hiroute_domain::AgentModelSurfaceV2::DshCli => None,}}@@ -583,6 +599,9 @@ impl FilesystemAgentScannerV1 {.into_iter().collect()}+ "agent_dsh_default" if self.dsh_executable_target().is_some() => {+ [hiroute_domain::AgentModelSurfaceV2::DshCli].into()+ }"agent_pi_default" if self.pi_executable_target().is_some() => {[hiroute_domain::AgentModelSurfaceV2::PiCli].into()}diff --git a/crates/integrations/src/agents/filesystem_tests.rs b/crates/integrations/src/agents/filesystem_tests.rsindex fcd96433..68c6eb2e 100644--- a/crates/integrations/src/agents/filesystem_tests.rs+++ b/crates/integrations/src/agents/filesystem_tests.rs@@ -11,6 +11,8 @@ use crate::agents::{#[path = "filesystem_tests/claude_routing.rs"]mod claude_routing;+#[path = "filesystem_tests/dsh.rs"]+mod dsh;#[path = "filesystem_tests/pi.rs"]mod pi;#[path = "filesystem_tests/qoder.rs"]@@ -85,6 +87,8 @@ fn layout_with_claude_version(root: &Path, claude_version: &str) -> AgentFilesysqoder_executable: bin.join("qoder-not-installed"),pi_executable: root.join("bin/pi"),pi_config_root: root.join("home/.pi/agent"),+ dsh_executable: root.join("bin/dsh-not-installed"),+ dsh_config_root: root.join("home/.dsh"),qoder_home: home.clone(),qoder_config_root: home.join(".qoder"),codex_user_config: home.join(".codex/config.toml"),@@ -112,7 +116,15 @@ fn filesystem_scanner_registers_claude_and_never_serializes_token() {);let scanner = FilesystemAgentScannerV1::new(layout, registry());let results = scanner.scan();- assert_eq!(results.len(), 4);+ let unique: std::collections::BTreeSet<_> = results+ .iter()+ .map(|r| outcome_agent_id(&r.outcome))+ .collect();+ assert_eq!(+ unique.len(),+ results.len(),+ "discovered identities must be unique"+ );let claude = results.iter().find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")@@ -901,7 +913,15 @@ fn filesystem_scan_keeps_missing_installation_and_other_agent_result() {let mut layout = layout(directory.path());layout.codex_executable = directory.path().join("not-installed");let results = FilesystemAgentScannerV1::new(layout, registry()).scan();- assert_eq!(results.len(), 4);+ let unique: std::collections::BTreeSet<_> = results+ .iter()+ .map(|r| outcome_agent_id(&r.outcome))+ .collect();+ assert_eq!(+ unique.len(),+ results.len(),+ "discovered identities must be unique"+ );assert!(results.iter().any(|result| matches!(&result.outcome,AgentDiscoveryOutcomeV1::ReportOnly {diff --git a/crates/integrations/src/agents/filesystem_tests/dsh.rs b/crates/integrations/src/agents/filesystem_tests/dsh.rsnew file mode 100644index 00000000..b85339ee--- /dev/null+++ b/crates/integrations/src/agents/filesystem_tests/dsh.rs@@ -0,0 +1,491 @@+//! DSH's supported passive source and CLI capability boundaries.+use super::*;++fn scanner(root: &Path) -> FilesystemAgentScannerV1 {+ let mut layout = layout(root);+ layout.dsh_executable = root.join("bin/dsh");+ fs::create_dir_all(&layout.dsh_config_root).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(&layout.dsh_config_root, fs::Permissions::from_mode(0o700)).unwrap();+ }+ FilesystemAgentScannerV1::new(layout, registry())+}++fn write_patch(path: &Path, patch: serde_json::Value) {+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, serde_json::to_vec(&patch).unwrap()).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ for directory in [+ path.parent().unwrap(),+ path.parent().unwrap().parent().unwrap(),+ ] {+ fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap();+ }+ fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();+ }+}++#[test]+fn dsh_static_flow_sources_require_explicit_models_and_preservable_model_semantics() {+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ write_secret_settings(+ &scanner.layout.dsh_config_root.join(".credentials.yaml"),+ json!({"version":1,"refs":{"DSH_STATIC_SOURCE_TEST_KEY":"portable-token"}}),+ );+ let mut provider = json!({"api":"openai-responses","baseURL":"https://source.invalid/v1",+ "apiKeyEnv":"DSH_STATIC_SOURCE_TEST_KEY"});+ for models in [None, Some(json!([]))] {+ if let Some(models) = models {+ provider["models"] = models;+ }+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([{"id":"llm-pi-ai","config":{"providers":{"native":provider}}}]),+ );+ assert!(+ scanner.dsh_api_sources().unwrap().is_empty(),+ "catalog-only providers are not explicit candidates"+ );+ }+ provider["models"] = json!([+ {"id":"portable","input":["text"]},+ {"id":"needs-compat","compat":{"supportsMaxOutputTokens":false}}+ ]);+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([{"id":"llm-pi-ai","config":{"providers":{"native":provider}}}]),+ );+ let sources = scanner.dsh_api_sources().unwrap();+ let portable = sources.iter().find(|s| s.model_id == "portable").unwrap();+ assert!(portable.supported_auth && portable.credential.is_some());+ scanner.read_dsh_api_source(portable).unwrap();+ let special = sources+ .iter()+ .find(|s| s.model_id == "needs-compat")+ .unwrap();+ assert!(!special.supported_auth && special.credential.is_none());+ assert!(scanner.read_dsh_api_source(special).is_err());+}++#[test]+fn dsh_model_input_is_unknown_until_explicit_and_nonempty() {+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([{"id":"llm-pi-ai","config":{+ "providers":{"native":{"api":"openai-responses","baseURL":"https://source.invalid/v1",+ "defaultInput":["text"],"models":[+ {"id":"inherited"},{"id":"empty","input":[]},+ {"id":"text","input":["text"]},{"id":"image","input":["text","image"]}+ ]}}+ }}]),+ );+ let sources = scanner.dsh_api_sources().unwrap();+ for (id, expected) in [+ ("inherited", None),+ ("empty", None),+ ("text", Some(false)),+ ("image", Some(true)),+ ] {+ assert_eq!(+ sources.iter().find(|s| s.model_id == id).unwrap().vision,+ expected,+ "{id}"+ );+ }+}++#[cfg(unix)]+#[test]+fn dsh_collaboration_requires_enabled_standard_resources_and_ignores_model_only_changes() {+ use hiroute_domain::{AgentCapability, CapabilityState};+ use std::os::unix::fs::PermissionsExt;+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let cli = &scanner.layout.dsh_executable;+ fs::write(cli, "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'DSH fixture'; else printf '%s\\n' '- id: skill' '- id: skill-filesystem' '- id: tool-skill' '- id: tool-fs' '- id: tool-bash'; fi\n").unwrap();+ fs::set_permissions(cli, fs::Permissions::from_mode(0o700)).unwrap();+ scanner.check_dsh_collaboration(cli).unwrap();+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([{"id":"llm-pi-ai","config":{"providers":{}}}]),+ );+ let AgentDiscoveryOutcomeV1::Supported { installation } =+ scanner.dsh_settings_discovery().outcome+ else {+ panic!("installed fixture")+ };+ assert!(installation.capability_evidence.iter().any(|p| p.capability+ == AgentCapability::SkillLoading+ && p.state == CapabilityState::Proven));+ for relative in [+ "cordis.patch.yml",+ "profiles/web/cordis.patch.yml",+ "profiles/acp/cordis.patch.yml",+ ] {+ let path = scanner.layout.dsh_config_root.join(relative);+ for module in [+ "skill-filesystem",+ "tool-skill",+ "tool-fs",+ "tool-bash",+ "skill",+ ] {+ write_patch(&path, json!([{"id":module,"disabled":true}]));+ assert!(+ scanner.check_dsh_collaboration(cli).is_err(),+ "{relative}: {module}"+ );+ }+ write_patch(+ &path,+ json!([{"id":"skill-filesystem","config":{"includeDefaultRoots":false}}]),+ );+ assert!(+ scanner.check_dsh_collaboration(cli).is_err(),+ "{relative}: standard user Skill root"+ );+ write_patch(+ &path,+ json!([{"id":"skill-filesystem","config":{"customSkillDirs":["/custom/skills"],"includeDefaultRoots":true}}]),+ );+ scanner.check_dsh_collaboration(cli).unwrap();+ fs::remove_file(path).unwrap();+ }+}++#[test]+fn dsh_static_import_is_secret_free_and_rejects_changed_credential_or_custom_auth() {+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let target = scanner.dsh_user_models_target();+ fs::create_dir_all(target.parent().unwrap()).unwrap();+ let patch = b"- id: llm-pi-ai\n config:\n providers:\n native-source:\n api: openai-responses\n baseURL: http://127.0.0.1:4222/v1\n apiKeyEnv: DSH_FIXTURE_KEY\n models: [{id: native-model, contextWindow: 16384, maxTokens: 4096, input: [text]}]\n";+ fs::write(&target, patch).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ for path in [+ target.parent().unwrap(),+ target.parent().unwrap().parent().unwrap(),+ ] {+ fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap();+ }+ fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap();+ }+ let credentials = scanner.layout.dsh_config_root.join(".credentials.yaml");+ write_secret_settings(+ &credentials,+ json!({"version":1,"refs":{"DSH_FIXTURE_KEY":"saved-token"}}),+ );+ let selected = scanner.dsh_api_sources().unwrap().remove(0);+ let public = serde_json::to_string(&selected).unwrap();+ assert!(!public.contains("saved-token") && !public.contains("127.0.0.1"));+ let (endpoint, secret) = scanner.read_dsh_api_source(&selected).unwrap();+ assert_eq!(endpoint.as_str(), "http://127.0.0.1:4222/v1");+ assert_eq!(secret.expose(), b"saved-token");+ write_secret_settings(+ &credentials,+ json!({"version":1,"refs":{"DSH_FIXTURE_KEY":"rotated"}}),+ );+ assert!(matches!(+ scanner.read_dsh_api_source(&selected),+ Err(AgentFilesystemScanError::SourceChanged)+ ));+ fs::write(+ &target,+ String::from_utf8(patch.to_vec()).unwrap().replace(+ " models:",+ " headers: {Authorization: custom}\n models:",+ ),+ )+ .unwrap();+ let selected = scanner.dsh_api_sources().unwrap().remove(0);+ assert!(!selected.supported_auth && selected.credential.is_none());+ assert!(scanner.read_dsh_api_source(&selected).is_err());+}++fn credentials_source(key: &str) -> serde_json::Value {+ json!({"id":"llm-pi-ai","config":{"providers":{"native":{+ "api":"openai-responses","baseURL":"https://credentials-source.invalid/v1",+ "apiKeyEnv":key,"models":[{"id":"explicit-model"}]+ }}}})+}++#[test]+fn dsh_credentials_use_the_effective_static_path_and_home_overrides() {+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let key = "HIROUTE_DSH_CREDENTIAL_PATH_TEST_KEY";+ assert!(std::env::var_os(key).is_none());+ let file = root.path().join("custom.yaml");+ let home = root.path().join("custom-home");+ for (path, token) in [+ (+ scanner.layout.dsh_config_root.join(".credentials.yaml"),+ "default",+ ),+ (file.clone(), "explicit-path"),+ (home.join(".credentials.yaml"), "explicit-home"),+ ] {+ write_secret_settings(&path, json!({"version":1,"refs":{key:token}}));+ }+ for (profile_config, home_config, expected) in [+ (json!({"path":file}), None, "explicit-path"),+ (json!({"dshHome":home}), None, "explicit-home"),+ (+ json!({"path":file}),+ Some(json!({"dshHome":home})),+ "explicit-home",+ ),+ (+ json!({"dshHome":home}),+ Some(json!({"path":file,"dshHome":home})),+ "explicit-path",+ ),+ (json!({"path":file}), Some(json!({})), "default"),+ ] {+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([+ credentials_source(key),+ {"id":"credentials","name":"@deepseek-ai/dsh-credentials-local","config":profile_config}+ ]),+ );+ write_patch(+ &scanner.layout.dsh_config_root.join("cordis.patch.yml"),+ home_config.map_or_else(+ || json!([]),+ |config| json!([{"id":"credentials","config":config}]),+ ),+ );+ let selected = scanner.dsh_api_sources().unwrap().remove(0);+ let public = serde_json::to_string(&selected).unwrap();+ assert!(!public.contains(file.to_str().unwrap()) && !public.contains("explicit-path"));+ assert_eq!(+ scanner.read_dsh_api_source(&selected).unwrap().1.expose(),+ expected.as_bytes()+ );+ }+}++#[test]+fn dsh_active_credentials_rotation_rejects_the_previous_import_selection() {+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let key = "HIROUTE_DSH_CREDENTIAL_ROTATION_TEST_KEY";+ assert!(std::env::var_os(key).is_none());+ let default = scanner.layout.dsh_config_root.join(".credentials.yaml");+ let active = root.path().join("active.yaml");+ for path in [&default, &active] {+ write_secret_settings(path, json!({"version":1,"refs":{key:"original"}}));+ }+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([credentials_source(key)]),+ );+ write_patch(+ &scanner.layout.dsh_config_root.join("cordis.patch.yml"),+ json!([{"id":"credentials","config":{"path":active}}]),+ );+ let selected = scanner.dsh_api_sources().unwrap().remove(0);+ write_secret_settings(&active, json!({"version":1,"refs":{key:"rotated"}}));+ assert!(matches!(+ scanner.read_dsh_api_source(&selected),+ Err(AgentFilesystemScanError::SourceChanged)+ ));+ let refreshed = scanner.dsh_api_sources().unwrap().remove(0);+ assert_eq!(+ scanner.read_dsh_api_source(&refreshed).unwrap().1.expose(),+ b"rotated"+ );+ write_secret_settings(&default, json!({"version":1,"refs":{key:"unused-default"}}));+ assert!(+ scanner.dsh_api_sources().unwrap().remove(0) == refreshed,+ "inactive default credentials must not change an effective-source selection"+ );+}++#[test]+fn dsh_disabled_removed_or_unknown_credentials_modules_block_import() {+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let key = "HIROUTE_DSH_CREDENTIAL_REJECTION_TEST_KEY";+ assert!(std::env::var_os(key).is_none());+ write_secret_settings(+ &scanner.layout.dsh_config_root.join(".credentials.yaml"),+ json!({"version":1,"refs":{key:"must-not-import"}}),+ );+ for module in [+ json!({"id":"credentials","disabled":true}),+ json!({"id":"credentials","remove":true}),+ json!({"id":"credentials","name":"custom-credential-helper"}),+ json!({"id":"credentials","config":{"path":"relative.yaml"}}),+ json!({"id":"credentials","config":{"dshHome":"~/unresolved-home"}}),+ json!({"id":"credentials","config":{"path":false}}),+ json!({"id":"credentials","config":{"unknownProvider":"custom"}}),+ json!({"insert":[{"id":"credentials","name":"custom-credential-helper"}]}),+ json!({"id":"other","insert":[{"id":"credentials","name":"custom-credential-helper"}]}),+ ] {+ for home_layer in [false, true] {+ let profile = if home_layer {+ json!([credentials_source(key)])+ } else {+ json!([credentials_source(key), module])+ };+ write_patch(&scanner.dsh_user_models_target(), profile);+ write_patch(+ &scanner.layout.dsh_config_root.join("cordis.patch.yml"),+ if home_layer {+ json!([module])+ } else {+ json!([])+ },+ );+ assert!(+ scanner.dsh_api_sources().is_err(),+ "unsupported credentials module was importable"+ );+ }+ }+}++#[cfg(unix)]+#[test]+fn dsh_effective_credentials_file_must_stay_private() {+ use std::os::unix::fs::PermissionsExt;+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let key = "HIROUTE_DSH_CREDENTIAL_PERMISSION_TEST_KEY";+ let active = root.path().join("active.yaml");+ for path in [+ &scanner.layout.dsh_config_root.join(".credentials.yaml"),+ &active,+ ] {+ write_secret_settings(path, json!({"version":1,"refs":{key:"private"}}));+ }+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([+ credentials_source(key), {"id":"credentials","config":{"path":active}}+ ]),+ );+ fs::set_permissions(&active, fs::Permissions::from_mode(0o644)).unwrap();+ assert!(matches!(+ scanner.dsh_api_sources(),+ Err(AgentFilesystemScanError::UnsafePermissions)+ ));+ fs::set_permissions(&active, fs::Permissions::from_mode(0o600)).unwrap();+ let selected = scanner.dsh_api_sources().unwrap().remove(0);+ scanner.read_dsh_api_source(&selected).unwrap();+}++#[test]+fn dsh_inherited_environment_precedes_the_selected_credentials_file() {+ let key = "HIROUTE_DSH_CREDENTIAL_ENVIRONMENT_TEST_KEY";+ if std::env::var_os(key).is_none() {+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "agents::filesystem::tests::dsh::dsh_inherited_environment_precedes_the_selected_credentials_file"])+ .env(key, "inherited-key").output().unwrap();+ assert!(output.status.success());+ assert!(+ String::from_utf8(output.stdout)+ .unwrap()+ .contains("test result: ok. 1 passed;")+ );+ return;+ }+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let active = root.path().join("active.yaml");+ write_secret_settings(&active, json!({"version":1,"refs":{key:"stored-key"}}));+ write_patch(+ &scanner.dsh_user_models_target(),+ json!([+ credentials_source(key), {"id":"credentials","config":{"path":active}}+ ]),+ );+ let selected = scanner.dsh_api_sources().unwrap().remove(0);+ assert_eq!(+ scanner.read_dsh_api_source(&selected).unwrap().1.expose(),+ b"inherited-key"+ );+}++#[cfg(unix)]+#[test]+fn dsh_admission_uses_required_public_modules_not_cli_version() {+ use std::os::unix::fs::PermissionsExt;+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let cli = &scanner.layout.dsh_executable;+ // Version is diagnostic; the public dump demonstrates capabilities without inference.+ fs::write(cli,"#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'DSH diagnostic-build'; else printf '%s\\n' '- id: llm-pi-ai' '- id: skill' '- id: skill-filesystem' '- id: tool-skill' '- id: tool-fs' '- id: tool-bash'; fi\n").unwrap();+ fs::set_permissions(cli, fs::Permissions::from_mode(0o700)).unwrap();+ scanner.check_dsh_model_configuration().unwrap();+ scanner.check_dsh_collaboration(cli).unwrap();+ fs::write(+ cli,+ "#!/bin/sh\nprintf '%s\\n' '- id: skill' '- id: skill-filesystem' '- id: tool-skill' '- id: tool-fs' '- id: tool-bash'\n",+ )+ .unwrap();+ assert!(scanner.check_dsh_model_configuration().is_err());+ // Model-provider capability is unnecessary for installing the collaboration Skill.+ scanner.check_dsh_collaboration(cli).unwrap();+ fs::write(cli, "#!/bin/sh\nprintf '%s\\n' '- id: llm-pi-ai'\n").unwrap();+ scanner.check_dsh_model_configuration().unwrap();+ assert!(scanner.check_dsh_collaboration(cli).is_err());+ let home = scanner.layout.dsh_config_root.join("cordis.patch.yml");+ fs::write(&home, b"- id: llm-pi-ai\n config: {providers: {}}\n").unwrap();+ fs::set_permissions(&home, fs::Permissions::from_mode(0o600)).unwrap();+ assert!(+ scanner.check_dsh_model_configuration().is_err(),+ "home layer must not shadow a managed Web provider"+ );+}++#[test]+fn dsh_home_default_guards_web_removal_without_requiring_cli() {+ let root = tempfile::tempdir().unwrap();+ let scanner = scanner(root.path());+ let home = scanner.layout.dsh_config_root.join("cordis.patch.yml");+ let namespace = "hiroute-main-test";+ let models = vec![hiroute_domain::AdditionalAgentModelV1 {+ alias: "route-a".into(),+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,+ context_window_tokens: 16384,+ max_output_tokens: 4096,+ }];+ let selected = hiroute_domain::additional_model_provider_for(namespace, &models, &models[0]);+ fs::write(+ &home,+ format!("- id: agent-default-model\n config: {{provider: {selected}, model: route-a}}\n"),+ )+ .unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(&home, fs::Permissions::from_mode(0o600)).unwrap();+ }+ assert!(scanner.dsh_web_default_in_use(namespace, &[]).unwrap());+ assert!(!scanner.dsh_web_default_in_use(namespace, &models).unwrap());+ assert!(+ !scanner+ .dsh_web_default_in_use("another-owner", &[])+ .unwrap()+ );+ fs::write(+ &home,+ b"- id: agent-default-model\n config: {provider: native, model: unchanged}\n",+ )+ .unwrap();+ assert!(!scanner.dsh_web_default_in_use(namespace, &[]).unwrap());+ fs::write(&home, b"- id: llm-pi-ai\n config: {providers: {}}\n").unwrap();+ assert!(scanner.dsh_web_default_in_use(namespace, &[]).is_err());+}diff --git a/crates/integrations/src/agents/mod.rs b/crates/integrations/src/agents/mod.rsindex 378e17d2..83f0019c 100644--- a/crates/integrations/src/agents/mod.rs+++ b/crates/integrations/src/agents/mod.rs@@ -29,10 +29,14 @@ mod native_ingress_probe;mod native_probe_process;#[cfg(unix)]pub use native_probe_process::NativeProbeProcess;+mod dsh_config;+mod dsh_sources;+#[cfg(test)]+mod dsh_tests;mod observed_capabilities;mod pi_runtime;mod pi_sources;-pub use pi_sources::PiApiSource;+pub use pi_sources::{NativeApiSource, PiApiSource};mod qoder;pub use pi_runtime::*;mod additional_native;diff --git a/crates/integrations/src/agents/pi_sources.rs b/crates/integrations/src/agents/pi_sources.rsindex 896c7c83..7fdba519 100644--- a/crates/integrations/src/agents/pi_sources.rs+++ b/crates/integrations/src/agents/pi_sources.rs@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet};use zeroize::{Zeroize, Zeroizing};#[derive(Clone, Eq, PartialEq, Serialize)]-pub struct PiApiSource {+pub struct NativeApiSource {pub provider_id: String,pub model_id: String,pub protocol: Option<UpstreamProtocol>,@@ -26,23 +26,25 @@ pub struct PiApiSource {pub credential: Option<DiscoveredCredentialRefV1>,pub supported_auth: bool,}+pub type PiApiSource = NativeApiSource;+type PiSourceSnapshot = (Vec<PiApiSource>,Option<(Zeroizing<String>, ProtectedSecret)>,);/// Raw provider values stay privileged and are cleared after each bounded scan.-struct Document(Value);+pub(super) struct Document(pub(super) Value);impl Drop for Document {fn drop(&mut self) {- fn clear(v: &mut Value) {- match v {- Value::String(s) => s.zeroize(),- Value::Array(a) => a.iter_mut().for_each(clear),- Value::Object(o) => o.values_mut().for_each(clear),- _ => {}- }- }- clear(&mut self.0);+ clear_native_value(&mut self.0);+ }+}+pub(super) fn clear_native_value(v: &mut Value) {+ match v {+ Value::String(s) => s.zeroize(),+ Value::Array(a) => a.iter_mut().for_each(clear_native_value),+ Value::Object(o) => o.values_mut().for_each(clear_native_value),+ _ => {}}}fn read(path: &std::path::Path) -> Result<(Document, CanonicalDigest), Error> {diff --git a/crates/integrations/src/agents/registry.rs b/crates/integrations/src/agents/registry.rsindex 22829072..8a6ac5be 100644--- a/crates/integrations/src/agents/registry.rs+++ b/crates/integrations/src/agents/registry.rs@@ -23,6 +23,7 @@ pub fn builtin_agent_profiles() -> Vec<AgentProfileV1> {claude_code_profile_v1(),qoder_collaboration_profile_v1(),pi_profile_v1(),+ dsh_profile_v1(),]}@@ -136,6 +137,27 @@ pub fn pi_profile_v1() -> AgentProfileV1 {}}+pub const DSH_PROFILE_ID_V1: &str = "dsh-responses-v1";+pub const DSH_INTEGRATION_PROFILE_REF_V1: &str = "builtin/dsh-responses/v1";++pub fn dsh_profile_v1() -> AgentProfileV1 {+ AgentProfileV1 {+ schema: AGENT_PROFILE_SCHEMA_V1.into(),+ profile_id: DSH_PROFILE_ID_V1.into(),+ integration_profile_ref: DSH_INTEGRATION_PROFILE_REF_V1.into(),+ kind: AgentKindV1::DeepseekHarness,+ legacy_exact_versions: BTreeSet::new(),+ ingress_protocol: Some(AgentIngressProtocolV1::Responses),+ config_precedence: AgentKindV1::DeepseekHarness.config_precedence().to_vec(),+ owned_config_fields: vec![field("additional_provider", "hiroute.additional_provider")],+ dynamic_catalog: false,+ static_catalog_fallback: false,+ native_subagent_routing: false,+ spawn_guidance: None,+ managed_launch: None,+ }+}+pub fn codex_spawn_agent_tool_v1() -> FunctionToolV1 {FunctionToolV1 {registration_id: "codex.builtin.spawn-agent.v1".to_owned(),diff --git a/crates/integrations/src/agents/tests.rs b/crates/integrations/src/agents/tests.rsindex b47b36ef..5bac7800 100644--- a/crates/integrations/src/agents/tests.rs+++ b/crates/integrations/src/agents/tests.rs@@ -21,7 +21,7 @@ fn observation(kind: AgentKindV1, version: &str) -> AgentScanObservationV1 {#[test]fn agents_registry_binds_codex_to_responses_and_claude_to_messages() {let profiles = builtin_agent_profiles();- assert_eq!(profiles.len(), 4);+ assert_eq!(profiles.len(), 5);for profile in &profiles {profile.validate().unwrap();}diff --git a/crates/local-storage/src/control/worker_dependencies.rs b/crates/local-storage/src/control/worker_dependencies.rsindex 98acfc52..4ae8a13e 100644--- a/crates/local-storage/src/control/worker_dependencies.rs+++ b/crates/local-storage/src/control/worker_dependencies.rs@@ -629,6 +629,7 @@ pub(super) const fn harness_key(harness: WorkerHarnessV1) -> &'static str {WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",WorkerHarnessV1::Pi => "pi",+ WorkerHarnessV1::DeepseekHarness => "deepseek_harness",}}@@ -638,6 +639,7 @@ fn parse_harness(value: &str) -> PortResult<WorkerHarnessV1> {"claude_code" => Ok(WorkerHarnessV1::ClaudeCode),"qoder_cli" => Ok(WorkerHarnessV1::QoderCli),"pi" => Ok(WorkerHarnessV1::Pi),+ "deepseek_harness" => Ok(WorkerHarnessV1::DeepseekHarness),_ => Err(port(PortErrorCode::Corrupt,"control.worker_dependency.harness",diff --git a/crates/local-storage/src/control/worker_dependencies_tests.rs b/crates/local-storage/src/control/worker_dependencies_tests.rsindex 981ac411..5980b383 100644--- a/crates/local-storage/src/control/worker_dependencies_tests.rs+++ b/crates/local-storage/src/control/worker_dependencies_tests.rs@@ -34,6 +34,7 @@ fn selection_operation(WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",WorkerHarnessV1::Pi => "pi",+ WorkerHarnessV1::DeepseekHarness => "deepseek_harness",};let expected_revisions = RevisionSetV1 {target: change.before_revision,diff --git a/crates/local-storage/src/migrations/mod.rs b/crates/local-storage/src/migrations/mod.rsindex c85bc134..a6372c24 100644--- a/crates/local-storage/src/migrations/mod.rs+++ b/crates/local-storage/src/migrations/mod.rs@@ -41,6 +41,7 @@ mod worker_dependencies_v24;#[cfg(test)]mod worker_dependencies_v24_tests;mod worker_dependencies_v26;+mod worker_dependencies_v27;mod worker_instance_v19;#[cfg(test)]@@ -49,7 +50,7 @@ mod convergence_tests;/// Current stable storage format, including native ACP Worker dependency selections./// Production source admission is defined in `startup_format`; supported upgrades retain the/// existing durable three-store backup and recovery coordinator.-pub const LATEST_SCHEMA_VERSION: u32 = 26;+pub const LATEST_SCHEMA_VERSION: u32 = 27;#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub enum DatabaseKind {@@ -840,7 +841,8 @@ fn migration_sql(kind: DatabaseKind, version: u32) -> Result<&'static str, Local(DatabaseKind::Control, 25) => Ok(agent_surface_checks_v25::CONTROL),(DatabaseKind::Runtime | DatabaseKind::Secrets, 25) => Ok(NOOP_V9),(DatabaseKind::Control, 26) => Ok(worker_dependencies_v26::CONTROL),- (DatabaseKind::Runtime | DatabaseKind::Secrets, 26) => Ok(NOOP_V9),+ (DatabaseKind::Control, 27) => Ok(worker_dependencies_v27::CONTROL),+ (DatabaseKind::Runtime | DatabaseKind::Secrets, 26 | 27) => Ok(NOOP_V9),_ => Err(LocalStorageError::InvalidData),}}diff --git a/crates/local-storage/src/migrations/startup_format.rs b/crates/local-storage/src/migrations/startup_format.rsindex 56587ca3..3e290043 100644--- a/crates/local-storage/src/migrations/startup_format.rs+++ b/crates/local-storage/src/migrations/startup_format.rs@@ -36,7 +36,7 @@ pub(crate) fn validate_startup_format(root: &Path) -> Result<(), LocalStorageErr// Schema 23 is the first stable format; 24 preserves that same marker.// A mixed supported live set is only a candidate for the existing coordinator:// it must still prove its complete source backup, store identities, key and phase.- if !matches!(version, 23 | 24 | 25 | LATEST_SCHEMA_VERSION) {+ if !matches!(version, 23 | 24 | 25 | 26 | LATEST_SCHEMA_VERSION) {return Err(LocalStorageError::UpgradeSourceUnsupported);}let marker = connection.query_row(diff --git a/crates/local-storage/src/migrations/worker_dependencies_v27.rs b/crates/local-storage/src/migrations/worker_dependencies_v27.rsnew file mode 100644index 00000000..7c601367--- /dev/null+++ b/crates/local-storage/src/migrations/worker_dependencies_v27.rs@@ -0,0 +1,108 @@+//! Extend Native DSH Worker installation support without decoding or reserializing stored journals.++pub(super) const CONTROL: &str = r#"+CREATE TABLE worker_dependency_selections_v27 (+ workspace_id TEXT NOT NULL,+ harness TEXT NOT NULL CHECK(harness IN ('codex_cli','claude_code','qoder_cli','pi','deepseek_harness')),+ revision INTEGER NOT NULL+ CHECK(typeof(revision) = 'integer' AND revision > 0),+ selection_json TEXT NOT NULL,+ owner_operation_id TEXT NOT NULL REFERENCES operations(operation_id),+ updated_at INTEGER NOT NULL,+ PRIMARY KEY(workspace_id, harness)+);++CREATE TABLE worker_dependency_selection_effects_v27 (+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id) ON DELETE CASCADE,+ workspace_id TEXT NOT NULL,+ harness TEXT NOT NULL CHECK(harness IN ('codex_cli','claude_code','qoder_cli','pi','deepseek_harness')),+ before_revision INTEGER NOT NULL+ CHECK(typeof(before_revision) = 'integer' AND before_revision >= 0),+ before_json TEXT,+ before_owner_operation_id TEXT,+ after_revision INTEGER NOT NULL+ CHECK(typeof(after_revision) = 'integer' AND after_revision > 0),+ after_json TEXT NOT NULL,+ activated INTEGER NOT NULL DEFAULT 0 CHECK(activated IN (0,1)),+ compensated INTEGER NOT NULL DEFAULT 0 CHECK(compensated IN (0,1)),+ UNIQUE(workspace_id, harness, after_revision)+);++INSERT INTO worker_dependency_selections_v27+ SELECT workspace_id, harness, revision, selection_json, owner_operation_id, updated_at+ FROM worker_dependency_selections;+INSERT INTO worker_dependency_selection_effects_v27+ SELECT operation_id, workspace_id, harness, before_revision, before_json,+ before_owner_operation_id, after_revision, after_json, activated, compensated+ FROM worker_dependency_selection_effects;++DROP TABLE worker_dependency_selection_effects;+DROP TABLE worker_dependency_selections;+ALTER TABLE worker_dependency_selections_v27 RENAME TO worker_dependency_selections;+ALTER TABLE worker_dependency_selection_effects_v27 RENAME TO worker_dependency_selection_effects;+CREATE INDEX worker_dependency_selection_effects_state+ ON worker_dependency_selection_effects(activated, compensated, operation_id);+"#;++#[cfg(test)]+mod tests {+ use super::super::*;+ #[test]+ fn dsh_upgrade_preserves_existing_selection_and_effect_bytes() {+ let connection = Connection::open_in_memory().unwrap();+ for version in 1..=26 {+ connection+ .execute_batch(migration_sql(DatabaseKind::Control, version).unwrap())+ .unwrap();+ }+ let before = " { \"historical\" : [ 1, 2 ] }\n";+ let after = "{\"opaque\":true, \"ordering\" : 42}\n";+ connection+ .pragma_update(None, "foreign_keys", true)+ .unwrap();+ // This SQL migration fixture needs real parent rows. Native journal replay is+ // covered by the frozen schema-23 product fixtures, not these opaque payloads.+ for owner in [+ "operation-codex_cli",+ "operation-claude_code",+ "operation-qoder_cli",+ "operation-pi",+ "new-owner",+ ] {+ connection.execute(+ "INSERT INTO operations VALUES (?1,'personal/default','fixture-owner','worker_dependency_selection',?1,'request','accepted','succeeded',1,'{}',123,123)",+ [owner],+ ).unwrap();+ }+ for harness in ["codex_cli", "claude_code", "qoder_cli", "pi"] {+ connection.execute("INSERT INTO worker_dependency_selections VALUES ('personal/default',?1,7,?2,?3,123)",params![harness,after,format!("operation-{harness}")]).unwrap();+ connection.execute("INSERT INTO worker_dependency_selection_effects VALUES (?1,'personal/default',?2,6,?3,'previous-owner',7,?4,1,0)",params![format!("operation-{harness}"),harness,before,after]).unwrap();+ }+ connection.execute_batch(super::CONTROL).unwrap();+ let selections: Vec<(String, String)> = connection+ .prepare(+ "SELECT harness,selection_json FROM worker_dependency_selections ORDER BY harness",+ )+ .unwrap()+ .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))+ .unwrap()+ .map(Result::unwrap)+ .collect();+ assert_eq!(selections.len(), 4);+ assert!(selections.iter().all(|(_, raw)| raw == after));+ let effects:Vec<(String,String,i64,i64)> = connection.prepare("SELECT before_json,after_json,activated,compensated FROM worker_dependency_selection_effects").unwrap().query_map([],|r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).unwrap().map(Result::unwrap).collect();+ assert_eq!(effects, vec![(before.into(), after.into(), 1, 0); 4]);+ connection.execute("INSERT INTO worker_dependency_selections VALUES ('personal/default','deepseek_harness',1,'{}','new-owner',124)",[]).unwrap();+ assert!(connection.execute("INSERT INTO worker_dependency_selections VALUES ('personal/default','unknown',1,'{}','new-owner',124)",[]).is_err());+ assert!(+ connection+ .prepare("PRAGMA foreign_key_check")+ .unwrap()+ .query([])+ .unwrap()+ .next()+ .unwrap()+ .is_none()+ );+ }+}diff --git a/docs/code-map/README.md b/docs/code-map/README.mdindex a24bae6b..efce9a26 100644--- a/docs/code-map/README.md+++ b/docs/code-map/README.md@@ -10,7 +10,7 @@ ownership or entry points change.| Add model sources and inspect usable models | Model connections | [Application](../../crates/application/src/compute_management), [native integrations](../../crates/integrations/src/model_connections), [daemon assembly](../../crates/daemon/src/control/runtime/model_connections.rs) | [Typed/fixture contracts](../../tools/product-e2e/tests/compute_pool.rs); [installed CLI journey](../../crates/daemon/tests/publication_process.rs) || Create and publish a routing plan | Routing plans | [Authoring and lifecycle](../../crates/application/src/routing), [compiler](../../crates/application/src/compiler), [domain types](../../crates/domain/src/routing) | [Compiler/fixture contracts](../../tools/product-e2e/tests/routing_plans.rs); [installed CLI journey](../../crates/daemon/tests/publication_process.rs) || Connect, edit and safely disable an Agent | Agent connections | [Application transaction](../../crates/application/src/agent_connection), [filesystem adapters](../../crates/integrations/src/agents), [Desktop feature](../../apps/desktop/src/features/agents/README.md) | [Settings ordering](../../crates/application/src/operations/tests/settings_tail.rs), [daemon product entry](../../crates/daemon/src/control/runtime/settings_profile_tests.rs) |-| Select saved additional Qoder/Pi model routes while keeping task collaboration independent | Agent connections | [Shared settings transaction](../../crates/application/src/agent_connection/settings), [native provider ownership](../../crates/integrations/src/agents/additional_native/README.md), [Desktop model editor](../../apps/desktop/src/features/agents/AdditionalModelEditor.tsx) | [Shared native journeys](../../crates/daemon/tests/support/additional_model_product.py), [Qoder](../../tools/product-e2e/tests/QODER_DELEGATION.md) and [Pi](../../tools/product-e2e/tests/PI_INTEGRATION.md) entry and limits |+| Select saved additional Qoder/Pi/DSH model routes while keeping task collaboration independent | Agent connections | [Shared settings transaction](../../crates/application/src/agent_connection/settings), [native provider ownership](../../crates/integrations/src/agents/additional_native/README.md), [Desktop model editor](../../apps/desktop/src/features/agents/AdditionalModelEditor.tsx) | [Shared native journeys](../../crates/daemon/tests/support/additional_model_product.py), [Qoder](../../tools/product-e2e/tests/QODER_DELEGATION.md) and [Pi](../../tools/product-e2e/tests/PI_INTEGRATION.md) entry and limits || Route a model request and apply bounded fallback | Request routing | [Gateway map](../../crates/gateway/README.md), [execution core](../../crates/gateway-core/src) | [Real listener scenarios](../../tools/e2e-harness/tests/p0_gateway_runtime.rs) || Ask an external service to select a branch | [Decision API](../../decision-extensions/api/README.md) | [Gateway classification](../../crates/gateway/src/core_runtime/classification.rs), [Jev reference service](../../decision-extensions/extensions/jev-decider/README.md) | [Jev tests](../../decision-extensions/extensions/jev-decider), real listener classifier scenarios above || Delegate, read and continue Worker tasks | Agent delegation | [Application authorization](../../crates/application/src/delegation), [daemon execution](../../crates/daemon/src/delegation), [OS launcher](../../crates/daemon/src/delegation/local_worker/README.md) | [Worker lifecycle](../../tools/product-e2e/tests/worker_delegation.rs), [read/continue](../../tools/product-e2e/tests/worker_read.rs) |@@ -21,6 +21,7 @@ Read [architecture and ownership](architecture.md) for cross-module changes,[tests as product documentation](testing.md) before changing coverage, and[remaining cleanup work](maintenance.md) before starting another refactor.For later decision features, read the [provider and consumer boundaries](decision-foundation.md).+For DeepSeek Harness, start with [the DSH boundary map](dsh.md).Before extending Worker ecosystems, read the [native context, route and history owners](worker-context.md).Pi static API discovery is owned by [the bounded native reader](../../crates/integrations/src/agents/pi_sources.rs)diff --git a/docs/code-map/dsh.md b/docs/code-map/dsh.mdnew file mode 100644index 00000000..1d10c615--- /dev/null+++ b/docs/code-map/dsh.md@@ -0,0 +1,91 @@+# DeepSeek Harness boundaries++[Code map](README.md) · [Worker context](worker-context.md)++DSH uses its official CLI and native ACP. HiRoute does not import a DSH SDK,+inspect npm package layout, or decode native history. An acceptance release is a+reproducibility input, never a production version allowlist.++| User capability | Owner | Required boundary |+| --- | --- | --- |+| Import existing explicit API sources | [Passive source reader](../../crates/integrations/src/agents/dsh_sources.rs), [shared candidate prepare](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Static public provider/model declarations, supported protocol and safe API-key reference. No OAuth, dynamic composition, credential helper or model call during discovery. Public output excludes endpoints and secrets; changed source evidence blocks Save. |+| Add model routes | [Native admission](../../crates/integrations/src/agents/dsh_native.rs), [YAML leaf](../../crates/integrations/src/agents/dsh_config.rs), [shared provider engine](../../crates/integrations/src/agents/additional_native/README.md) | Standard `profiles/web/cordis.patch.yml`; one provider per Plan with explicit Responses/Messages choice. Preserve native defaults and foreign configuration. Reject global `llm-pi-ai` shadowing. Restore stays in the shared conditional transaction. |+| Enable task routing | [Native local checks](../../crates/integrations/src/agents/dsh_native.rs), [shared settings](../../crates/application/src/agent_connection/settings.rs) | Actual Skill registry/loader, enabled read/bash modules, standard Skill roots and selected HiRoute CLI; check relevant home/Web/ACP resource overrides independently of model configuration. No model runtime/session prerequisite, additional validation button or automatic paid inference. |+| Execute a Worker | [Public patch renderer](../../crates/daemon/src/delegation/profile/dsh.rs), [ACP](../../crates/daemon/src/delegation/acp/mod.rs) | Selected native CLI, ACP initialize/new, explicit model option and finite prompt/cancel. Freeze route, budgets and per-run credential; keep resource HOME/DSH_HOME and custom Skill roots. Own task history, attachments and run patch separately. Disable auxiliary providers, telemetry and background shell promotion. |+| Continue | [Shared exact binding](../../crates/daemon/src/delegation/profile/native_history.rs), [ACP resume](../../crates/daemon/src/delegation/acp/mod.rs) | Require advertised `session/resume`, identical native/ACP session ID and frozen cwd/context/route. Native DSH interprets its history and must refuse missing or unusable state. Never replace the conversation with `session/new`. |++DSH composition layers replace whole module configurations. Model edits therefore+manage the standard Web profile only and reject an overriding home provider row.+The independent home default is also checked at planning, staging and activation;+removing its selected HiRoute model is blocked. Restore needs these static checks,+but remains available when the CLI is removed or no longer compatible.+Shared recovery copy directs the user to the selected client's model selector;+it must not assume Pi's `/model` command for DSH Web. The+[additional-route browser scenarios](../../apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs)+reuse one fixture for this default-reference recovery; native persistence remains+covered by the real additional-model journey.+Worker launch supplies a final run-owned patch through public `--patch`; it leaves+the borrowed home/profile files untouched. JSON is used only as a public YAML+subset for generated patches. The bounded static reader accepts block/flow YAML+and JSON, while edits require a block sequence to preserve unrelated row bytes.+Executable tags, includes, merge keys and ambiguous rows are refused. Edit spans+are checked against semantic rows; a dash inside a multiline string cannot become+an owned patch row.++Passive discovery checks both the home and Web files; a home `llm-pi-ai` row+replaces the Web module, rather than merging providers. It imports only explicit+nonempty model declarations, not catalog-only providers or placeholder model IDs.+API-key environment values precede the private version-1 credentials refs. Resolve+the standard credentials module before reading a store: Web config precedes home+config, and each supplied config replaces the earlier object. Static absolute+`path` wins over `dshHome/.credentials.yaml`, then the selected DSH root's default.+Disabled/removed modules, replacement plugins, unsupported composition operations+and relative/tilde paths are refused; do not borrow HiRoute's cwd or HOME to guess.+Only the effective file needs private-file validation. Source+evidence binds home/profile bytes, the effective credential path/bytes and the selected environment secret;+Prepare and Save recheck that evidence without executing helpers or inference.+The shared [Desktop scan flow](../../apps/desktop/src/product/ModelManagementPage.tsx)+maps both bare and application-qualified stale/revision-conflict errors to the+existing rescan action. It discards the old candidate, then prepares and saves the+fresh scan; cover that recovery in the shared subscription-repair browser journey.+Provider/model compatibility options and custom authentication that cannot be+preserved remain ineligible. Only a nonempty explicit model `input` establishes+vision support; empty/missing input stays Unknown because native catalog/default+inheritance is outside this passive contract.+Run credentials stay in the environment via `apiKeyEnv`. For Messages, the+[Gateway ingress](../../crates/gateway/src/core_runtime/inbound_auth_tests.rs)+accepts the native `x-api-key` carrier only for a run-model token on `/v1/messages`;+the existing run authority still verifies the live run and frozen protocol.+Native account keys, model grants and control-run tokens cannot use this carrier.++The production capability checks use the CLI's public composition dump in a+private temporary DSH root, without activating model plugins. CLI version is+recorded for diagnosis. Module presence establishes only a local prerequisite;+actual ACP/model/history behavior is guarded on the operation that uses it.+Borrowed resource overrides cannot disable the required Skill/read/bash modules,+turn off standard Skill roots or substitute a different `dshHome`. Additional+custom Skill directories remain native-owned. The collaboration proof binds only+these resource configurations, so unrelated model-provider edits do not revoke it.+Custom plugins and unknown provider protocols need an explicit integration+contract; a successful local dump is not a claim that every custom composition+or future release works. No cross-version task migration or Continue guarantee+is made.++Start validation from [DSH product entry](../../tools/product-e2e/tests/dsh_delegation.rs)+and [run guide](../../tools/product-e2e/tests/DSH_INTEGRATION.md). The native context,+concurrency/cancellation, additional-model and main-Agent journeys are shared with+other ecosystems; [DSH fixture facts](../../crates/daemon/tests/support/dsh_native_context.py)+add public composition and opaque synthetic-history witnesses only.+[Native ACP fixture client](../../crates/daemon/tests/support/native_acp_client.py)+is a test consumer, not a production adapter. Required positive outcomes include+upstream request counts and protocol, independent tool artifacts, preserved user+files, exact Continue and real public CLI delegation. Fixture rejection or process+exit alone does not establish product completion.+The static-import journey reuses the common Scan → Prepare → Save → restart →+native-call oracle with a different valid default credential as a decoy. Select+`HIROUTE_PRODUCT_DSH_CREDENTIAL_SOURCE=path` or `dsh-home` to exercise either+override; rotation of the active store must reject the previous Save preview.++Public references: [CLI](https://github.com/deepseek-ai/deepseek-harness/blob/master/apps/cli/reference/README.md),+[providers](https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/user/guide/providers.md),+[ACP](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/acp/acp/README.md).diff --git a/docs/code-map/testing.md b/docs/code-map/testing.mdindex 520c78de..bc2f1849 100644--- a/docs/code-map/testing.md+++ b/docs/code-map/testing.md@@ -27,6 +27,9 @@ Its protected-input/grant channel belongs to the daemon that the fixture starts;it cannot be attached to an already running Desktop. Prepare sources before handingthat instance to Desktop, then perform protected user mutations through the real UI.Native main-Agent delegation separately invokes the actual public Worker CLI.+`Product` leases its listener address outside the host's outbound ephemeral range+until fixture cleanup, including daemon restarts. Keep this shared ownership rule;+a closed `bind(0)` probe can be claimed by concurrent clients before startup.Start from the representative cases in the [capability map](README.md). In`tools/product-e2e`, inspect the declared proof level: `transaction_recovery.rs`diff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.mdindex 5b525b19..903cac80 100644--- a/docs/code-map/worker-context.md+++ b/docs/code-map/worker-context.md@@ -5,7 +5,7 @@A delegated task uses the product instance's effective native user context to findskills, while HiRoute controls the frozen Plan, per-run credential and permissionpolicy. A task owns its HiRoute metadata; the native client owns borrowed user-configuration and borrowed history; Pi owns its task transcript separately. This page locates those responsibilities. Executable tests define the boundaries described here; validation reports must+configuration and borrowed history; Pi and DSH own task history separately. This page locates those responsibilities. Executable tests define the boundaries described here; validation reports mustrecord their exact revision, environment and scenario outcomes.@@ -16,6 +16,7 @@ record their exact revision, environment and scenario outcomes.| Codex | Effective HOME/CODEX_HOME and project Skills | Selected ACP adapter | Borrowed native history, exact session identity || Claude Code | Effective HOME/CLAUDE_CONFIG_DIR and project Skills | Selected ACP adapter | Borrowed native history, exact session identity || Qoder | Effective HOME/QODER_CONFIG_DIR and project Skills | Selected native ACP | Borrowed native history, exact session identity |+| DSH | Effective HOME/DSH_HOME, project and custom Skill roots | Selected native ACP | Task-owned native history; opaque native session ID restored with ACP `session/resume` || Pi | Effective HOME/PI_CODING_AGENT_DIR, project and already installed package Skills | Bundled SDK→ACP bridge bound to selected npm CLI and Node | Task-owned `native-pi.jsonl`; strict body and context validation before load |The resource root is never replaced with the task root. Pi deliberately uses an@@ -41,6 +42,10 @@ The shared boundary journey retains total model POST counts, concurrent nativechildren, exact Continue and neighbor preservation; missing/corrupt history mustproduce zero model calls without repair or replacement.+DSH reuses these lifecycle and product-journey owners. Its public composition and+ACP resume differences are mapped in [DSH boundaries](dsh.md); the daemon does not+read its native session format or use an internal SDK.+## Pi compatibility is a capability contractThe acceptance fixture pins a reproducible release; production never compares a@@ -87,13 +92,13 @@ only the native leaf and capability regression when the startup protocol differs| Product question | Read this owner | Boundary to preserve || --- | --- | --- |-| How does Desktop confirm a Worker installation? | [React selection](../../apps/desktop/src/features/WorkerDependencies.tsx), [native preparation and confirmation](../../apps/desktop/src-tauri/src/bridge/worker_tasks.rs), [protected submission and recovery](../../apps/desktop/src-tauri/src/session/worker_dependencies.rs) | Native preparation validates the shared launch shape and canonical file metadata before freezing the selection in a window-bound, expiring, single-use confirmation. Qoder contains only a CLI; Pi selects its official npm CLI plus Node for the bundled SDK bridge; Codex/Claude retain their adapter requirements. The confirmed canonical request feeds the shared digest and revision plan; discovery is not authority. |+| How does Desktop confirm a Worker installation? | [React selection](../../apps/desktop/src/features/WorkerDependencies.tsx), [native preparation and confirmation](../../apps/desktop/src-tauri/src/bridge/worker_tasks.rs), [protected submission and recovery](../../apps/desktop/src-tauri/src/session/worker_dependencies.rs) | Native preparation validates the shared launch shape and canonical file metadata before freezing the selection in a window-bound, expiring, single-use confirmation. Qoder and DSH contain only a CLI; Pi selects its official npm CLI plus Node for the bundled SDK bridge; Codex/Claude retain their adapter requirements. The confirmed canonical request feeds the shared digest and revision plan; discovery is not authority. || Why does a selected CLI survive restart and upgrade? | [Validated launch form](../../crates/domain/src/delegation/installation.rs), [selection storage](../../crates/local-storage/src/control/worker_dependencies.rs), [Qoder upgrade](../../crates/local-storage/src/migrations/worker_dependencies_v24.rs), [Pi upgrade](../../crates/local-storage/src/migrations/worker_dependencies_v26.rs) | Harness chooses native ACP, adapter ACP or the selected native SDK bridge. Preserve previous selection and Operation bytes during migration; resume interrupted upgrades only through the existing complete three-store backup coordinator. || Where does an Agent learn the valid installation and Plan request shape? | [Worker schema producer](../../crates/application-api/src/generated/worker.rs), [Plan schema producer](../../crates/application-api/src/generated/plan_authoring.rs), [generator](../../crates/cli/src/bin/generate_cli_contract.rs), [published schemas](../../contracts/cli) | The Rust `generated/` directory contains producer source; `contracts/cli` contains its output. Update both request families when adding a harness. Generate twice, retain old adapter requirements and native-only forbidden fields, then run the [exact artifact gate](../../crates/cli/tests/contracts.rs). || Did a Worker submission reach the daemon? | [CLI submission](../../crates/cli/src/worker.rs), [local submission receipts](../../crates/cli/src/worker/receipt.rs), [daemon task admission](../../crates/daemon/src/control/runtime/delegation_tasks.rs) | The CLI rejects a reused submission key with different selectors or intent before transport. A local receipt conflict is distinct from daemon admission. Product fixtures borrowing native HOME must still give HiRoute receipts their own directory, stable for replay within one scenario and separate between scenarios. || How does a main Agent prove it can use task routing? | [Native local checks](../../apps/desktop/src-tauri/src/agent_check_session.rs), [shared main-Agent journey](../../crates/daemon/tests/support/collaboration_product.py), [Qoder](../../tools/product-e2e/tests/QODER_DELEGATION.md) and [Pi](../../tools/product-e2e/tests/PI_INTEGRATION.md) run contracts | A local capability check does not prove the installed user Skill or actual delegation. The real main Agent must read the installed Skill, use public plans/exec/wait/result and produce an independently witnessed Worker artifact. Local checks do not add a separate settings-page verification step. Borrowed HOME is not an isolation claim. |-| Which user resources does this Worker see? | [Installation](../../crates/daemon/src/delegation/installation.rs), [native context](../../crates/daemon/src/delegation/profile/native_context.rs) | New tasks use effective HOME plus explicit CODEX_HOME, CLAUDE_CONFIG_DIR , QODER_CONFIG_DIR or PI_CODING_AGENT_DIR. Pilot/service overrides are authoritative; executable location does not identify a different user's home. |-| Which endpoint, model and credential can it use? | [Profile guide](../../crates/daemon/src/delegation/profile/README.md), [Codex](../../crates/daemon/src/delegation/profile/codex.rs), [Claude](../../crates/daemon/src/delegation/profile/claude.rs), [Qoder](../../crates/daemon/src/delegation/profile/qoder.rs), [Pi](../../crates/daemon/src/delegation/profile/pi.rs) | Apply native startup/session overrides without editing shared settings. Credentials stay transient. Qoder's shared native settings renderer lives in integrations; Gateway retains the frozen Plan's upstream reasoning authority. |+| Which user resources does this Worker see? | [Installation](../../crates/daemon/src/delegation/installation.rs), [native context](../../crates/daemon/src/delegation/profile/native_context.rs) | New tasks use effective HOME plus explicit CODEX_HOME, CLAUDE_CONFIG_DIR , QODER_CONFIG_DIR PI_CODING_AGENT_DIR or DSH_HOME. Pilot/service overrides are authoritative; executable location does not identify a different user's home. |+| Which endpoint, model and credential can it use? | [Profile guide](../../crates/daemon/src/delegation/profile/README.md), [Codex](../../crates/daemon/src/delegation/profile/codex.rs), [Claude](../../crates/daemon/src/delegation/profile/claude.rs), [Qoder](../../crates/daemon/src/delegation/profile/qoder.rs), [Pi](../../crates/daemon/src/delegation/profile/pi.rs), [DSH](../../crates/daemon/src/delegation/profile/dsh.rs) | Apply native startup/session overrides without editing shared settings. Credentials stay transient. Qoder's shared native settings renderer lives in integrations; Gateway retains the frozen Plan's upstream reasoning authority. DSH uses a final public patch and task-owned native history, resumed only by its native ACP session ID. || Can the native client use the frozen Plan's context and output budget? | [Qoder Plan projection](../../crates/integrations/src/agents/qoder_budget.rs), [shared budget policy](../../crates/domain/src/agents/additional_model.rs), [shared native renderer](../../crates/integrations/src/agents/qoder.rs), [budget contract and limits](../../crates/daemon/src/delegation/profile/README.md) | Project both context and output from the frozen Plan into native model metadata. Reject unknown or unusable budgets before launch. Gateway output capping alone cannot prove the native client's compaction reservation; preserve the small-window real-Agent journey and version-specific native control. || Who admits its requests and attributes them to the right Worker? | [Run authority](../../crates/daemon/src/delegation/run_authority.rs), [Gateway admission and observation metadata](../../crates/gateway/src/dispatch/run.rs) | Profile construction alone cannot admit a request. The sealed Plan and run must agree on the typed harness, and the Gateway must accept its current observation identity while rejecting unknown values. Check both consumers when adding an ecosystem. || Has the native session accepted the planned model? | [ACP model confirmation](../../crates/daemon/src/delegation/acp/model.rs) | New and restored sessions confirm the profile's exact native model ID before prompt. Qoder adds its native provider prefix only here; the Plan alias stays unchanged. Missing or ambiguous capability fails explicitly. |diff --git a/docs/github-actions-validation.md b/docs/github-actions-validation.mdindex afbd8e67..869191c6 100644--- a/docs/github-actions-validation.md+++ b/docs/github-actions-validation.md@@ -35,7 +35,13 @@ their tests or documentation keep the ordinary tooling-only selection.The toolchain comes from `rust-toolchain.toml`. Cargo sources are cached, not`target/`; shards do not exchange compiled binaries or claim another runner's build-evidence. Build concurrency defaults to the runner CPU count; incremental compilation is+evidence. The shared Rust setup exports `CARGO_NET_GIT_FETCH_WITH_CLI=true` for+subsequent job steps, so pinned Git dependencies use the installed Git client+instead of Cargo's embedded libgit2 transport. This avoids the libgit2 SSL failure+observed when fetching Pingora on a cold hosted runner; TLS verification and locked+dependency revisions remain enforced. Fetch failures still fail the job, and the+setup does not retry test commands.+Build concurrency defaults to the runner CPU count; incremental compilation isdisabled. Every job keeps its own checkout-local Cargo output. The hosted job isdisposable, so there is no persistent worktree cleanup service.diff --git a/scripts/check-contract-convergence.py b/scripts/check-contract-convergence.pyindex 284736cc..bb892e81 100755--- a/scripts/check-contract-convergence.py+++ b/scripts/check-contract-convergence.py@@ -14,7 +14,7 @@ REGISTRY_PATH = Path("contracts/compatibility-support.v1.json")# must deliberately update this gate after reviewing migrations/startup_format.rs and# docs/upgrade-storage-design.md; fixtures cannot satisfy it. This is not a migration test.DATABASE_SCHEMA_SOURCE = "crates/local-storage/src/migrations/mod.rs"-EXPECTED_DATABASE_SCHEMA_VERSION = 26+EXPECTED_DATABASE_SCHEMA_VERSION = 27VERSION_SUFFIX = re.compile(r"/v[0-9]+")INTERNAL_CONTRACT = re.compile(r"hiroute(?:\.[a-z0-9][a-z0-9-]*)+/v[0-9]+")VALID_MODES = {diff --git a/scripts/ci-shards.py b/scripts/ci-shards.pyindex 1e22077a..61a08410 100755--- a/scripts/ci-shards.py+++ b/scripts/ci-shards.py@@ -80,6 +80,7 @@ INTEGRATION_SHARDS = {("hiroute-product-e2e", "compute_pool"),("hiroute-product-e2e", "control_shell"),("hiroute-product-e2e", "cpa_connector"),+ ("hiroute-product-e2e", "dsh_delegation"),("hiroute-product-e2e", "gateway_adapter_contract"),("hiroute-product-e2e", "local_observation"),("hiroute-product-e2e", "pi_delegation"),diff --git a/scripts/desktop-pilot.py b/scripts/desktop-pilot.pyindex fa909562..90f90d5c 100755--- a/scripts/desktop-pilot.py+++ b/scripts/desktop-pilot.py@@ -124,6 +124,7 @@ def launch_environment(environment["CLAUDE_CONFIG_DIR"] = str(process_home / ".claude")environment["QODER_CONFIG_DIR"] = str(process_home / ".qoder")environment["PI_CODING_AGENT_DIR"] = str(process_home / ".pi/agent")+ environment["DSH_HOME"] = str(process_home / ".dsh")if diagnostic_override is not None:environment[DIAGNOSTIC_LEVEL_ENV] = diagnostic_overridereturn environmentdiff --git a/scripts/test-contract-convergence.py b/scripts/test-contract-convergence.pyindex a0a57d9e..fefaea57 100755--- a/scripts/test-contract-convergence.py+++ b/scripts/test-contract-convergence.py@@ -47,7 +47,7 @@ class ContractConvergenceTests(unittest.TestCase):'"hiroute.sample/v2"'),"crates/local-storage/src/migrations/mod.rs": (- "pub const LATEST_SCHEMA_VERSION: u32 = 26;\n"+ "pub const LATEST_SCHEMA_VERSION: u32 = 27;\n"),# Historical/test text must never stand in for the production declaration."tests/old_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 17;",@@ -60,34 +60,34 @@ class ContractConvergenceTests(unittest.TestCase):return MODULE.audit(root, value or registry(), files)def test_database_schema_change_is_not_hidden_by_a_fixture(self):- for version in (17, 22, 23, 24, 25, 27):+ for version in (17, 22, 23, 24, 25, 26, 28):with self.subTest(version=version):errors = self.run_audit({"legacy.rs": '"hiroute.sample/v1"',"crates/local-storage/src/migrations/mod.rs": (f"pub const LATEST_SCHEMA_VERSION: u32 = {version};\n"),- "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 26;",+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 27;",})self.assertTrue(any("database schema" in error for error in errors), errors)def test_database_schema_requires_the_authoritative_production_declaration(self):for source in ("// declaration removed\n",- "#[cfg(test)]\nmod fixture {\n pub const LATEST_SCHEMA_VERSION: u32 = 26;\n}\n",- "/*\npub const LATEST_SCHEMA_VERSION: u32 = 26;\n*/\n",- "pub const LATEST_SCHEMA_VERSION: u32 = 26;\npub const LATEST_SCHEMA_VERSION: u32 = 27;\n",+ "#[cfg(test)]\nmod fixture {\n pub const LATEST_SCHEMA_VERSION: u32 = 27;\n}\n",+ "/*\npub const LATEST_SCHEMA_VERSION: u32 = 27;\n*/\n",+ "pub const LATEST_SCHEMA_VERSION: u32 = 27;\npub const LATEST_SCHEMA_VERSION: u32 = 27;\n",):with self.subTest(source=source):errors = self.run_audit({"legacy.rs": '"hiroute.sample/v1"',"crates/local-storage/src/migrations/mod.rs": source,- "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 26;",+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 27;",})self.assertTrue(any("database schema" in error for error in errors), errors)def test_database_schema_requires_an_unconditional_top_level_constant(self):- declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 26;\n"+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 27;\n"for source in ("#[cfg(all(unix, test))]\n" + declaration,"#[cfg(any(unix, test))]\n" + declaration,@@ -108,7 +108,7 @@ class ContractConvergenceTests(unittest.TestCase):self.assertTrue(any("database schema" in error for error in errors), errors)def test_database_schema_fails_closed_on_unterminated_lexical_input(self):- declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 26;\n"+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 27;\n"for suffix in ('/* unclosed', 'const TEXT: &str = r#"unclosed','const TEXT: &str = "unclosed', 'mod fixture {', ']'):with self.subTest(suffix=suffix):@@ -119,7 +119,7 @@ class ContractConvergenceTests(unittest.TestCase):self.assertTrue(any("database schema" in error for error in errors), errors)def test_database_schema_ignores_literal_and_comment_declarations(self):- declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 26;\n"+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 27;\n"for source in ('const FIXTURE: &str = "\n' + declaration + '";\n','const FIXTURE: &str = r"\n' + declaration + '";\n',@@ -147,7 +147,7 @@ const BRACE: char = '}';mod fixture {pub const LATEST_SCHEMA_VERSION: u32 = 17;}-pub const LATEST_SCHEMA_VERSION: u32 = 26;+pub const LATEST_SCHEMA_VERSION: u32 = 27;'''self.assertEqual(self.run_audit({"legacy.rs": '"hiroute.sample/v1"',diff --git a/scripts/test-delegation-product.py b/scripts/test-delegation-product.pyindex 209d588a..568786fb 100644--- a/scripts/test-delegation-product.py+++ b/scripts/test-delegation-product.py@@ -22,6 +22,7 @@ class CodexFixtureSelectionTests(unittest.TestCase):self.selected = root / 'installed-codex'self.selected.write_bytes(b'installed native Codex remains intact\n')self.product = Product(REPO, root=root / 'product')+ self.addCleanup(self.product.close)def test_fixture_refuses_to_write_through_selected_engine_symlink(self):(self.product.root / 'bin/codex').symlink_to(self.selected)diff --git a/scripts/test-native-context-product.py b/scripts/test-native-context-product.pyindex a3eb9dcb..f6a316a7 100644--- a/scripts/test-native-context-product.py+++ b/scripts/test-native-context-product.py@@ -25,6 +25,57 @@ class NativeContextOracleTests(unittest.TestCase):self.addCleanup(self.temporary.cleanup)self.root = Path(self.temporary.name)+ def test_product_listener_is_outside_the_hosts_outbound_ephemeral_range(self):+ product = Product(REPO, root=self.root / 'listener-product')+ try:+ bounds = (subprocess.check_output(['sysctl', '-n', 'net.inet.ip.portrange.first',+ 'net.inet.ip.portrange.last'], text=True).split() if sys.platform == 'darwin'+ else Path('/proc/sys/net/ipv4/ip_local_port_range').read_text().split())+ first, last = map(int, bounds)+ self.assertFalse(first <= product.port <= last,+ 'a closed bind(0) probe can be stolen by a concurrent outbound client')+ finally:+ product.close()++ def test_product_listener_lease_survives_service_stop_and_releases_with_the_fixture(self):+ product = Product(REPO, root=self.root / 'lease-product')+ other_tmp = self.root / 'competing-run-tmp'+ other_tmp.mkdir()+ command = [sys.executable, '-B', '-c', '''+import sys+from unittest.mock import patch+sys.path.insert(0, sys.argv[1])+from publication_product import fixture_listener_port+with patch('publication_product.secrets.SystemRandom') as chooser:+ chooser.return_value.sample.return_value = [int(sys.argv[2])]+ try:+ lease, port = fixture_listener_port()+ lease.close()+ print('available')+ except RuntimeError as error:+ assert str(error) == 'no unoccupied fixture listener address available', str(error)+ print('leased')+''', str(REPO/'crates/daemon/tests/support'), str(product.port)]+ environment = dict(os.environ, TMPDIR=str(other_tmp))+ process = None+ try:+ # Exercise the actual nonempty stop branch with a bounded local process+ # that exits on the same shutdown pipe EOF as the real daemon.+ product.shutdown_r, product.shutdown_w = os.pipe()+ product.cap_r, product.cap_w = os.pipe()+ product.cap_ack_r, product.cap_ack_w = os.pipe()+ process = product.process = subprocess.Popen([sys.executable, '-c',+ 'import os,sys; os.read(int(sys.argv[1]),1)', str(product.shutdown_r)],+ pass_fds=(product.shutdown_r,), stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ product.stop()+ self.assertEqual(subprocess.check_output(command, text=True, env=environment).strip(), 'leased')+ finally:+ product.close()+ if process is not None:+ process.stdout.close()+ process.stderr.close()+ self.assertEqual(subprocess.check_output(command, text=True, env=environment).strip(), 'available')+def context(self, harness):root = self.root / harnesshome, project = root / 'home', root / 'project'@@ -227,6 +278,7 @@ class NativeContextOracleTests(unittest.TestCase):'HIROUTE_WORKER_RECEIPT_DIR': '/daily/worker-receipts','QODER_PERSONAL_ACCESS_TOKEN': 'synthetic-qoder-secret'}):product = Product(REPO, root=self.root / 'product')+ self.addCleanup(product.close)home = Path(product.env['HOME'])self.assertEqual(product.env['CODEX_HOME'], str(home / '.codex'))self.assertEqual(product.env['CLAUDE_CONFIG_DIR'], str(home / '.claude'))@@ -239,6 +291,7 @@ class NativeContextOracleTests(unittest.TestCase):product.env['HOME'] = '/explicitly-borrowed/native-home'self.assertEqual(product.env['HIROUTE_WORKER_RECEIPT_DIR'], receipt_root)neighbor = Product(REPO, root=self.root / 'neighbor-product')+ self.addCleanup(neighbor.close)neighbor.env['HOME'] = product.env['HOME']self.assertNotEqual(neighbor.env['HIROUTE_WORKER_RECEIPT_DIR'], receipt_root)for key in ('CLAUDE_CODE_OAUTH_TOKEN', 'CODEX_CONFIG', 'AWS_PROFILE', 'QODER_PERSONAL_ACCESS_TOKEN',@@ -421,7 +474,7 @@ class NativeContextOracleTests(unittest.TestCase):project.mkdir()selected = home / 'custom-native-configuration'value = fixture.prepare(home, selected, project, 'claude')- self.assertEqual(Path(value['skills'][0]['skill']).parent.parent, selected / 'skills')+ self.assertEqual(Path(value['skills'][0]['skill']).parent.parent, (selected / 'skills').resolve())self.assertFalse((home / '.claude').exists())diff --git a/scripts/test-plan.py b/scripts/test-plan.pyindex 2f3ceb88..8a4c0405 100644--- a/scripts/test-plan.py+++ b/scripts/test-plan.py@@ -147,6 +147,18 @@ WORKER_PRODUCT_CHECKS = {"required_environment": ["HIROUTE_PRODUCT_CANDIDATE_SHA", "HIROUTE_WORKER_PI_BINARY", "HIROUTE_WORKER_NODE"],"missing_environment": "fail",},+ "dsh_delegation": {+ "id": "dsh.delegation", "harnesses": ["dsh"],+ "guide": "tools/product-e2e/tests/DSH_INTEGRATION.md",+ "required_tests": [+ "dsh_worker_uses_native_skills_and_continues_the_frozen_task",+ "dsh_workers_route_independently_cancel_and_reject_missing_history",+ "dsh_agent_saved_model_routes_preserve_defaults_and_restore_independently",+ "dsh_agent_uses_installed_user_skill_to_delegate_through_public_cli",+ "dsh_static_api_discovery_imports_effective_source_and_rejects_stale_save"],+ "required_environment": ["HIROUTE_PRODUCT_CANDIDATE_SHA", "HIROUTE_WORKER_DSH_BINARY"],+ "missing_environment": "fail",+ },}OPT_IN_WORKER_TARGETS = set(WORKER_PRODUCT_CHECKS)PRODUCT_GUIDES = {entry["guide"] for entry in WORKER_PRODUCT_CHECKS.values()} | {@@ -181,6 +193,10 @@ QODER_PRODUCT_PATHS = {"crates/integrations/src/agents/settings_discovery.rs","crates/integrations/src/agents/executable.rs",}+DSH_PRODUCT_PREFIXES = (+ "crates/integrations/src/agents/dsh", "crates/daemon/src/delegation/profile/dsh",+ "crates/integrations/src/agents/filesystem_tests/dsh",+)PI_PRODUCT_PREFIXES = ("crates/integrations/src/agents/pi", "crates/daemon/src/delegation/profile/pi","crates/daemon/src/control/runtime/model_connections/pi",@@ -214,9 +230,15 @@ def e2e_consumers(path):if path.startswith("tools/product-e2e/tests/") and Path(path).stem in OPT_IN_WORKER_TARGETS:return [("hiroute-product-e2e", Path(path).stem)]if path.startswith("crates/daemon/tests/support/native_context_"):- return [("hiroute-product-e2e", name) for name in ("worker_native_context", "qoder_delegation", "pi_delegation")]+ return [("hiroute-product-e2e", name) for name in ("worker_native_context", "qoder_delegation", "pi_delegation", "dsh_delegation")]+ if path == "crates/daemon/tests/support/native_task_witness.py":+ return [("hiroute-product-e2e", name) for name in ("qoder_delegation", "dsh_delegation")]if path == "crates/daemon/tests/support/agent_product_support.py" or path.startswith(ADDITIONAL_NATIVE_FIXTURE_PREFIXES):- return [("hiroute-product-e2e", name) for name in ("qoder_delegation", "pi_delegation")]+ return [("hiroute-product-e2e", name) for name in ("qoder_delegation", "pi_delegation", "dsh_delegation")]+ if path.startswith("crates/daemon/tests/support/dsh_") or path == "crates/daemon/tests/support/native_acp_client.py":+ return [("hiroute-product-e2e", "dsh_delegation")]+ if path == "crates/daemon/tests/support/pi_discovery_product.py":+ return [("hiroute-product-e2e", "pi_delegation"),("hiroute-product-e2e", "dsh_delegation")]if path.startswith("crates/daemon/tests/support/pi_"):return [("hiroute-product-e2e", "pi_delegation")]if path.startswith("crates/daemon/tests/support/qoder_"):@@ -251,14 +273,16 @@ def worker_product_checks(paths):continueselected.update(target for package, target in e2e_consumers(path)if package == "hiroute-product-e2e" and target in OPT_IN_WORKER_TARGETS)- if path.startswith(PI_PRODUCT_PREFIXES):+ if path.startswith(DSH_PRODUCT_PREFIXES):+ selected.add("dsh_delegation")+ elif path.startswith(PI_PRODUCT_PREFIXES):selected.add("pi_delegation")elif path.startswith(ADDITIONAL_MODEL_PREFIXES):- selected.update(("qoder_delegation", "pi_delegation"))+ selected.update(("qoder_delegation", "pi_delegation", "dsh_delegation"))elif path in QODER_PRODUCT_PATHS or path.startswith(QODER_PRODUCT_PREFIXES):selected.add("qoder_delegation")if path in QODER_PRODUCT_PATHS or path.startswith(("crates/application/src/agent_connection/settings/", "crates/application/src/agent_connection/skill")):- selected.add("pi_delegation")+ selected.update(("pi_delegation", "dsh_delegation"))elif path.startswith(("crates/daemon/src/delegation/", "crates/application/src/delegation/","crates/domain/src/delegation/")) or path in SHARED_WORKER_FIXTURES:selected.update(OPT_IN_WORKER_TARGETS)diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.pyindex 34ec98b7..c86215fa 100644--- a/scripts/test-test-plan.py+++ b/scripts/test-test-plan.py@@ -136,7 +136,7 @@ class SelectionTests(unittest.TestCase):):with self.subTest(path=path):result = plan.select([path])- expected = ['qoder_delegation', 'pi_delegation'] if (path in plan.QODER_PRODUCT_PATHS or path.startswith(('crates/application/src/agent_connection/skill', 'crates/application/src/agent_connection/settings/'))) else ['qoder_delegation']+ expected = ['qoder_delegation', 'pi_delegation', 'dsh_delegation'] if (path in plan.QODER_PRODUCT_PATHS or path.startswith(('crates/application/src/agent_connection/skill', 'crates/application/src/agent_connection/settings/'))) else ['qoder_delegation']self.assertEqual([check['command'][6] for check in result['product_checks']], expected)self.assertIn(['python3', 'scripts/test-qoder-product.py'], result['commands'])# Model-specific settings are not consumers of the independent Qoder Skill path.@@ -148,7 +148,7 @@ class SelectionTests(unittest.TestCase):def test_shared_agent_journey_helper_selects_current_consumers_and_its_ownership_checks(self):result = plan.select(['crates/daemon/tests/support/agent_product_support.py'])self.assertEqual(result['mode'], 'affected')- self.assertEqual([check['command'][6] for check in result['product_checks']], ['qoder_delegation', 'pi_delegation'])+ self.assertEqual([check['command'][6] for check in result['product_checks']], ['qoder_delegation', 'pi_delegation', 'dsh_delegation'])self.assertIn(['python3', 'scripts/test-agent-product-support.py'], result['commands'])tooling = plan.select(['scripts/test-agent-product-support.py'])self.assertEqual(tooling['product_checks'], [])@@ -162,7 +162,7 @@ class SelectionTests(unittest.TestCase):result = plan.select([path])self.assertEqual(result['mode'], 'affected')self.assertEqual({check['command'][6] for check in result['product_checks']},- {'worker_native_context', 'qoder_delegation', 'pi_delegation'})+ {'worker_native_context', 'qoder_delegation', 'pi_delegation', 'dsh_delegation'})def test_qoder_production_gates_preserve_ordinary_owner_checks_and_deduplicate(self):result = plan.select(['crates/integrations/src/agents/qoder.rs',@@ -185,7 +185,7 @@ class SelectionTests(unittest.TestCase):'crates/daemon/src/control/runtime/native_additional_model.rs'):with self.subTest(path=path):checks = plan.select([path])['product_checks']- self.assertEqual({check['command'][6] for check in checks}, {'qoder_delegation', 'pi_delegation'})+ self.assertEqual({check['command'][6] for check in checks}, {'qoder_delegation', 'pi_delegation', 'dsh_delegation'})checks = plan.select(['crates/integrations/src/agents/pi_sources.rs'])['product_checks']self.assertEqual([check['command'][6] for check in checks], ['pi_delegation'])self.assertIn('pi_worker_recovers_length_overflow_and_continues_edited_history', checks[0]['required_tests'])@@ -198,6 +198,18 @@ class SelectionTests(unittest.TestCase):self.assertFalse(result['frontend'])self.assertEqual(result['product_checks'], [])+ def test_dsh_native_leaf_and_shared_acp_fixture_select_their_actual_consumers(self):+ for path in ('crates/integrations/src/agents/dsh_native.rs',+ 'crates/daemon/tests/support/dsh_native_context.py',+ 'crates/daemon/tests/support/native_acp_client.py'):+ checks = plan.worker_product_checks([path])+ self.assertEqual([row['id'] for row in checks],['dsh.delegation'])+ self.assertEqual(checks[0]['missing_environment'],'fail')+ shared = plan.worker_product_checks(['crates/daemon/tests/support/pi_discovery_product.py'])+ self.assertEqual({row['id'] for row in shared},{'pi.delegation','dsh.delegation'})+ witness = plan.worker_product_checks(['crates/daemon/tests/support/native_task_witness.py'])+ self.assertEqual({row['id'] for row in witness},{'qoder.delegation','dsh.delegation'})+def test_worker_context_changes_require_explicit_real_harness_cases(self):for path in ('crates/daemon/src/delegation/profile/mod.rs','crates/daemon/src/delegation/executor/resume.rs',@@ -205,7 +217,7 @@ class SelectionTests(unittest.TestCase):with self.subTest(path=path):result = plan.select([path])required = result['product_checks']- self.assertEqual(len(required), 1 if path.endswith('worker_native_context.rs') else 5)+ self.assertEqual(len(required), 1 if path.endswith('worker_native_context.rs') else len(plan.WORKER_PRODUCT_CHECKS))self.assertEqual(required[0]['id'], 'worker.native-context')self.assertEqual(required[0]['harnesses'], ['codex', 'claude'])self.assertIn('--ignored', required[0]['command'])diff --git a/tools/product-e2e/tests/DSH_INTEGRATION.md b/tools/product-e2e/tests/DSH_INTEGRATION.mdnew file mode 100644index 00000000..30c9b894--- /dev/null+++ b/tools/product-e2e/tests/DSH_INTEGRATION.md@@ -0,0 +1,43 @@+# DSH product acceptance++[Entry](dsh_delegation.rs) · [Code map](../../../docs/code-map/dsh.md)++Select an explicitly installed official DSH CLI with `HIROUTE_WORKER_DSH_BINARY`+and an exact committed `HIROUTE_PRODUCT_CANDIDATE_SHA`. Native npm launch also+requires its supported Node on PATH. Do not select an adapter or unrelated SDK.+The executable test entry builds the matching production daemon and CLI and+requires every declared case to report green. An omitted installation is a+failure, not a successful skip.++Run the ignored `dsh_delegation` target through `scripts/validation.py backend`+with the feature plan and exact ref/SHA. The five product journeys cover passive+Scan → Prepare → Save → restart → use, both saved model protocols and independent+restore/credential rotation, native Skills and frozen exact Continue, concurrent+routes/cancellation/missing-history rejection, and a native main Agent reading+the installed user Skill before executing a real Worker through the public CLI.+Use `HIROUTE_PRODUCT_AGENT_PROTOCOL=responses` and `messages` for Worker variants.++For credential-import changes, run the exact+`dsh_static_api_discovery_imports_effective_source_and_rejects_stale_save` case+with `HIROUTE_PRODUCT_DSH_CREDENTIAL_SOURCE=path` and `dsh-home` separately. Both+variants retain a valid private default file with a different key, import only+the active store, reject Save after its rotation, preserve all native files, and+use the imported source in an ordinary native request. Zero inference during+Scan/Prepare/Save remains independently asserted. This targeted source case+does not replace unrelated Worker/Continue or native Desktop evidence.++All native homes and writable Web provider files are fixture-owned. Borrowed+HOME in production remains separate from task-owned history. Only the source+model is deterministic; native CLI, ACP, public control, Gateway, native tools+and Worker processes are real. The persisted Web model file is consumed through+native ACP `--patch` and explicit model selection, without injected provider or+credential values. This proves the persisted public configuration is usable;+it does not claim DSH's own Web UI was exercised. Desktop acceptance must also+configure and read back the real HiRoute UI and observe a real delegated task.++The initial research/acceptance installation is `0.2.0-rc.2`. Record the actual+CLI version and full HiRoute SHA in each run. Production checks required public+capabilities, not this label. No multi-version matrix, native-history decoder or+cross-version exact Continue contract is introduced. Same-installation Continue+and daemon restart remain required. Controlled upstreams do not establish paid+provider/account compatibility.diff --git a/tools/product-e2e/tests/dsh_delegation.rs b/tools/product-e2e/tests/dsh_delegation.rsnew file mode 100644index 00000000..a0ce1d82--- /dev/null+++ b/tools/product-e2e/tests/dsh_delegation.rs@@ -0,0 +1,43 @@+#![cfg(unix)]+mod worker_product_support;++#[test]+#[ignore = "requires the selected official DSH CLI and real production binaries"]+fn dsh_worker_uses_native_skills_and_continues_the_frozen_task() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_DSH_CORE",+ "worker-native-context-core",+ );+}+#[test]+#[ignore = "requires the selected official DSH CLI and real production binaries"]+fn dsh_workers_route_independently_cancel_and_reject_missing_history() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_DSH_BOUNDARIES",+ "worker-native-context-boundaries",+ );+}+#[test]+#[ignore = "requires the selected official DSH CLI and real production binaries"]+fn dsh_agent_saved_model_routes_preserve_defaults_and_restore_independently() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_DSH_MODELS",+ "dsh-persisted-model-routes",+ );+}+#[test]+#[ignore = "requires the selected official DSH CLI and real production binaries"]+fn dsh_agent_uses_installed_user_skill_to_delegate_through_public_cli() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_DSH_MAIN",+ "dsh-main-agent-delegation",+ );+}+#[test]+#[ignore = "requires the selected official DSH CLI and real production binaries"]+fn dsh_static_api_discovery_imports_effective_source_and_rejects_stale_save() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_DSH_DISCOVERY",+ "dsh-static-source-import",+ );+}diff --git a/tools/product-e2e/tests/worker_product_support/mod.rs b/tools/product-e2e/tests/worker_product_support/mod.rsindex ea613e56..6f7a1eee 100644--- a/tools/product-e2e/tests/worker_product_support/mod.rs+++ b/tools/product-e2e/tests/worker_product_support/mod.rs@@ -15,6 +15,24 @@ const REQUIRED_INSTALLATIONS: [&str; 5] = [];pub fn run_real_worker_scenario(mode: &str, expected_scenario: &str) {+ let dsh_script = match mode {+ "HIROUTE_PRODUCT_DSH_CORE" => Some("native_context_product.py"),+ "HIROUTE_PRODUCT_DSH_BOUNDARIES" => Some("native_context_boundaries.py"),+ "HIROUTE_PRODUCT_DSH_MODELS" => Some("additional_model_product.py"),+ "HIROUTE_PRODUCT_DSH_MAIN" => Some("collaboration_product.py"),+ "HIROUTE_PRODUCT_DSH_DISCOVERY" => Some("pi_discovery_product.py"),+ _ => None,+ };+ if let Some(script) = dsh_script {+ run_scenario(+ script,+ mode,+ expected_scenario,+ &["dsh"],+ &["HIROUTE_WORKER_DSH_BINARY"],+ );+ return;+ }let pi_script = match mode {"HIROUTE_PRODUCT_PI_CORE" => Some("native_context_product.py"),"HIROUTE_PRODUCT_PI_BOUNDARIES" => Some("native_context_boundaries.py"),@@ -184,17 +202,21 @@ fn assert_scenario(output: Output, scenario: &str, harness: &str, candidate: &st"worker.context.compaction-route",],"pi-worker-compaction-route" => &["worker.context.compaction-route"],- "pi-static-source-import" => &[+ "pi-static-source-import" | "dsh-static-source-import" => &["agent.sources.effective-static-import","agent.sources.changed-source-rejected","agent.sources.imported-route-usable",],- "qoder-main-agent-delegation" | "pi-main-agent-delegation" => &[+ "qoder-main-agent-delegation"+ | "pi-main-agent-delegation"+ | "dsh-main-agent-delegation" => &["agent.collaboration.user-skill","agent.collaboration.public-worker-delegation","agent.collaboration.disable-owned-skill",],- "qoder-persisted-model-routes" | "pi-persisted-model-routes" => &[+ "qoder-persisted-model-routes"+ | "pi-persisted-model-routes"+ | "dsh-persisted-model-routes" => &["agent.models.persisted-routes","agent.models.credential-rotation","agent.models.independent-restore",