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 Pi Agent model routing and task delegation (#44)
澄潭189962e2da5f
diff --git a/apps/desktop/src-tauri/src/agent_check_session.rs b/apps/desktop/src-tauri/src/agent_check_session.rsindex fc7ba3dc..d7bc3dfc 100644--- a/apps/desktop/src-tauri/src/agent_check_session.rs+++ b/apps/desktop/src-tauri/src/agent_check_session.rs@@ -122,6 +122,7 @@ impl AgentCheckConfirmation {let agent = match self.request.agent_id.as_str() {"agent_claude_default" => "Claude Code","agent_qoder_default" => "Qoder",+ "agent_pi_default" => "Pi",_ => "Codex",};if self.request.scope == AgentCheckScopeV1::Live {@@ -135,6 +136,7 @@ impl AgentCheckConfirmation {AgentModelSurfaceV2::CodexDesktop => "Codex Desktop",AgentModelSurfaceV2::ClaudeCli => "Claude Code CLI",AgentModelSurfaceV2::QoderCli => "Qoder CLI",+ AgentModelSurfaceV2::PiCli => "Pi CLI",};let models = target.client_model_ids.join(", ");let message = if self.english {@@ -172,6 +174,15 @@ impl AgentCheckConfirmation {"检查 Qoder 任务协作?\n使用所选 Qoder CLI 的正常登录状态和用户技能,在独立验证目录中访问本机测试端点,不调用上游提供方,也不执行委派任务。已启用协作时检查已安装的用户协作技能;尚未启用时检查启用能力。不改写日常配置。".into()};}+ if self.request.scope == AgentCheckScopeV1::Collaboration+ && self.request.agent_id == "agent_pi_default"+ {+ return if self.english {+ "Check local Pi task delegation compatibility?\nReads the selected official SDK, native Skill settings and trusted sibling HiRoute CLI. No model call, delegated task or native configuration change.".into()+ } else {+ "检查本机 Pi 任务委派兼容性?\n读取所选官方 SDK、原生技能设置和同一安装中的 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."@@ -255,6 +266,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_qoder_default" => matches!(scope,AgentCheckScopeV1::Collaboration | AgentCheckScopeV1::Live@@ -369,31 +381,42 @@ mod tests {}#[test]- fn qoder_checks_keep_collaboration_independent_and_require_explicit_live_targets() {+ fn additional_agents_keep_collaboration_independent_and_require_explicit_live_targets() {+ for agent in ["agent_qoder_default", "agent_pi_default"] {+ let mut input = AgentCheckInput {+ agent_id: agent.into(),+ language: "en".into(),+ scope: Some("collaboration".into()),+ target: None,+ };+ let request = input+ .request()+ .expect("Task routing can reach its local prerequisite check");+ assert_eq!(request.scope, AgentCheckScopeV1::Collaboration);+ assert!(!request.allow_model_call);+ assert!(request.target.is_none());+ input.target = Some(live_target());+ assert!(+ input.request().is_err(),+ "Task routing cannot borrow a model target"+ );+ input.target = None;+ for scope in [None, Some("native_authentication"), Some("live")] {+ input.scope = scope.map(str::to_owned);+ assert!(input.request().is_err());+ }+ if agent == "agent_pi_default" {+ input.target = Some(live_target());+ input.target.as_mut().unwrap().surface = AgentModelSurfaceV2::PiCli;+ assert!(input.request().is_err(), "Pi has no paid Live check");+ }+ }let mut input = AgentCheckInput {agent_id: "agent_qoder_default".into(),language: "en".into(),- scope: Some("collaboration".into()),- target: None,+ scope: Some("live".into()),+ target: Some(live_target()),};- let request = input- .request()- .expect("Qoder collaboration can reach the protected check");- assert_eq!(request.scope, AgentCheckScopeV1::Collaboration);- assert!(!request.allow_model_call);- assert!(request.target.is_none());- input.target = Some(live_target());- assert!(- input.request().is_err(),- "Collaboration cannot borrow a model target"- );- input.target = None;- for scope in [None, Some("native_authentication"), Some("live")] {- input.scope = scope.map(str::to_owned);- assert!(input.request().is_err());- }- input.scope = Some("live".into());- input.target = Some(live_target());let request = input.request().expect("Explicit Qoder Live target");assert!(request.allow_model_call);assert_eq!(request.target, input.target);@@ -430,12 +453,14 @@ mod tests {),("agent_claude_default", vec![AgentModelSurfaceV2::ClaudeCli]),("agent_qoder_default", vec![AgentModelSurfaceV2::QoderCli]),+ ("agent_pi_default", vec![]),] {for surface in [AgentModelSurfaceV2::CodexCli,AgentModelSurfaceV2::CodexDesktop,AgentModelSurfaceV2::ClaudeCli,AgentModelSurfaceV2::QoderCli,+ AgentModelSurfaceV2::PiCli,] {let mut target = live_target();target.surface = surface;diff --git a/apps/desktop/src-tauri/src/bridge/model_connection_web.rs b/apps/desktop/src-tauri/src/bridge/model_connection_web.rsindex 11518aa0..30565327 100644--- a/apps/desktop/src-tauri/src/bridge/model_connection_web.rs+++ b/apps/desktop/src-tauri/src/bridge/model_connection_web.rs@@ -54,6 +54,8 @@ impl TryFrom<WebComputeDiscoveryRefV1> for ComputeDiscoveryRefV1 {pub(super) struct WebComputeScanItemV1 {agent_id: String,supported: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ native_provider_id: Option<String>,configuration_state: String,#[serde(skip_serializing_if = "Option::is_none")]connection_option_id: Option<String>,@@ -81,6 +83,7 @@ impl From<ComputeScanResultV1> for WebComputeScanResultV1 {.map(|item| WebComputeScanItemV1 {agent_id: item.agent_id,supported: item.supported,+ native_provider_id: item.native_provider_id,configuration_state: item.configuration_state,connection_option_id: item.connection_option_id,observed_model_id: item.observed_model_id,@@ -383,7 +386,7 @@ mod tests {#[test]fn compute_scan_web_view_omits_protected_discovery_material() {- let scan = ComputeScanResultV1 {+ let mut scan = ComputeScanResultV1 {schema: COMPUTE_SCAN_RESULT_SCHEMA_V1.into(),catalog: ComputeCatalogProvenanceViewV1 {product_release: "fixture-release".into(),@@ -394,6 +397,7 @@ mod tests {cross_reference_digest: CanonicalDigest::of_bytes(b"cross-reference"),},items: vec![ComputeScanItemV1 {+ native_provider_id: None,agent_id: "agent_claude_default".into(),supported: true,configuration_state: "registered_with_protected_input".into(),@@ -427,9 +431,23 @@ mod tests {}],};+ scan.items.push(ComputeScanItemV1 {+ agent_id: "agent_pi_default".into(),+ native_provider_id: Some("native-static-provider".into()),+ connection_option_id: None,+ ..scan.items[0].clone()+ });+let web = serde_json::to_value(WebComputeScanResultV1::from(scan)).unwrap();assert_eq!(web["items"][0]["agent_id"], "agent_claude_default");assert_eq!(web["items"][0]["supported"], true);+ assert!(web["items"][0].get("native_provider_id").is_none());+ assert_eq!(web["items"][1]["agent_id"], "agent_pi_default");+ assert_eq!(+ web["items"][1]["native_provider_id"],+ "native-static-provider"+ );+ assert!(web["items"][1].get("connection_option_id").is_none());assert_eq!(web["items"][0]["configuration_state"],"registered_with_protected_input"diff --git a/apps/desktop/src/features/WorkerDependencies.tsx b/apps/desktop/src/features/WorkerDependencies.tsxindex 72265111..056abce1 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' }[harness];+ const name = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', qoder_cli: 'Qoder CLI', pi: 'Pi' }[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' ? {} : { adapter_path: '', node_path: null }),+ ...(harness === 'qoder_cli' ? {} : { ...(harness === 'pi' ? {} : { adapter_path: '' }), node_path: null }),expected_selection_revision: view ? workerDependencyRevision(view, harness) : 0,...current,...patch,@@ -143,7 +143,7 @@ export function WorkerDependencies({try {const input = harness === 'qoder_cli'? { harness, cli_path: selection.cli_path, expected_selection_revision: selection.expected_selection_revision }- : selection;+ : harness === 'pi' ? { harness, cli_path: selection.cli_path, node_path: selection.node_path, expected_selection_revision: selection.expected_selection_revision } : selection;const prepared = await invoke<Confirmation>('worker_dependencies_select_prepare', { input });if (!mounted.current) {await invoke('worker_dependencies_select_cancel', {@@ -222,9 +222,10 @@ 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 === '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.')- : text(`查找 ${name}、连接组件和必要的 Node.js。`, `Find ${name}, its adapter, and Node.js when required.`)}</span></div><button className="btn btn-primary" type="button" disabled={refreshing} onClick={() => void discover()}>{refreshing ? text('正在检测…', 'Detecting…') : text('一键检测', 'Detect')}</button></div></div>}+ : harness === 'pi' ? text('查找 Pi 和 Node.js。', 'Find Pi and Node.js.') : text(`查找 ${name}、连接组件和必要的 Node.js。`, `Find ${name}, its adapter, and Node.js when required.`)}</span></div><button className="btn btn-primary" type="button" disabled={refreshing} onClick={() => void discover()}>{refreshing ? text('正在检测…', 'Detecting…') : text('一键检测', 'Detect')}</button></div></div>}{view && <div className={`callout ${state === 'configured' ? 'good' : state === 'found' ? '' : 'warn'}`}><UiIcon name={state === 'incomplete' ? 'warning' : 'check'} />@@ -249,7 +250,7 @@ export function WorkerDependencies({</div>}{advanced && view && <Disclosure className="native-details" defaultOpen label={text('安装路径与候选', 'Installation paths and candidates')} language={language}>{components.map(component => <div className="field" key={component}>- <label className="field-label" htmlFor={`worker-${harness}-${component}`}>{componentName(component)} {component === 'node' && <span className="muted">{text('按连接组件需要选填', 'Optional when the adapter does not require it')}</span>}</label>+ <label className="field-label" htmlFor={`worker-${harness}-${component}`}>{componentName(component)} {component === 'node' && harness !== 'pi' && <span className="muted">{text('按连接组件需要选填', 'Optional when the adapter does not require it')}</span>}</label><input id={`worker-${harness}-${component}`} className="input" value={inputValue(component)} placeholder={text('输入绝对路径', 'Enter an absolute path')} onChange={event => selectCandidate(component, event.target.value)} />{!!candidates(component).length && <div className="native-list">{candidates(component).map(candidate => <button className={`list-row${inputValue(component) === candidate.path ? ' active' : ''}`} type="button" key={`${component}:${candidate.path}`} onClick={() => selectCandidate(component, candidate.path)}><span className="row-main"><span className="row-title">{candidate.path}</span><span className="row-meta">{candidate.source} · {candidate.state}</span></span>{inputValue(component) === candidate.path && <UiIcon name="check" />}</button>)}</div>}</div>)}</Disclosure>}diff --git a/apps/desktop/src/features/agents/AdditionalModelEditor.tsx b/apps/desktop/src/features/agents/AdditionalModelEditor.tsxnew file mode 100644index 00000000..f49ddfab--- /dev/null+++ b/apps/desktop/src/features/agents/AdditionalModelEditor.tsx@@ -0,0 +1,35 @@+import React from 'react';+import { UiIcon } from '../../ui';+import { agentDisplayName } from './ecosystems';+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 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));+ function toggle(planId: string) {+ onChange(current => ({ ...current, allowedPlanIds: current.allowedPlanIds.includes(planId)+ ? current.allowedPlanIds.filter(id => id !== planId) : [...current.allowedPlanIds, planId] }));+ onEdited();+ }+ return <div className="worker-choices" data-additional-routes={name} data-qoder-additional-routes={name === 'Qoder' ? true : undefined}>+ <p>{text(`将所选智能路由添加到 ${name} 的模型选择中。原有模型、提供方、登录和当前默认模型保持不变。`, `Add selected smart routes to ${name}’s model choices. Existing models, providers, sign-in and the current default model stay unchanged.`)}</p>+ <fieldset disabled={disabled} className="worker-choices">+ <legend className="field-label">{text(`添加智能路由`, `Add smart routes`)}</legend>+ {enabledPlans.map(plan => <label className="check-row" key={plan.agent_plan_id} data-agent-plan-id={plan.agent_plan_id}>+ <input type="checkbox" checked={values.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggle(plan.agent_plan_id)} />+ <span>{plan.desired.display_name}</span>+ </label>)}+ {unavailable.map(id => <label className="check-row" key={id} data-agent-plan-id={id}>+ <input type="checkbox" checked onChange={() => toggle(id)} />+ <span>{plans.find(plan => plan.agent_plan_id === id)?.desired.display_name ?? id} · {text(`当前不可用,可取消选择`, `Currently unavailable; deselect to remove`)}</span>+ </label>)}+ </fieldset>+ <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">{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>+ {invalid && <span className="oc-inline-error">{text(`至少选择一条已启用路由,并取消不可用的选择。`, `Select at least one enabled route and remove unavailable selections.`)}</span>}+ {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div>{text(`先创建并启用一条智能路由。任务协作仍可独立启用。`, `Create and enable a smart route first. Task collaboration can still be enabled independently.`)}</div>{onCreatePlan && <button className="btn" type="button" onClick={onCreatePlan}>{text(`创建路由`, `Create route`)}</button>}</div>}+ </div>;+}diff --git a/apps/desktop/src/features/agents/AgentModelEditor.tsx b/apps/desktop/src/features/agents/AgentModelEditor.tsxindex 9ac7d362..24bdbf07 100644--- a/apps/desktop/src/features/agents/AgentModelEditor.tsx+++ b/apps/desktop/src/features/agents/AgentModelEditor.tsx@@ -7,7 +7,7 @@ import { commonClaudePlan } from './editor-state';import { agentEcosystem } from './ecosystems';import { CodexModelEditor } from './CodexModelEditor';import { ClaudeModelEditor } from './ClaudeModelEditor';-import { QoderModelEditor } from './QoderModelEditor';+import { AdditionalModelEditor } from './AdditionalModelEditor';export type AgentModelEditorProps = {agent: Agent;@@ -27,7 +27,8 @@ export function AgentModelEditor(props: AgentModelEditorProps) {switch (agentEcosystem(props.agent.agent_id)) {case 'codex': return <CodexModelEditor {...props} />;case 'claude': return <ClaudeModelEditor {...props} />;- case 'qoder': return <QoderModelEditor {...props} />;+ case 'pi':+ case 'qoder': return <AdditionalModelEditor {...props} />;default: return null;}}@@ -48,6 +49,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 'pi_additional':case 'qoder_additional':return selection.allowed_plan_ids.map(id => planName(id) ?? text('当前路由不可用', 'Current route unavailable')).join(' · ');default: return '';diff --git a/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx b/apps/desktop/src/features/agents/AgentSettingsFeedback.tsxindex 4807ae92..4da8c789 100644--- a/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx+++ b/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx@@ -30,6 +30,8 @@ export function AgentSettingsFeedback({ preview, agent: selected, facet, default? `${text('原 Codex 默认模型没有同账号可用路由;请接入对应来源,或改选“只使用已配置的 HiRoute 模型”:', 'The native Codex default has no proven same-account route. Connect its source or select HiRoute-only: ')}${(block.model_ids ?? []).join(', ')}`: 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.'): 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/QoderModelEditor.tsx b/apps/desktop/src/features/agents/QoderModelEditor.tsxdeleted file mode 100644index 7eacaeb1..00000000--- a/apps/desktop/src/features/agents/QoderModelEditor.tsx+++ /dev/null@@ -1,33 +0,0 @@-import React from 'react';-import { UiIcon } from '../../ui';-import type { AgentModelEditorProps } from './AgentModelEditor';--/** Qoder adds explicit routes without importing or replacing native models. */-export function QoderModelEditor({ values, plans, language, disabled, invalid, onChange, onEdited, onCreatePlan }: AgentModelEditorProps) {- const text = (zh: string, en: string) => language === 'zh' ? zh : en;- const enabledPlans = plans.filter(plan => plan.head.status === 'enabled');- const unavailable = values.allowedPlanIds.filter(id => !enabledPlans.some(plan => plan.agent_plan_id === id));- function toggle(planId: string) {- onChange(current => ({ ...current, allowedPlanIds: current.allowedPlanIds.includes(planId)- ? current.allowedPlanIds.filter(id => id !== planId) : [...current.allowedPlanIds, planId] }));- onEdited();- }- return <div className="worker-choices" data-qoder-additional-routes>- <p>{text('将所选智能路由添加到 Qoder 的模型选择中。原有模型、提供方、登录和当前默认模型保持不变。', 'Add selected smart routes to Qoder’s model choices. Existing models, providers, sign-in and the current default model stay unchanged.')}</p>- <fieldset disabled={disabled} className="worker-choices">- <legend className="field-label">{text('添加智能路由', 'Add smart routes')}</legend>- {enabledPlans.map(plan => <label className="check-row" key={plan.agent_plan_id} data-agent-plan-id={plan.agent_plan_id}>- <input type="checkbox" checked={values.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggle(plan.agent_plan_id)} />- <span>{plan.desired.display_name}</span>- </label>)}- {unavailable.map(id => <label className="check-row" key={id} data-agent-plan-id={id}>- <input type="checkbox" checked onChange={() => toggle(id)} />- <span>{plans.find(plan => plan.agent_plan_id === id)?.desired.display_name ?? id} · {text('当前不可用,可取消选择', 'Currently unavailable; deselect to remove')}</span>- </label>)}- </fieldset>- <p className="field-help" data-agent-activation>{text('保存后重新启动 Qoder,通过 /model 明确选用已添加的 HiRoute 路由。未选择时继续使用原来的模型。', 'Restart Qoder 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 中调整或移除这些路由。如果已将某条路由设为 Qoder 默认模型,移除前请先在 Qoder 中切换到其他模型。', 'Adjust or remove these routes in HiRoute. If one is now your Qoder default, switch to another model in Qoder before removing it.')}</p>- {invalid && <span className="oc-inline-error">{text('至少选择一条已启用路由,并取消不可用的选择。', 'Select at least one enabled route and remove unavailable selections.')}</span>}- {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div>{text('先创建并启用一条智能路由。任务协作仍可独立启用。', 'Create and enable a smart route first. Task collaboration can still be enabled independently.')}</div>{onCreatePlan && <button className="btn" type="button" onClick={onCreatePlan}>{text('创建路由', 'Create route')}</button>}</div>}- </div>;-}diff --git a/apps/desktop/src/features/agents/README.md b/apps/desktop/src/features/agents/README.mdindex 19476c7f..53793e2d 100644--- a/apps/desktop/src/features/agents/README.md+++ b/apps/desktop/src/features/agents/README.md@@ -14,7 +14,7 @@ to their production owners and executable contracts.| [ecosystems.ts](ecosystems.ts) | Explicit current Agent identity, display name, brand and surface labels. Unknown discovered identities have no settings editor. || [editor-state.ts](editor-state.ts) | Draft initialization, dirty comparison and local form completeness. Only a trusted first connection can preselect a sole enabled route. Existing mappings, including unavailable choices, are retained. || [settings-request.ts](settings-request.ts) | Ecosystem-specific intent construction, independent model/collaboration restore intents, token changes that retain the saved selection, and capability-based prerequisite check selection. |-| [AgentModelEditor.tsx](AgentModelEditor.tsx) | Explicit composition of [Codex](CodexModelEditor.tsx), [Claude](ClaudeModelEditor.tsx) and [Qoder](QoderModelEditor.tsx) forms and their saved-selection summary. Codex allowlist/default/native retention, Claude preset mappings and Qoder additional routes remain different concepts. |+| [AgentModelEditor.tsx](AgentModelEditor.tsx) | Explicit composition of [Codex](CodexModelEditor.tsx), [Claude](ClaudeModelEditor.tsx) and [Qoder](AdditionalModelEditor.tsx) forms and their saved-selection summary. Codex allowlist/default/native retention, Claude preset mappings and Qoder additional routes remain different concepts. || [AgentSettingsFeedback.tsx](AgentSettingsFeedback.tsx) | Presentation of authoritative Preview blockers. || [collaboration-check-feedback.ts](collaboration-check-feedback.ts) | Versioned collaboration-check failures become safe login, Skill recovery and retry guidance; native output is never display text. || [CodexAccessPanel.tsx](CodexAccessPanel.tsx) | Profile/root facts, mode controls, launch commands, ordinary file-conflict diagnosis and an existing pending Operation's recovery entry. |diff --git a/apps/desktop/src/features/agents/ecosystems.ts b/apps/desktop/src/features/agents/ecosystems.tsindex f92b78ea..44ceb445 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';+export type AgentEcosystem = 'codex' | 'claude' | 'qoder' | 'pi';/** 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_pi_default': return 'pi';case 'agent_qoder_default': return 'qoder';default: return null;}@@ -14,7 +15,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';+ return ecosystem === 'codex' || ecosystem === 'claude' || ecosystem === 'qoder' || ecosystem === 'pi';}/** A saved selection must belong to the actual integration, including token-only edits. */@@ -22,6 +23,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 'pi': return selection.mode === 'pi_additional';case 'qoder': return selection.mode === 'qoder_additional';default: return false;}@@ -31,15 +33,17 @@ export function agentDisplayName(agentId: string, language: 'zh' | 'en'): stringswitch (agentEcosystem(agentId)) {case 'codex': return 'Codex';case 'claude': return 'Claude Code';+ 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' | 'agent' {+export function agentBrand(agentId: string): 'codex' | 'claude-code' | 'qoder' | 'pi' | 'agent' {switch (agentEcosystem(agentId)) {case 'codex': return 'codex';case 'claude': return 'claude-code';+ case 'pi': return 'pi';case 'qoder': return 'qoder';default: return 'agent';}@@ -50,6 +54,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 '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 b72ec63b..534f319d 100644--- a/apps/desktop/src/features/agents/editor-state.ts+++ b/apps/desktop/src/features/agents/editor-state.ts@@ -70,7 +70,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 : undefined;+ const qoder = (currentModel?.mode === 'qoder_additional' || currentModel?.mode === 'pi_additional') ? currentModel : undefined;const collaboration = facet === 'collaboration'&& selection&& 'trigger_mode' in selection@@ -85,7 +85,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') ? [initialPlan] : []),+ ?? (initialPlan && (ecosystem === 'codex' || ecosystem === 'qoder' || ecosystem === 'pi') ? [initialPlan] : []),defaultChoice: codex?.default_selection ?? (initialPlan && ecosystem === 'codex'? { kind: 'plan', plan_id: initialPlan } : { kind: 'preserve_native' }),claudePresets: claude?.preset_mappings ?? {@@ -113,7 +113,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 (agentEcosystem(agent.agent_id) === 'qoder') {+ if (['qoder', 'pi'].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 bad6df7f..85f2f76d 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 'pi':+ settings = { mode: 'pi_additional', allowed_plan_ids: values.allowedPlanIds };+ break;case 'qoder':settings = { mode: 'qoder_additional', allowed_plan_ids: values.allowedPlanIds };break;diff --git a/apps/desktop/src/features/agents/types.ts b/apps/desktop/src/features/agents/types.tsindex 85e80312..6208bade 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';+export type AgentModelSurface = 'codex_cli' | 'codex_desktop' | 'claude_cli' | 'qoder_cli' | 'pi_cli';export type AgentReasoningSelection =| { kind: 'profile'; profile: string }| { kind: 'toggle'; enabled: boolean }@@ -85,7 +85,8 @@ export type QoderModelSelection = {mode: 'qoder_additional';allowed_plan_ids: string[];};-export type AgentModelSelection = CodexModelSelection | ClaudeModelSelection | QoderModelSelection;+export type PiModelSelection = { mode: 'pi_additional'; allowed_plan_ids: string[] };+export type AgentModelSelection = CodexModelSelection | ClaudeModelSelection | QoderModelSelection | PiModelSelection;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 43f15465..f046c371 100644--- a/apps/desktop/src/features/device-scan/DeviceScanList.tsx+++ b/apps/desktop/src/features/device-scan/DeviceScanList.tsx@@ -6,6 +6,7 @@ import { agentBrandFromId } from '../../ui/BrandIcon';export type ComputeScanItem = {agent_id: string;supported: boolean;+ native_provider_id?: string;configuration_state: string;connection_option_id?: string;observed_model_id?: string;@@ -22,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_pi_default') return 'Pi';if (agentId.includes('qoder')) return 'Qoder';return language === 'zh' ? '本机 Agent' : 'Local agent';}@@ -123,7 +125,7 @@ export function DeviceScanList({onViewConnectedSubscription(candidate: SubscriptionCandidate): void;onOpenDiscoveredConfiguration(item: ComputeScanItem): void;}) {- const configurations = computeItems.filter(item => item.connection_option_id);+ const configurations = computeItems.filter(item => item.connection_option_id || item.native_provider_id);const detectedAgents = agents.filter(agent => agent.configuration_state !== 'not_found_in_scope');const text = (zh: string, en: string) => language === 'zh' ? zh : en;return <div className="oc-scan-list">@@ -146,10 +148,10 @@ export function DeviceScanList({{subscriptionScanFailed && <div className="callout bad" role="alert"><UiIcon name="warning" /><span>{text('暂时无法读取本机 Codex 订阅。', 'The local Codex subscription could not be read.')}</span></div>}<h3 className="oc-section-label">{text('Agent 中的模型配置', 'Model configurations in agents')}</h3>- {configurations.map(item => <div className="oc-status-row" key={`${item.agent_id}:${item.connection_option_id}:${item.observed_model_id ?? 'unknown'}`}>+ {configurations.map(item => <div className="oc-status-row" key={item.discovery?.discovery_ref ?? `${item.agent_id}:${item.native_provider_id ?? item.connection_option_id}:${item.observed_model_id ?? 'unknown'}`}><BrandIcon kind={agentBrandFromId(item.agent_id)} label={agentName(item.agent_id, language)} /><div className="row-main">- <strong>{connectionName(item.connection_option_id, language)}</strong>+ <strong>{item.native_provider_id ?? connectionName(item.connection_option_id, language)}</strong><p>{agentName(item.agent_id, language)} · {configurationMessage(item, language)}</p></div>{item.discovery && item.inventory_eligiblediff --git a/apps/desktop/src/features/worker-dependencies-state.ts b/apps/desktop/src/features/worker-dependencies-state.tsindex b7d11213..9c06cfc0 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';+export type WorkerHarness = 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi';export type WorkerDependencyComponent = 'cli' | 'adapter' | 'node';export type WorkerDependencyCandidateState = 'found' | 'missing' | 'invalid' | 'unavailable';@@ -37,14 +37,14 @@ export type WorkerDependencySelectionRequest = WorkerDependencySelection & {};export function workerDependencyComponents(harness: WorkerHarness): WorkerDependencyComponent[] {- return harness === 'qoder_cli' ? ['cli'] : ['cli', 'adapter', 'node'];+ return harness === 'qoder_cli' ? ['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'? selection.adapter_path == null && selection.node_path == null- : Boolean(selection.adapter_path);+ : selection.harness === 'pi' ? selection.adapter_path == null && Boolean(selection.node_path) : Boolean(selection.adapter_path);}export type WorkerMachineEnvelope<T> = {@@ -105,7 +105,7 @@ export function recommendedWorkerDependencies(harness,cli_path: found('cli')?.path ?? '',...(harness === 'qoder_cli' ? {} : {- adapter_path: found('adapter')?.path ?? '',+ ...(harness === 'pi' ? {} : { adapter_path: found('adapter')?.path ?? '' }),node_path: found('node')?.path ?? null,}),expected_selection_revision: workerDependencyRevision(view, harness),@@ -123,13 +123,13 @@ export function workerDependencySelectionState(&& candidate.component === component&& candidate.path === path)?.state: undefined;- const nodeRequired = harness !== 'qoder_cli' && (Boolean(request.node_path)+ const nodeRequired = harness === 'pi' || harness !== 'qoder_cli' && (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' || fact('adapter', request.adapter_path) === 'found')+ && (harness === 'qoder_cli' || 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 5e36ed42..3b9f3fe0 100644--- a/apps/desktop/src/plan-editor.tsx+++ b/apps/desktop/src/plan-editor.tsx@@ -16,7 +16,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'; protocol: 'responses' | 'messages' };+type Work = { harness: 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi'; protocol: 'responses' | 'messages' };type ClassifierAuthHeader = { name: string; value_secret_ref: string };type SmartClassifier = { kind: 'local_rules' } | {kind: 'rest';@@ -109,7 +109,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; usedBy?: { id: string; name: string; brand: 'codex' | 'claude-code' | 'qoder' | '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, 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; 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, 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());@@ -482,8 +482,9 @@ 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')],+ ['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={() => update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } })}><BrandIcon kind={value === 'codex_cli' ? 'codex' : value === 'claude_code' ? 'claude-code' : '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>}+ ] 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={() => 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 && <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/ui/BrandIcon.tsx b/apps/desktop/src/ui/BrandIcon.tsxindex b0e82ef9..88c061f8 100644--- a/apps/desktop/src/ui/BrandIcon.tsx+++ b/apps/desktop/src/ui/BrandIcon.tsx@@ -5,14 +5,16 @@ import codexDark from './assets/codex-dark.png?inline';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';-export type BrandKind = 'codex' | 'claude-code' | 'qoder' | 'agent' | 'model';+export type BrandKind = 'codex' | 'claude-code' | 'qoder' | 'pi' | '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_pi_default') return 'pi';return 'agent';}@@ -47,9 +49,9 @@ export function BrandIcon({);}- if (kind === 'qoder') {- return <span className={classes} data-size={size} data-brand="qoder" {...accessibility}>- <img src={qoder} alt="" />+ if (kind === 'qoder' || kind === 'pi') {+ return <span className={classes} data-size={size} data-brand={kind} {...accessibility}>+ <img src={kind === 'pi' ? pi : qoder} alt="" /></span>;}diff --git a/apps/desktop/src/ui/assets/pi.svg b/apps/desktop/src/ui/assets/pi.svgnew file mode 100644index 00000000..58e2e3a0--- /dev/null+++ b/apps/desktop/src/ui/assets/pi.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800">+ <path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/>+ <path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/>+ <path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/>+</svg>diff --git a/apps/desktop/tests/agent-settings-request.test.mjs b/apps/desktop/tests/agent-settings-request.test.mjsindex 74956d84..5a7137fe 100644--- a/apps/desktop/tests/agent-settings-request.test.mjs+++ b/apps/desktop/tests/agent-settings-request.test.mjs@@ -117,29 +117,31 @@ test('collaboration-only Qoder and cross-ecosystem selections cannot authorize m}});-test('Qoder adds only selected routes and keeps token rotation and both restores independent', () => {- const capable = { ...qoder, settings: { state: 'not_configured', collaboration: qoder.settings.collaboration } };+for (const ecosystem of ['qoder', 'pi']) 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 } };const configure = wire(agentSettingsSpec(capable, 'model', false, draft));assert.deepEqual(configure, {- schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',- model: { intent: 'configure', settings: { mode: 'qoder_additional', allowed_plan_ids: ['route/b', 'route/a'] } },+ schema_version: { major: 2, minor: 0 }, context_id: `context/${ecosystem}`,+ model: { intent: 'configure', settings: { mode: `${ecosystem}_additional`, allowed_plan_ids: ['route/b', 'route/a'] } },collaboration: { intent: 'keep' },});const saved = { ...capable, settings: {- state: 'configured', current_selection: configure.model.settings, restore_point_ref: 'restore/qoder-model',- collaboration: qoder.settings.collaboration,+ state: 'configured', current_selection: configure.model.settings, restore_point_ref: `restore/${ecosystem}-model`,+ collaboration: native.settings.collaboration,} };assert.deepEqual(agentTokenSpec(saved, true), {- schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',+ schema_version: { major: 2, minor: 0 }, context_id: `context/${ecosystem}`,model: configure.model, collaboration: { intent: 'keep' }, access_token: { intent: 'regenerate' },});assert.deepEqual(wire(agentSettingsSpec(saved, 'model', true, draft)), {- schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',- model: { intent: 'restore', restore_point_ref: 'restore/qoder-model' }, collaboration: { intent: 'keep' },+ schema_version: { major: 2, minor: 0 }, context_id: `context/${ecosystem}`,+ model: { intent: 'restore', restore_point_ref: `restore/${ecosystem}-model` }, collaboration: { intent: 'keep' },});assert.deepEqual(wire(agentSettingsSpec(saved, 'collaboration', true, draft)), {- schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',- model: { intent: 'keep' }, collaboration: { intent: 'restore', restore_point_ref: 'restore/qoder-skill' },+ schema_version: { major: 2, minor: 0 }, context_id: `context/${ecosystem}`,+ model: { intent: 'keep' }, collaboration: { intent: 'restore', restore_point_ref: `restore/${ecosystem}-skill` },});for (const agent of [codex, claude]) {const mixed = { ...agent, settings: saved.settings };diff --git a/apps/desktop/tests/worker-dependencies-state.test.mjs b/apps/desktop/tests/worker-dependencies-state.test.mjsindex e389d959..6dc5b467 100644--- a/apps/desktop/tests/worker-dependencies-state.test.mjs+++ b/apps/desktop/tests/worker-dependencies-state.test.mjs@@ -90,6 +90,27 @@ test('a CLI alone remains incomplete for Codex and Claude adapter installations'}});+test('Pi uses its selected CLI and Node without an external adapter and never replaces a missing saved Node', () => {+ const selection = { harness: 'pi', cli_path: '/selected/pi', node_path: '/selected/node' };+ const detected = view({ selection_revisions: [{ harness: 'pi', revision: 3 }], candidates: [+ { harness: 'pi', component: 'cli', path: selection.cli_path, source: 'path', state: 'found' },+ { harness: 'pi', component: 'node', path: selection.node_path, source: 'path', state: 'found' },+ ] });+ const request = recommendedWorkerDependencies(detected, 'pi');+ assert.deepEqual(request, { ...selection, expected_selection_revision: 3 });+ assert.deepEqual(workerDependencyComponents('pi'), ['cli', 'node']);+ assert.equal(workerDependencySelectionState(detected, 'pi'), 'found');+ assert.equal(workerDependencySelectionComplete({ ...selection, node_path: null }), false);+ assert.equal(workerDependencySelectionComplete({ ...selection, adapter_path: '/foreign/adapter' }), false);+ const saved = { ...detected, selected: [selection] };+ assert.equal(workerDependencySelectionState(saved, 'pi'), 'configured');+ saved.candidates = [detected.candidates[0],+ { ...detected.candidates[1], state: 'missing' },+ { harness: 'pi', component: 'node', path: '/other/node', source: 'path', state: 'found' }];+ assert.equal(workerDependencySelectionState(saved, 'pi'), 'incomplete');+ assert.deepEqual(recommendedWorkerDependencies(saved, 'pi'), request);+});+test('an explicit selected path remains authoritative even when another candidate is found', () => {const selected = {harness: 'codex_cli',diff --git a/assets/agent-profiles/current/profile-seed.json b/assets/agent-profiles/current/profile-seed.jsonindex 9c2b344f..a1a9b172 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":"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":"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 56a58ecc..8d05ab49 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":"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":"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 3cddc4fb..80b36d7b 100644--- a/contracts/cli/agent-plan-catalog-query.v2.schema.json+++ b/contracts/cli/agent-plan-catalog-query.v2.schema.json@@ -441,7 +441,8 @@"enum": ["codex_cli","claude_code",- "qoder_cli"+ "qoder_cli",+ "pi"]},"protocol": {diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.jsonindex 46d419f9..964ec251 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:2341c620bb43c9738ff1d639fa7057ecd301ee2799584ac35b1662137fc92754",+ "agent-plan-catalog-query.v2.schema.json": "sha256:fae6bcd7e9ed4ab480c2bfe055d7bb3422977b7748374d6063c100eb7db4bff4","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:d74a6e9af374cf7d505afc1e9f1d15b47e2bc42f841030f347120407a1c33d39",- "plan-draft-change.v1.schema.json": "sha256:780afb152b88f0e17a3b1acce955d3b2329fbc385b56575c50b594a023485ca5",- "plan-editor.v2.schema.json": "sha256:9083d469b1fdb957dd176cdf48e4acd63e9a74938366d4890fb618e2c03726de",- "plan-lifecycle-change.v1.schema.json": "sha256:eb54a14f53f0e0a15463be1053b9b8f2f349b643ac9c9037cf879cfda26d05b5",+ "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","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:0f164b8dddc097c0f5e88e8fcfa38dba4e6702b018413b55673da7d9a0606a0a",- "worker-dependencies-select-request.v1.schema.json": "sha256:6e3e231fe506812128c73a18752699d7e5869fba80d92bdc187b003daa67f55c",+ "worker-dependencies-discover-request.v1.schema.json": "sha256:383af1b2f41e8d5210a1a8f77238dcc54938868846bb472fdb5d9dcc5e5ca61d",+ "worker-dependencies-select-request.v1.schema.json": "sha256:af583e55e3199755fc6e7a7248fa07672e120273a0d5e81792cc1687e897e91e","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 f680eede..cdc73585 100644--- a/contracts/cli/plan-content-change.v2.schema.json+++ b/contracts/cli/plan-content-change.v2.schema.json@@ -441,7 +441,8 @@"enum": ["codex_cli","claude_code",- "qoder_cli"+ "qoder_cli",+ "pi"]},"protocol": {diff --git a/contracts/cli/plan-draft-change.v1.schema.json b/contracts/cli/plan-draft-change.v1.schema.jsonindex 4f638e0b..cd56396e 100644--- a/contracts/cli/plan-draft-change.v1.schema.json+++ b/contracts/cli/plan-draft-change.v1.schema.json@@ -441,7 +441,8 @@"enum": ["codex_cli","claude_code",- "qoder_cli"+ "qoder_cli",+ "pi"]},"protocol": {diff --git a/contracts/cli/plan-editor.v2.schema.json b/contracts/cli/plan-editor.v2.schema.jsonindex aa2b7799..5fbae689 100644--- a/contracts/cli/plan-editor.v2.schema.json+++ b/contracts/cli/plan-editor.v2.schema.json@@ -441,7 +441,8 @@"enum": ["codex_cli","claude_code",- "qoder_cli"+ "qoder_cli",+ "pi"]},"protocol": {diff --git a/contracts/cli/plan-lifecycle-change.v1.schema.json b/contracts/cli/plan-lifecycle-change.v1.schema.jsonindex aed9d170..0b5bb681 100644--- a/contracts/cli/plan-lifecycle-change.v1.schema.json+++ b/contracts/cli/plan-lifecycle-change.v1.schema.json@@ -441,7 +441,8 @@"enum": ["codex_cli","claude_code",- "qoder_cli"+ "qoder_cli",+ "pi"]},"protocol": {diff --git a/contracts/cli/worker-dependencies-discover-request.v1.schema.json b/contracts/cli/worker-dependencies-discover-request.v1.schema.jsonindex 7da5572f..230c3f0d 100644--- a/contracts/cli/worker-dependencies-discover-request.v1.schema.json+++ b/contracts/cli/worker-dependencies-discover-request.v1.schema.json@@ -7,7 +7,8 @@"enum": ["codex_cli","claude_code",- "qoder_cli"+ "qoder_cli",+ "pi"]}},diff --git a/contracts/cli/worker-dependencies-select-request.v1.schema.json b/contracts/cli/worker-dependencies-select-request.v1.schema.jsonindex f196d54f..ab7326d6 100644--- a/contracts/cli/worker-dependencies-select-request.v1.schema.json+++ b/contracts/cli/worker-dependencies-select-request.v1.schema.json@@ -3,9 +3,26 @@"$schema": "https://json-schema.org/draft/2020-12/schema","additionalProperties": false,"else": {- "required": [- "adapter_path"- ]+ "else": {+ "required": [+ "adapter_path"+ ]+ },+ "if": {+ "properties": {+ "harness": {+ "const": "pi"+ }+ }+ },+ "then": {+ "properties": {+ "adapter_path": false+ },+ "required": [+ "node_path"+ ]+ }},"if": {"properties": {@@ -34,7 +51,8 @@"enum": ["codex_cli","claude_code",- "qoder_cli"+ "qoder_cli",+ "pi"]},"node_path": {diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.jsonindex 8587bc1b..0386c7b4 100644--- a/contracts/compatibility-support.v1.json+++ b/contracts/compatibility-support.v1.json@@ -244,6 +244,12 @@"hiroute.operation-step/v1","hiroute.operation-view/v1","hiroute.otel.gen-ai-mapping/v1",+ "hiroute.pi-additional-model/v1",+ "hiroute.pi-local-cli/v1",+ "hiroute.pi-native-resources/v1",+ "hiroute.pi-native-restore/v1",+ "hiroute.pi-sdk-capability/v1",+ "hiroute.pi-worker-failure/v1","hiroute.plan-authoring/v2","hiroute.plan-content-change/v2","hiroute.plan-content-preview/v2",@@ -302,6 +308,7 @@"hiroute.settings-codex-model-file/v1","hiroute.settings-login-item/v1","hiroute.settings-model-publication/v1",+ "hiroute.settings-pi-model-file/v1","hiroute.settings-qoder-model-file/v1","hiroute.settings-service-completion/v2","hiroute.settings-service-proof/v2",@@ -987,14 +994,16 @@},{"contract": "hiroute.worker-dependency-selection-confirmation/v1",- "field": "schema23 selection/effect constraints and original Operation journal bytes",+ "field": "stable schema23/24/25 selection/effect constraints and original Operation journal bytes","mode": "recovery_read_only","owner": "local-storage",- "reason": "Accept only marked stable schema23 through the existing complete three-store backup coordinator; schema24 expands harness constraints without reserializing selections, effects or Operation journals. Interrupted 23/24 sets require validated source backup, identities, key and migration phase.",- "removal_condition": "End schema23 upgrade support only by an explicit product decision that preserves a documented usable recovery path for supported stores and backups.",+ "reason": "Upgrade marked stable schema23/24/25 through the complete three-store backup coordinator; schema26 adds the Pi SDK launch shape without reserializing selection/effect or Operation bytes. Interrupted steps require a contiguous committed ledger, exact source backup, identities, key and phase.",+ "removal_condition": "End marked schema23/24/25 upgrade support only through an explicit product decision preserving a usable supported recovery path.","allowed_paths": ["crates/local-storage/src/migrations/startup_format.rs",- "crates/local-storage/src/migrations/worker_dependencies_v24.rs"+ "crates/local-storage/src/migrations/worker_dependencies_v24.rs",+ "crates/local-storage/src/migrations/worker_dependencies_v26.rs",+ "crates/local-storage/src/migrations/mod.rs"]},{diff --git a/crates/application-api/src/agent_settings.rs b/crates/application-api/src/agent_settings.rsindex 6a0040c0..8932f0fe 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::PiAdditional { .. } => *surface == AgentModelSurfaceV2::PiCli,AgentModelSelectionV2::QoderAdditional { .. } => {*surface == AgentModelSurfaceV2::QoderCli}diff --git a/crates/application-api/src/compute_control.rs b/crates/application-api/src/compute_control.rsindex 18525518..de3e1ee1 100644--- a/crates/application-api/src/compute_control.rs+++ b/crates/application-api/src/compute_control.rs@@ -69,6 +69,8 @@ impl ComputeDiscoveryRefV1 {pub struct ComputeScanItemV1 {pub agent_id: String,pub supported: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub native_provider_id: Option<String>,pub configuration_state: String,#[serde(default, skip_serializing_if = "Option::is_none")]pub discovered_source_ref: Option<String>,diff --git a/crates/application-api/src/generated/plan_authoring.rs b/crates/application-api/src/generated/plan_authoring.rsindex fe854e93..82194d4f 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"]},"protocol":{"enum":["responses","messages"]}}))+ "work":object(&["harness","protocol"],json!({"harness":{"enum":["codex_cli","claude_code","qoder_cli","pi"]},"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 decadaab..2d1460f4 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"]}}+ "properties": {"harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi"]}}})}@@ -251,7 +251,7 @@ pub(super) fn dependencies_select() -> Value {"additionalProperties": false,"required": ["harness", "cli_path", "expected_selection_revision"],"properties": {- "harness": {"enum": ["codex_cli", "claude_code", "qoder_cli"]},+ "harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi"]},"adapter_path": {"type": "string", "minLength": 1, "maxLength": 4096},"cli_path": {"type": "string", "minLength": 1, "maxLength": 4096},"node_path": {"type": "string", "minLength": 1, "maxLength": 4096},@@ -259,6 +259,8 @@ pub(super) fn dependencies_select() -> Value {},"if": {"properties": {"harness": {"const": "qoder_cli"}}},"then": {"properties": {"adapter_path": false, "node_path": false}},- "else": {"required": ["adapter_path"]}+ "else": {"if": {"properties": {"harness": {"const": "pi"}}},+ "then": {"required": ["node_path"], "properties": {"adapter_path": false}},+ "else": {"required": ["adapter_path"]}}})}diff --git a/crates/application-api/src/worker.rs b/crates/application-api/src/worker.rsindex 4c77c27b..bc1a1bc2 100644--- a/crates/application-api/src/worker.rs+++ b/crates/application-api/src/worker.rs@@ -131,6 +131,7 @@ pub fn plan_worker_dependency_selection(WorkerHarnessV1::CodexCli => "codex_cli",WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",+ WorkerHarnessV1::Pi => "pi",};let spec = ChangeSpecV1 {schema_version: CHANGE_SPEC_SCHEMA_V1,@@ -376,10 +377,11 @@ pub struct WorkerExecutorAvailabilityListV1 {impl WorkerExecutorAvailabilityListV1 {pub fn valid(&self) -> bool {self.schema == WORKER_EXECUTOR_AVAILABILITY_SCHEMA_V1- && self.executors.len() == 3+ && self.executors.len() == 4&& 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.iter()@@ -1149,7 +1151,7 @@ mod tests {}#[test]- fn executor_availability_is_exactly_three_capability_scoped_harnesses() {+ fn executor_availability_lists_all_supported_capability_scoped_harnesses() {let ready = WorkerExecutorCapabilityAvailabilityV1 {state: WorkerExecutorAvailabilityStateV1::Ready,reason: None,@@ -1177,6 +1179,7 @@ mod tests {executor(WorkerHarnessV1::CodexCli),executor(WorkerHarnessV1::ClaudeCode),executor(WorkerHarnessV1::QoderCli),+ executor(WorkerHarnessV1::Pi),],};assert!(response.valid());diff --git a/crates/application-api/src/worker_selection_tests.rs b/crates/application-api/src/worker_selection_tests.rsindex aa00dcd7..f17263b2 100644--- a/crates/application-api/src/worker_selection_tests.rs+++ b/crates/application-api/src/worker_selection_tests.rs@@ -10,14 +10,22 @@ fn generated_schema(path: &str) -> serde_json::Value {serde_json::from_str(&file.contents).unwrap()}+// Resolve a harness form by its discriminator, rather than a conditional's nesting depth.+fn harness_rule<'a>(+ schema: &'a serde_json::Value,+ harness: &serde_json::Value,+) -> &'a serde_json::Value {+ let mut rule = schema;+ while let Some(condition) = rule.get("if") {+ let selected = condition["properties"]["harness"]["const"] == *harness;+ rule = &rule[if selected { "then" } else { "else" }];+ }+ rule+}+#[test]fn saved_adapter_selections_preserve_json_and_confirmation_identity() {let schema = generated_schema("worker-dependencies-select-request.v1.schema.json");- // Adapter-based clients keep their required adapter in the published conditional schema.- assert_eq!(- schema["else"]["required"],- serde_json::json!(["adapter_path"])- );// Frozen V1 payloads and independently calculated canonical SHA-256 values. The expected// side deliberately does not serialize the current producer or call its digest algorithm.let cases = [@@ -49,9 +57,10 @@ fn saved_adapter_selections_preserve_json_and_confirmation_identity() {for (request_json, selection_json, accepted, idempotency) in cases {let request: WorkerDependenciesSelectRequestV1 =serde_json::from_str(request_json).unwrap();- assert_ne!(- schema["if"]["properties"]["harness"]["const"],- serde_json::to_value(request.harness).unwrap()+ // Adapter-based clients keep the required adapter, regardless of native forms added.+ assert_eq!(+ harness_rule(&schema, &serde_json::to_value(request.harness).unwrap())["required"],+ serde_json::json!(["adapter_path"]));assert_eq!(serde_json::to_string(&request).unwrap(), request_json);let plan = plan_worker_dependency_selection(&request).unwrap();@@ -83,11 +92,7 @@ fn native_acp_requires_only_cli_and_rejects_cross_form_fields() {serde_json::json!(["harness", "cli_path", "expected_selection_revision"]));assert_eq!(- schema["if"]["properties"]["harness"]["const"],- serde_json::to_value(request.harness).unwrap()- );- assert_eq!(- schema["then"]["properties"],+ 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);@@ -136,7 +141,7 @@ 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"]);+ let expected = serde_json::json!(["codex_cli", "claude_code", "qoder_cli", "pi"]);for declared in [&discover["properties"]["harness"]["enum"],&select["properties"]["harness"]["enum"],diff --git a/crates/application/src/agent_connection/qoder_model_journal.rs b/crates/application/src/agent_connection/additional_model_journal.rssimilarity index 54%rename from crates/application/src/agent_connection/qoder_model_journal.rsrename to crates/application/src/agent_connection/additional_model_journal.rsindex 2fb63a72..9c70079d 100644--- a/crates/application/src/agent_connection/qoder_model_journal.rs+++ b/crates/application/src/agent_connection/additional_model_journal.rs@@ -1,23 +1,38 @@//! Non-secret additive Qoder model effects, bound to one settings Operation.use hiroute_domain::{- AgentConnectionControlIntentV1, AgentConnectionEffectRoleV1, AgentConnectionTransactionKindV1,- AgentFacetIntent, AgentIngressProtocolV1, AgentModelGrantV2, AgentModelRouteV2,- AgentModelSelectionV2, AgentOperationRead, AgentSettingsSpecV2, CanonicalDigest,- ExternalEffectIntentV1, OperationId, OperationValidationError, PortError, PortErrorCode,- PortResult, QoderAdditionalModelV1,+ AdditionalAgentModelV1, AgentConnectionControlIntentV1, AgentConnectionEffectRoleV1,+ AgentConnectionTransactionKindV1, AgentFacetIntent, AgentIngressProtocolV1, AgentKindV1,+ AgentModelGrantV2, AgentModelRouteV2, AgentModelSelectionV2, AgentOperationRead,+ AgentSettingsSpecV2, CanonicalDigest, ExternalEffectIntentV1, OperationId,+ OperationValidationError, PortError, PortErrorCode, PortResult,};use serde::{Deserialize, Serialize};-const SCHEMA: &str = "hiroute.settings-qoder-model-file/v1";+const QODER_SCHEMA: &str = "hiroute.settings-qoder-model-file/v1";+const PI_SCHEMA: &str = "hiroute.settings-pi-model-file/v1";++pub fn additional_model_kind(intent: &ExternalEffectIntentV1) -> PortResult<AgentKindV1> {+ match intent.desired()["subject"]["agent_id"].as_str() {+ Some("agent_qoder_default") => Ok(AgentKindV1::Qoder),+ Some("agent_pi_default") => Ok(AgentKindV1::Pi),+ _ => Err(invalid()),+ }+}+fn schema(kind: AgentKindV1) -> &'static str {+ match kind {+ AgentKindV1::Pi => PI_SCHEMA,+ _ => QODER_SCHEMA,+ }+}#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]-pub enum QoderModelFileAction {+pub enum AdditionalModelFileAction {Configure {previous_operation: Option<OperationId>,provider_id: String,endpoint: String,- models: Vec<QoderAdditionalModelV1>,+ models: Vec<AdditionalAgentModelV1>,},Restore {original_operation: OperationId,@@ -26,34 +41,43 @@ pub enum QoderModelFileAction {#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(deny_unknown_fields)]-pub struct QoderModelFilePayload {+pub struct AdditionalModelFilePayload {schema: String,pub context_id: String,pub expected_content: CanonicalDigest,- pub change: QoderModelFileAction,+ pub change: AdditionalModelFileAction,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pi_settings_content: Option<CanonicalDigest>,}/// A stable, context-owned namespace. It never adopts an existing unowned provider.-pub fn qoder_model_provider_id(context_id: &str) -> String {+pub fn additional_model_provider_id(context_id: &str) -> String {let digest = CanonicalDigest::of_bytes(context_id.as_bytes());format!("hiroute-main-{}", &digest.as_str()[7..])}-pub fn settings_qoder_model_file_intent(+pub fn settings_additional_model_file_intent(control: &AgentConnectionControlIntentV1,context_id: &str,expected_content: CanonicalDigest,before_fingerprint: Option<CanonicalDigest>,- change: QoderModelFileAction,+ change: AdditionalModelFileAction,+ pi_settings_content: Option<CanonicalDigest>,) -> Result<ExternalEffectIntentV1, OperationValidationError> {if control.transaction() != AgentConnectionTransactionKindV1::Settings {return Err(OperationValidationError::UnregisteredEffectPlan);}- let payload = QoderModelFilePayload {- schema: SCHEMA.into(),+ let payload = AdditionalModelFilePayload {+ schema: schema(if control.subject().agent_id() == "agent_pi_default" {+ AgentKindV1::Pi+ } else {+ AgentKindV1::Qoder+ })+ .into(),context_id: context_id.into(),expected_content,change,+ pi_settings_content,};let intent = ExternalEffectIntentV1::from_agent_connection_planner(control,@@ -62,14 +86,14 @@ pub fn settings_qoder_model_file_intent(&payload,0o600,)?;- decode_settings_qoder_model_file(&intent)+ decode_settings_additional_model_file(&intent).map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;Ok(intent)}-pub fn decode_settings_qoder_model_file(+pub fn decode_settings_additional_model_file(intent: &ExternalEffectIntentV1,-) -> PortResult<QoderModelFilePayload> {+) -> PortResult<AdditionalModelFilePayload> {ExternalEffectIntentV1::from_registered_adapter(intent.effect_id(),intent.kind(),@@ -81,47 +105,70 @@ pub fn decode_settings_qoder_model_file().map_err(|_| invalid())?;let value = intent.desired();+ let kind = additional_model_kind(intent)?;+ let (agent, profile, integration) = match kind {+ AgentKindV1::Pi => (+ "agent_pi_default",+ "pi-responses-v1",+ "builtin/pi-responses/v1",+ ),+ _ => (+ "agent_qoder_default",+ "qoder-collaboration-v1",+ "builtin/qoder-collaboration/v1",+ ),+ };if intent.effect_id() != "agent-connection-managed-configuration"|| intent.desired_mode() != 0o600|| value["transaction"] != "settings"- || value["subject"]["agent_id"] != "agent_qoder_default"- || value["subject"]["profile_id"] != "qoder-collaboration-v1"- || value["subject"]["integration_profile_ref"] != "builtin/qoder-collaboration/v1"+ || value["subject"]["agent_id"] != agent+ || value["subject"]["profile_id"] != profile+ || value["subject"]["integration_profile_ref"] != integration{return Err(invalid());}- let payload: QoderModelFilePayload =+ let payload: AdditionalModelFilePayload =serde_json::from_value(value["payload"].clone()).map_err(|_| invalid())?;- if payload.schema != SCHEMA || !super::settings::identity(&payload.context_id) {+ if payload.schema != schema(kind)+ || (kind == AgentKindV1::Pi) != payload.pi_settings_content.is_some()+ || !super::settings::identity(&payload.context_id)+ {return Err(invalid());}match &payload.change {- QoderModelFileAction::Configure {+ AdditionalModelFileAction::Configure {provider_id,endpoint,models,..} => {- if provider_id != &qoder_model_provider_id(&payload.context_id)- || !local_endpoint(endpoint)+ if provider_id != &additional_model_provider_id(&payload.context_id)+ || !local_endpoint(endpoint, kind)|| models.is_empty()|| models.len() > 256- || models.iter().any(|model| model.validate().is_err())+ || models.iter().any(|model| {+ (if kind == AgentKindV1::Pi {+ model.validate_pi()+ } else {+ model.validate()+ })+ .is_err()+ })|| models.windows(2).any(|pair| pair[0].alias >= pair[1].alias){return Err(invalid());}}- QoderModelFileAction::Restore { .. } => {}+ AdditionalModelFileAction::Restore { .. } => {}}Ok(payload)}-pub fn settings_qoder_model_file_for_operation(+pub fn settings_additional_model_file_for_operation(operation: &(impl AgentOperationRead + ?Sized),intent: &ExternalEffectIntentV1,-) -> PortResult<QoderModelFilePayload> {- let payload = decode_settings_qoder_model_file(intent)?;+) -> PortResult<AdditionalModelFilePayload> {+ let payload = decode_settings_additional_model_file(intent)?;let spec: AgentSettingsSpecV2 =serde_json::from_value(operation.agent_input().spec.desired_state.clone()).map_err(|_| invalid())?;@@ -138,17 +185,29 @@ pub fn settings_qoder_model_file_for_operation({return Err(invalid());}+ let kind = additional_model_kind(intent)?;match (&spec.model, &payload.change) {(AgentFacetIntent::Configure {- settings: AgentModelSelectionV2::QoderAdditional { allowed_plan_ids },+ settings:+ AgentModelSelectionV2::QoderAdditional { allowed_plan_ids }+ | AgentModelSelectionV2::PiAdditional { allowed_plan_ids },},- QoderModelFileAction::Configure {+ AdditionalModelFileAction::Configure {previous_operation,models,..},) => {+ if matches!(+ &spec.model,+ AgentFacetIntent::Configure {+ settings: AgentModelSelectionV2::PiAdditional { .. }+ }+ ) != (kind == AgentKindV1::Pi)+ {+ return Err(invalid());+ }let grant: AgentModelGrantV2 =serde_json::from_value(state["model_grant"].clone()).map_err(|_| invalid())?;let [mutation] = operation.agent_input().grants else {@@ -163,7 +222,7 @@ pub fn settings_qoder_model_file_for_operation(}(AgentFacetIntent::Restore { restore_point_ref },- QoderModelFileAction::Restore { original_operation },+ AdditionalModelFileAction::Restore { original_operation },) if original_operation != operation.operation_id()&& *restore_point_ref == super::codex_model_restore_point_ref(original_operation) => {}_ => return Err(invalid()),@@ -171,11 +230,17 @@ pub fn settings_qoder_model_file_for_operation(Ok(payload)}-fn local_endpoint(value: &str) -> bool {+fn local_endpoint(value: &str, kind: AgentKindV1) -> bool {value.strip_prefix("http://127.0.0.1:").or_else(|| value.strip_prefix("http://[::1]:"))- .and_then(|rest| rest.strip_suffix(hiroute_domain::QODER_MODEL_BASE_PATH))+ .and_then(|rest| {+ rest.strip_suffix(if kind == AgentKindV1::Pi {+ "/v1"+ } else {+ hiroute_domain::QODER_MODEL_BASE_PATH+ })+ }).is_some_and(|port| {!port.is_empty()&& port.bytes().all(|b| b.is_ascii_digit())diff --git a/crates/application/src/agent_connection/control.rs b/crates/application/src/agent_connection/control.rsindex fa591624..a9c1a6b5 100644--- a/crates/application/src/agent_connection/control.rs+++ b/crates/application/src/agent_connection/control.rs@@ -64,9 +64,12 @@ pub(crate) fn check("agent_claude_default" => {target.surface != hiroute_application_api::AgentModelSurfaceV2::ClaudeCli}- "agent_qoder_default" => {- target.surface != hiroute_application_api::AgentModelSurfaceV2::QoderCli- }+ "agent_qoder_default" => !matches!(+ target.surface,+ hiroute_application_api::AgentModelSurfaceV2::QoderCli+ | hiroute_application_api::AgentModelSurfaceV2::PiCli+ ),+ "agent_pi_default" => true, // No public per-surface model probe for this integration._ => true,}{diff --git a/crates/application/src/agent_connection/mod.rs b/crates/application/src/agent_connection/mod.rsindex f03010c4..11ef7de2 100644--- a/crates/application/src/agent_connection/mod.rs+++ b/crates/application/src/agent_connection/mod.rs@@ -1,12 +1,12 @@//! Typed AgentConnection Preview and Apply-plan sealing.+mod additional_model_journal;mod claude_model_journal;pub(crate) mod collaboration_check;pub(crate) mod control;mod login_item;mod model_journal;mod planner;-mod qoder_model_journal;mod restore;mod revocation;mod settings;@@ -14,11 +14,11 @@ mod settings_input;mod skill;mod wire;+pub use additional_model_journal::*;pub use claude_model_journal::*;pub use login_item::*;pub use model_journal::*;pub use planner::*;-pub use qoder_model_journal::*;pub use restore::*;pub use revocation::*;pub use settings::*;diff --git a/crates/application/src/agent_connection/settings.rs b/crates/application/src/agent_connection/settings.rsindex 2aa07097..abbc03e0 100644--- a/crates/application/src/agent_connection/settings.rs+++ b/crates/application/src/agent_connection/settings.rs@@ -21,51 +21,8 @@ pub struct AgentSettingsFacts {pub restore_points: BTreeMap<String, AgentSettingsFacet>,}-pub struct SettingsModelFacts {- /// A closed native field conflict; only Qoder model changes consume this fact.- pub qoder_model_conflict: Option<SettingsBlockReason>,- pub codex_context_override: bool,- pub claude_context_override: bool,- pub claude_plan_capability_unavailable: bool,- pub ingress: AgentIngressProtocolV1,- pub available_surfaces: BTreeSet<hiroute_domain::AgentModelSurfaceV2>,- pub model_publication: Option<GatewayPublicationV1>,- /// The immutable model catalog artifact for a plan-carrying Codex selection; built by the- /// backend from a structurally valid full-catalog source and the merged permitted plans.- /// Absent when that catalog cannot be derived without losing source fidelity.- pub model_catalog: Option<SettingsModelCatalogFacts>,- /// True when this apply configures the model facet while no managed connection holds an- /// active grant anywhere: the first resident-service connection, which requires the host- /// to establish the login item before the Operation is sealed.- pub login_item_required: bool,- /// True when this restore removes the last managed connection while journal evidence- /// proves this feature owns the login item: the host must unregister that owned item as- /// part of the restore. A pre-existing user login item is never owned and never removed.- pub login_item_removal_required: bool,- pub fixed_candidate_facts: Vec<crate::compiler::CandidateCompilationFactV1>,- /// Native Codex source/account bindings established at initial adoption and carried through- /// subsequent full-state edits. Explicit replacements are rejected by the coverage check.- pub preserved_codex_models: Vec<hiroute_domain::AgentFixedModelSelectionV2>,- /// Sealed fixed routes for protected names. These remain usable for a Plan edit even if the- /// source is temporarily absent from the current discovery snapshot.- pub preserved_codex_bindings: BTreeMap<String, hiroute_domain::AttemptOwnedCandidateV1>,- /// Original names proven usable on the same account and retained for this selection.- pub required_native_model_ids: Option<Vec<String>>,- /// Names in Codex metadata without a proven same-account route, shown as guidance only.- pub unproven_native_model_ids: Vec<String>,- /// The user chose to keep proven native names alongside HiRoute routes.- pub require_native_model_routes: bool,- /// Preserving the native default requires an exact proven route for that name.- pub native_default_must_be_original: bool,- pub native_default_model: Option<String>,- /// Original directory for a Codex restore, never the HiRoute merged catalog.- pub restore_native_model_ids: Option<Vec<String>>,- /// A standalone file restores absence and inherits root; it never validates root's models.- pub restore_inherits_root: bool,- /// Model that an unmodified restore would leave in the native configuration.- pub restored_native_model: Option<String>,- pub native_claude_presets: Option<hiroute_domain::AgentClaudePresetValuesV2>,-}+mod model_facts;+pub use model_facts::*;#[derive(Clone, Debug, Eq, PartialEq, Serialize)]pub struct SettingsModelCatalogFacts {@@ -119,6 +76,7 @@ pub struct AgentSettingsBlock {#[serde(rename_all = "snake_case")]pub enum SettingsBlockReason {QoderDefaultInUse,+ AdditionalDefaultInUse,QoderModelFileConflict,CodexContextOverride,ClaudeContextOverride,@@ -174,7 +132,7 @@ pub fn preview_agent_settings(return Err(SettingsPlanningError::InvalidSelection);}spec.protected_native_model_ids.clear();- if let Some(model) = &facts.model {+ if let Some(model) = facts.model.as_ref().and_then(SettingsModelFacts::codex) {spec.protected_native_model_ids = if model.require_native_model_routes {model.required_native_model_ids.clone().unwrap_or_default()} else {@@ -197,14 +155,15 @@ pub fn preview_agent_settings(}let mut changed_facets = BTreeSet::new();let mut blockers = Vec::new();- if let Some(reason) = facts- .model- .as_ref()- .and_then(|model| model.qoder_model_conflict)- {+ if let Some(reason) = facts.model.as_ref().and_then(|model| match &model.native {+ SettingsModelNativeFacts::Additional(facts) => facts.model_conflict,+ _ => None,+ }) {if !matches!(reason,- SettingsBlockReason::QoderDefaultInUse | SettingsBlockReason::QoderModelFileConflict+ SettingsBlockReason::QoderDefaultInUse+ | SettingsBlockReason::QoderModelFileConflict+ | SettingsBlockReason::AdditionalDefaultInUse) {return Err(SettingsPlanningError::InvalidSelection);}@@ -229,6 +188,7 @@ pub fn preview_agent_settings(settings,AgentModelSelectionV2::CodexDefault { .. }| AgentModelSelectionV2::QoderAdditional { .. }+ | AgentModelSelectionV2::PiAdditional { .. }) {// A short-lived isolated HTTP challenge diagnoses a native client; it is not// authorization to write a safely observed Codex configuration. Actual client@@ -261,22 +221,31 @@ pub fn preview_agent_settings(}if matches!(settings, AgentModelSelectionV2::QoderAdditional { .. })&& !model+ .common.available_surfaces.contains(&hiroute_domain::AgentModelSurfaceV2::QoderCli){return Err(SettingsPlanningError::InvalidSelection);}+ if matches!(settings, AgentModelSelectionV2::PiAdditional { .. })+ && !model+ .common+ .available_surfaces+ .contains(&hiroute_domain::AgentModelSurfaceV2::PiCli)+ {+ return Err(SettingsPlanningError::InvalidSelection);+ }settings.validate().map_err(|_| SettingsPlanningError::InvalidSelection)?;if let AgentModelSelectionV2::ClaudeLauncher { surfaces, .. } = settings- && !surfaces.is_subset(&model.available_surfaces)+ && !surfaces.is_subset(&model.common.available_surfaces){return Err(SettingsPlanningError::InvalidSelection);}if matches!(settings, AgentModelSelectionV2::CodexDefault { .. })&& !settings.allowed_plan_ids().is_empty()- && model.codex_context_override+ && model.codex().is_some_and(|facts| facts.context_override){blockers.push(AgentSettingsBlock {facet: AgentSettingsFacet::Model,@@ -291,7 +260,10 @@ pub fn preview_agent_settings(// Every Codex selection publishes one exact client catalog, including// HiRoute-only fixed routes without a Plan.if matches!(settings, AgentModelSelectionV2::CodexDefault { .. })- && model.model_catalog.is_none()+ && model+ .codex()+ .and_then(|facts| facts.model_catalog.as_ref())+ .is_none(){blockers.push(AgentSettingsBlock {facet: AgentSettingsFacet::Model,@@ -304,7 +276,9 @@ pub fn preview_agent_settings(model_ids: Vec::new(),});}- if let Some(required) = &model.required_native_model_ids {+ if let Some(model) = model.codex()+ && let Some(required) = &model.required_native_model_ids+ {let missing = required.iter().filter(|name| {@@ -365,11 +339,8 @@ pub fn preview_agent_settings(restore_point_ref,&mut blockers,);- if model.ingress == AgentIngressProtocolV1::Responses+ if let Some(model) = model.codex()&& !model.restore_inherits_root- && !model- .available_surfaces- .contains(&hiroute_domain::AgentModelSurfaceV2::QoderCli){let chosen = spec.restore_native_model@@ -469,7 +440,7 @@ pub fn preview_agent_settings(facts.model.as_ref()- .and_then(|model| model.model_publication.as_ref()),+ .and_then(|model| model.common.model_publication.as_ref()),)}).transpose()@@ -496,7 +467,10 @@ pub fn preview_agent_settings(.model.as_ref().ok_or(SettingsPlanningError::InvalidSelection)?;- if model.claude_plan_capability_unavailable {+ let model = model+ .claude()+ .ok_or(SettingsPlanningError::InvalidSelection)?;+ if model.plan_capability_unavailable {blockers.push(AgentSettingsBlock {facet: AgentSettingsFacet::Model,reason: SettingsBlockReason::ClaudePlanCapabilityUnavailable,@@ -509,10 +483,10 @@ pub fn preview_agent_settings(.copied().min().and_then(hiroute_domain::claude_context_window);- if model.claude_context_override || window.is_none() {+ if model.context_override || window.is_none() {blockers.push(AgentSettingsBlock {facet: AgentSettingsFacet::Model,- reason: if model.claude_context_override {+ reason: if model.context_override {SettingsBlockReason::ClaudeContextOverride} else {SettingsBlockReason::ClaudeContextWindowUnsupported@@ -551,6 +525,7 @@ pub fn preview_agent_settings(unproven_native_model_ids: facts.model.as_ref()+ .and_then(SettingsModelFacts::codex).map(|model| model.unproven_native_model_ids.clone()).unwrap_or_default(),})@@ -565,29 +540,36 @@ fn derive_model_grant(.fixed_models().iter().filter(|selection| {- !facts- .preserved_codex_bindings- .contains_key(&selection.client_model_id)+ !facts.codex().is_some_and(|facts| {+ facts+ .preserved_codex_bindings+ .contains_key(&selection.client_model_id)+ })}).cloned().collect::<Vec<_>>();let mut fixed = crate::compiler::compile_fixed_model_bindings(&ordinary_fixed,- &facts.fixed_candidate_facts,+ &facts.common.fixed_candidate_facts,).map_err(|_| invalid())?;for selection in settings.fixed_models() {- if let Some(binding) = facts- .preserved_codex_bindings- .get(&selection.client_model_id)- {+ if let Some(binding) = facts.codex().and_then(|facts| {+ facts+ .preserved_codex_bindings+ .get(&selection.client_model_id)+ }) {fixed.insert(selection.client_model_id.clone(), binding.clone());}}let grant = AgentModelGrantV2::derive(- facts.ingress,+ facts.common.ingress,settings,- facts.model_publication.as_ref().ok_or_else(invalid)?,+ facts+ .common+ .model_publication+ .as_ref()+ .ok_or_else(invalid)?,&fixed,).map_err(|_| invalid())?;@@ -604,19 +586,20 @@ fn validate_model_default(let claude_presets;let default_name = match settings {AgentModelSelectionV2::CodexDefault { default_selection, .. } => match default_selection {- AgentModelDefaultSelectionV2::PreserveNative => facts.native_default_model.as_deref(),+ AgentModelDefaultSelectionV2::PreserveNative => facts.codex().ok_or_else(invalid)?.native_default_model.as_deref(),AgentModelDefaultSelectionV2::FixedModel { client_model_id } => Some(client_model_id.as_str()),AgentModelDefaultSelectionV2::Plan { plan_id } => grant.routes.iter().find_map(|(name, route)| {matches!(route, AgentModelRouteV2::Plan { plan_id: selected, .. } if selected == plan_id).then_some(name.as_str())}),},- AgentModelSelectionV2::QoderAdditional { .. } => return Ok(()),+ AgentModelSelectionV2::QoderAdditional { .. } | AgentModelSelectionV2::PiAdditional { .. } => return Ok(()),AgentModelSelectionV2::ClaudeLauncher { .. } => {+ let facts = facts.claude().ok_or_else(invalid)?;claude_presets = grant.claude_preset_values(settings,- facts.native_claude_presets.as_ref().ok_or_else(invalid)?,+ facts.presets.as_ref().ok_or_else(invalid)?,).map_err(|_| invalid())?;match facts.native_default_model.as_deref() {diff --git a/crates/application/src/agent_connection/settings/model_facts.rs b/crates/application/src/agent_connection/settings/model_facts.rsnew file mode 100644index 00000000..855c2317--- /dev/null+++ b/crates/application/src/agent_connection/settings/model_facts.rs@@ -0,0 +1,66 @@+//! Common planning inputs and the native facts owned by each ecosystem.+use super::*;++pub struct SettingsModelFacts {+ pub common: SettingsModelCommonFacts,+ pub native: SettingsModelNativeFacts,+}++pub struct SettingsModelCommonFacts {+ pub ingress: AgentIngressProtocolV1,+ pub available_surfaces: BTreeSet<hiroute_domain::AgentModelSurfaceV2>,+ pub model_publication: Option<GatewayPublicationV1>,+ pub login_item_required: bool,+ pub login_item_removal_required: bool,+ pub fixed_candidate_facts: Vec<crate::compiler::CandidateCompilationFactV1>,+}++pub enum SettingsModelNativeFacts {+ Codex(Box<SettingsCodexModelFacts>),+ Claude(SettingsClaudeNativeFacts),+ Additional(SettingsAdditionalModelFacts),+}++#[derive(Default)]+pub struct SettingsCodexModelFacts {+ pub context_override: bool,+ pub model_catalog: Option<SettingsModelCatalogFacts>,+ pub preserved_codex_models: Vec<hiroute_domain::AgentFixedModelSelectionV2>,+ pub preserved_codex_bindings: BTreeMap<String, hiroute_domain::AttemptOwnedCandidateV1>,+ pub required_native_model_ids: Option<Vec<String>>,+ pub unproven_native_model_ids: Vec<String>,+ pub require_native_model_routes: bool,+ pub native_default_must_be_original: bool,+ pub native_default_model: Option<String>,+ pub restore_native_model_ids: Option<Vec<String>>,+ pub restore_inherits_root: bool,+ pub restored_native_model: Option<String>,+}++#[derive(Default)]+pub struct SettingsClaudeNativeFacts {+ pub context_override: bool,+ pub plan_capability_unavailable: bool,+ pub native_default_model: Option<String>,+ pub presets: Option<hiroute_domain::AgentClaudePresetValuesV2>,+}++pub struct SettingsAdditionalModelFacts {+ pub model_conflict: Option<SettingsBlockReason>,+}++impl SettingsModelFacts {+ pub fn codex(&self) -> Option<&SettingsCodexModelFacts> {+ match &self.native {+ SettingsModelNativeFacts::Codex(facts) => Some(facts),+ _ => None,+ }+ }++ pub fn claude(&self) -> Option<&SettingsClaudeNativeFacts> {+ match &self.native {+ SettingsModelNativeFacts::Claude(facts) => Some(facts),+ _ => None,+ }+ }+}diff --git a/crates/application/src/agent_connection/settings/tests.rs b/crates/application/src/agent_connection/settings/tests.rsindex 7cdddc04..432ac74f 100644--- a/crates/application/src/agent_connection/settings/tests.rs+++ b/crates/application/src/agent_connection/settings/tests.rs@@ -30,33 +30,25 @@ fn facts() -> AgentSettingsFacts {collaboration_file_conflict: false,restore_points: BTreeMap::new(),model: Some(SettingsModelFacts {- qoder_model_conflict: None,- codex_context_override: false,- claude_context_override: false,- claude_plan_capability_unavailable: false,- ingress: hiroute_domain::AgentIngressProtocolV1::Messages,- available_surfaces: [- hiroute_domain::AgentModelSurfaceV2::CodexCli,- hiroute_domain::AgentModelSurfaceV2::CodexDesktop,- hiroute_domain::AgentModelSurfaceV2::ClaudeCli,- ]- .into(),- model_publication: None,- model_catalog: None,- login_item_required: false,- login_item_removal_required: false,- fixed_candidate_facts: Vec::new(),- preserved_codex_models: Vec::new(),- preserved_codex_bindings: BTreeMap::new(),- required_native_model_ids: None,- unproven_native_model_ids: Vec::new(),- require_native_model_routes: false,- native_default_must_be_original: false,- native_default_model: None,- restore_native_model_ids: None,- restore_inherits_root: false,- restored_native_model: None,- native_claude_presets: None,+ common: SettingsModelCommonFacts {+ ingress: hiroute_domain::AgentIngressProtocolV1::Messages,+ available_surfaces: [+ hiroute_domain::AgentModelSurfaceV2::CodexCli,+ hiroute_domain::AgentModelSurfaceV2::CodexDesktop,+ hiroute_domain::AgentModelSurfaceV2::ClaudeCli,+ ]+ .into(),+ model_publication: None,+ login_item_required: false,+ login_item_removal_required: false,+ fixed_candidate_facts: Vec::new(),+ },+ native: SettingsModelNativeFacts::Claude(SettingsClaudeNativeFacts {+ context_override: false,+ plan_capability_unavailable: false,+ native_default_model: None,+ presets: None,+ }),}),}}@@ -67,6 +59,22 @@ fn model(facts: &mut AgentSettingsFacts) -> &mut SettingsModelFacts {.expect("this fixture supports model settings")}+fn codex(facts: &mut AgentSettingsFacts) -> &mut SettingsCodexModelFacts {+ if !matches!(model(facts).native, SettingsModelNativeFacts::Codex(_)) {+ model(facts).native = SettingsModelNativeFacts::Codex(Box::default());+ }+ match &mut model(facts).native {+ SettingsModelNativeFacts::Codex(facts) => facts,+ _ => unreachable!(),+ }+}+fn claude(facts: &mut AgentSettingsFacts) -> &mut SettingsClaudeNativeFacts {+ match &mut model(facts).native {+ SettingsModelNativeFacts::Claude(facts) => facts,+ _ => panic!("Claude fixture required"),+ }+}+#[test]fn claude_default_coverage_resolves_all_three_presets_without_changing_selection() {use hiroute_domain::{@@ -98,29 +106,29 @@ fn claude_default_coverage_resolves_all_three_presets_without_changing_selection},};let mut current = facts();- model(&mut current).native_claude_presets = Some(AgentClaudePresetValuesV2 {+ claude(&mut current).presets = Some(AgentClaudePresetValuesV2 {opus: Some("native-opus".into()),sonnet: None,haiku: Some("native-haiku".into()),});for default in ["opus", "sonnet", "haiku", "hiroute-shared", "default"] {- model(&mut current).native_default_model = Some(default.into());+ claude(&mut current).native_default_model = Some(default.into());assert_eq!(validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),Ok(()));assert_eq!(- model(&mut current).native_default_model.as_deref(),+ claude(&mut current).native_default_model.as_deref(),Some(default));}- model(&mut current).native_default_model = None;+ claude(&mut current).native_default_model = None;assert_eq!(validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),Ok(()));for default in [Some("uncovered-native"), Some("opus[1m]")] {- model(&mut current).native_default_model = default.map(str::to_owned);+ claude(&mut current).native_default_model = default.map(str::to_owned);assert_eq!(validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),Err(SettingsPlanningError::InvalidSelection)@@ -134,18 +142,18 @@ fn claude_default_coverage_resolves_all_three_presets_without_changing_selectionpreset_mappings.sonnet = AgentClaudePresetSelectionV2::PreserveNative;}for default in ["opus", "sonnet"] {- model(&mut current).native_default_model = Some(default.into());+ claude(&mut current).native_default_model = Some(default.into());assert_eq!(validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),Err(SettingsPlanningError::InvalidSelection));}- model(&mut current).native_default_model = Some("haiku".into());+ claude(&mut current).native_default_model = Some("haiku".into());assert_eq!(validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),Ok(()));- model(&mut current).native_claude_presets = None;+ claude(&mut current).presets = None;assert_eq!(validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),Err(SettingsPlanningError::InvalidSelection)@@ -247,13 +255,13 @@ fn agent_settings_restore_reference_cannot_cross_context_or_facet() {#[test]fn codex_restore_requires_an_original_catalog_model_for_a_stale_alias() {let mut facts = facts();- model(&mut facts).ingress = AgentIngressProtocolV1::Responses;+ model(&mut facts).common.ingress = AgentIngressProtocolV1::Responses;facts.restore_points.insert("restore/owned".into(), AgentSettingsFacet::Model);- model(&mut facts).restore_native_model_ids =+ codex(&mut facts).restore_native_model_ids =Some(vec!["gpt-5.6-sol".into(), "gpt-5.6-luna".into()]);- model(&mut facts).restored_native_model = Some("hiroute-fanyi".into());+ codex(&mut facts).restored_native_model = Some("hiroute-fanyi".into());let mut spec: AgentSettingsSpecV2 = serde_json::from_value(json!({"schema_version": {"major": 2, "minor": 0},"context_id": "agent-context/test",@@ -464,32 +472,32 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {collaboration_file_conflict: false,restore_points: BTreeMap::new(),model: Some(SettingsModelFacts {- qoder_model_conflict: None,- codex_context_override: false,- claude_context_override: false,- claude_plan_capability_unavailable: false,- ingress: AgentIngressProtocolV1::Responses,- available_surfaces: [- hiroute_domain::AgentModelSurfaceV2::CodexCli,- hiroute_domain::AgentModelSurfaceV2::CodexDesktop,- ]- .into(),- model_publication: Some(publication.clone()),- model_catalog,- login_item_required: false,- login_item_removal_required: false,- fixed_candidate_facts: Vec::new(),- preserved_codex_models: Vec::new(),- preserved_codex_bindings: BTreeMap::new(),- required_native_model_ids: None,- unproven_native_model_ids: Vec::new(),- require_native_model_routes: false,- native_default_must_be_original: false,- native_default_model: None,- restore_native_model_ids: None,- restore_inherits_root: false,- restored_native_model: None,- native_claude_presets: None,+ common: SettingsModelCommonFacts {+ ingress: AgentIngressProtocolV1::Responses,+ available_surfaces: [+ hiroute_domain::AgentModelSurfaceV2::CodexCli,+ hiroute_domain::AgentModelSurfaceV2::CodexDesktop,+ ]+ .into(),+ model_publication: Some(publication.clone()),+ login_item_required: false,+ login_item_removal_required: false,+ fixed_candidate_facts: Vec::new(),+ },+ native: SettingsModelNativeFacts::Codex(Box::new(SettingsCodexModelFacts {+ context_override: false,+ model_catalog,+ preserved_codex_models: Vec::new(),+ preserved_codex_bindings: BTreeMap::new(),+ required_native_model_ids: None,+ unproven_native_model_ids: Vec::new(),+ require_native_model_routes: false,+ native_default_must_be_original: false,+ native_default_model: None,+ restore_native_model_ids: None,+ restore_inherits_root: false,+ restored_native_model: None,+ })),}),}};@@ -555,13 +563,16 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {producer_context_digest: CanonicalDigest::of_bytes(b"codex-context"),producer_dependency_digest: CanonicalDigest::of_bytes(b"catalog-dependencies"),}));- model(&mut no_detected_surface).available_surfaces.clear();+ model(&mut no_detected_surface)+ .common+ .available_surfaces+ .clear();let without_client =preview_agent_settings(spec(plan_selection.clone()), &no_detected_surface).unwrap();assert!(without_client.blockers.is_empty());assert!(without_client.model_grant.is_some());- model(&mut no_detected_surface).codex_context_override = true;+ codex(&mut no_detected_surface).context_override = true;let conflict =preview_agent_settings(spec(plan_selection.clone()), &no_detected_surface).unwrap();assert!(@@ -585,7 +596,7 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {let mut preserve_plan_alias = plan_selection.clone();preserve_plan_alias["native_model_mode"] = json!("preserve_available");preserve_plan_alias["default_selection"] = json!({"kind": "preserve_native"});- model(&mut proven_facts).native_default_model = Some(plan.model_alias.as_str().into());+ codex(&mut proven_facts).native_default_model = Some(plan.model_alias.as_str().into());let matched_alias =preview_agent_settings(spec(preserve_plan_alias.clone()), &proven_facts).unwrap();assert!(matched_alias.blockers.is_empty());@@ -596,14 +607,14 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {.permits_name(plan.model_alias.as_str()),"an explicitly allowed plan covers the same current Codex default alias");- model(&mut proven_facts).native_default_model = Some("hiroute-unpublished".into());+ codex(&mut proven_facts).native_default_model = Some("hiroute-unpublished".into());let unmatched_alias = preview_agent_settings(spec(preserve_plan_alias), &proven_facts).unwrap();assert_eq!(unmatched_alias.blockers[0].reason,SettingsBlockReason::ModelPlanUnavailable,"an unrelated default name still cannot be published");- model(&mut proven_facts).native_default_model = None;+ codex(&mut proven_facts).native_default_model = None;let candidates = crate::compiler::test_fixtures::compilation_facts().candidates;let candidate = candidates.iter()@@ -624,15 +635,16 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {}),},};- model(&mut proven_facts).fixed_candidate_facts = vec![candidate, replacement_candidate.clone()];- model(&mut proven_facts).preserved_codex_models = vec![preserved.clone()];- model(&mut proven_facts).native_default_model = Some(preserved.client_model_id.clone());- model(&mut proven_facts).required_native_model_ids = Some(vec![+ model(&mut proven_facts).common.fixed_candidate_facts =+ vec![candidate, replacement_candidate.clone()];+ codex(&mut proven_facts).preserved_codex_models = vec![preserved.clone()];+ codex(&mut proven_facts).native_default_model = Some(preserved.client_model_id.clone());+ codex(&mut proven_facts).required_native_model_ids = Some(vec![preserved.client_model_id.clone(),"native-unselected".into(),]);- model(&mut proven_facts).require_native_model_routes = true;- model(&mut proven_facts).native_default_must_be_original = true;+ codex(&mut proven_facts).require_native_model_routes = true;+ codex(&mut proven_facts).native_default_must_be_original = true;let mut preserve_selection = plan_selection.clone();preserve_selection["native_model_mode"] = json!("preserve_available");let incomplete =@@ -641,16 +653,16 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {block.reason == SettingsBlockReason::NativeModelCoverageUnavailable&& block.model_ids == ["native-unselected"]}));- model(&mut proven_facts).required_native_model_ids =+ codex(&mut proven_facts).required_native_model_ids =Some(vec![preserved.client_model_id.clone()]);- model(&mut proven_facts).native_default_model = Some(plan.model_alias.as_str().into());+ codex(&mut proven_facts).native_default_model = Some(plan.model_alias.as_str().into());let stale_default =preview_agent_settings(spec(preserve_selection.clone()), &proven_facts).unwrap();assert!(stale_default.blockers.iter().any(|block| {block.reason == SettingsBlockReason::NativeDefaultInvalid&& block.model_ids == [plan.model_alias.as_str()]}));- model(&mut proven_facts).native_default_model = Some(preserved.client_model_id.clone());+ codex(&mut proven_facts).native_default_model = Some(preserved.client_model_id.clone());let mut replacing = preserve_selection.clone();let mut replaced = preserved.clone();replaced.candidate.binding_id = replacement_candidate.binding.binding_id.clone();@@ -668,7 +680,7 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {};assert_eq!(fixed_models, std::slice::from_ref(&replaced));- model(&mut proven_facts).unproven_native_model_ids =+ codex(&mut proven_facts).unproven_native_model_ids =vec!["cache-name-without-account-proof".into()];let proven = preview_agent_settings(spec(preserve_selection.clone()), &proven_facts).unwrap();assert!(proven.blockers.is_empty());@@ -693,10 +705,13 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {else {panic!("fixed route")};- model(&mut proven_facts)+ codex(&mut proven_facts).preserved_codex_bindings.insert(preserved.client_model_id.clone(), binding.as_ref().clone());- model(&mut proven_facts).fixed_candidate_facts.clear();+ model(&mut proven_facts)+ .common+ .fixed_candidate_facts+ .clear();let later = preview_agent_settings(spec(preserve_selection.clone()), &proven_facts).unwrap();assert!(later.blockers.is_empty());assert_eq!(@@ -709,7 +724,7 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {);let mut changed_binding = preserve_selection;changed_binding["fixed_models"] = serde_json::to_value([replaced]).unwrap();- model(&mut proven_facts).fixed_candidate_facts = vec![replacement_candidate];+ model(&mut proven_facts).common.fixed_candidate_facts = vec![replacement_candidate];let rejected = preview_agent_settings(spec(changed_binding), &proven_facts).unwrap();assert!(!rejected.blockers.is_empty());assert!(@@ -720,10 +735,10 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {);// Plan-only settings without protected native bindings remain a full-state edit.- model(&mut proven_facts).preserved_codex_models.clear();- model(&mut proven_facts).preserved_codex_bindings.clear();- model(&mut proven_facts).required_native_model_ids = None;- model(&mut proven_facts).require_native_model_routes = false;+ codex(&mut proven_facts).preserved_codex_models.clear();+ codex(&mut proven_facts).preserved_codex_bindings.clear();+ codex(&mut proven_facts).required_native_model_ids = None;+ codex(&mut proven_facts).require_native_model_routes = false;let removed = preview_agent_settings(spec(plan_selection), &proven_facts).unwrap();let AgentFacetIntent::Configure {settings: AgentModelSelectionV2::CodexDefault { fixed_models, .. },@@ -1055,8 +1070,8 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {"opus":{"kind":"plan","plan_id":ids[0]},"sonnet":{"kind":"plan","plan_id":ids[1]},"haiku":{"kind":"preserve_native"}}}}})).unwrap();let mut facts = facts();- model(&mut facts).model_publication = Some(publication);- model(&mut facts).native_claude_presets = Some(hiroute_domain::AgentClaudePresetValuesV2 {+ model(&mut facts).common.model_publication = Some(publication);+ claude(&mut facts).presets = Some(hiroute_domain::AgentClaudePresetValuesV2 {opus: None,sonnet: None,haiku: None,@@ -1071,7 +1086,7 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {.collect::<BTreeSet<_>>(),[100_000, 120_000].into());- model(&mut facts).claude_context_override = true;+ claude(&mut facts).context_override = true;let blocked = preview_agent_settings(spec.clone(), &facts).unwrap();assert!(blocked@@ -1079,8 +1094,8 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {.iter().any(|block| block.reason == SettingsBlockReason::ClaudeContextOverride));- model(&mut facts).claude_context_override = false;- model(&mut facts).claude_plan_capability_unavailable = true;+ claude(&mut facts).context_override = false;+ claude(&mut facts).plan_capability_unavailable = true;let blocked = preview_agent_settings(spec, &facts).unwrap();assert!(blocked@@ -1093,8 +1108,8 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {#[test]fn standalone_profile_restore_inherits_root_without_catalog_or_native_override() {let mut facts = facts();- model(&mut facts).ingress = AgentIngressProtocolV1::Responses;- model(&mut facts).restore_inherits_root = true;+ model(&mut facts).common.ingress = AgentIngressProtocolV1::Responses;+ codex(&mut facts).restore_inherits_root = true;facts.capabilities = AgentCapabilitySet::new([AgentCapability::EffectiveConfiguration,diff --git a/crates/application/src/agent_connection/settings_input.rs b/crates/application/src/agent_connection/settings_input.rsindex 97dc04ae..e659d716 100644--- a/crates/application/src/agent_connection/settings_input.rs+++ b/crates/application/src/agent_connection/settings_input.rs@@ -43,10 +43,12 @@ pub enum SettingsModelTargetFacts {endpoint: String,},Claude(SettingsClaudeModelFacts),- Qoder {+ Additional {+ kind: hiroute_domain::AgentKindV1,+ pi_settings_content: Option<CanonicalDigest>,provider_id: String,endpoint: String,- models: Vec<hiroute_domain::QoderAdditionalModelV1>,+ models: Vec<hiroute_domain::AdditionalAgentModelV1>,},}@@ -109,31 +111,45 @@ impl AgentSettingsPlanningInput {.codex_default_override(settings).map_err(|_| invalid())?,model_catalog: model- .model_catalog- .as_ref()+ .codex()+ .and_then(|facts| facts.model_catalog.as_ref()).map(|catalog| catalog.content_digest.clone()),}),- SettingsModelTargetFacts::Qoder {+ SettingsModelTargetFacts::Additional {+ kind,+ pi_settings_content,provider_id,endpoint,models,} => {- if !matches!(settings, AgentModelSelectionV2::QoderAdditional { .. }) {+ if !matches!(+ settings,+ AgentModelSelectionV2::QoderAdditional { .. }+ | AgentModelSelectionV2::PiAdditional { .. }+ ) || matches!(settings, AgentModelSelectionV2::PiAdditional { .. })+ != (*kind == hiroute_domain::AgentKindV1::Pi)+ {return Err(invalid());}- SettingsModelAction::Qoder(super::QoderModelFileAction::Configure {- previous_operation: file.active_configuration.clone(),- provider_id: provider_id.clone(),- endpoint: endpoint.clone(),- models: models.clone(),- })+ SettingsModelAction::Additional(+ pi_settings_content.clone(),+ super::AdditionalModelFileAction::Configure {+ previous_operation: file.active_configuration.clone(),+ provider_id: provider_id.clone(),+ endpoint: endpoint.clone(),+ models: models.clone(),+ },+ )}SettingsModelTargetFacts::Claude(claude) => {let mut snapshot = claude_model_snapshot(settings,grant,claude,- model.native_claude_presets.as_ref().ok_or_else(invalid)?,+ model+ .claude()+ .and_then(|facts| facts.presets.as_ref())+ .ok_or_else(invalid)?,)?;snapshot.context_window_tokens = preview.claude_context_window;SettingsModelAction::Claude(ClaudeModelFileAction::Configure {@@ -194,11 +210,15 @@ impl AgentSettingsPlanningInput {native_model: preview.spec.restore_native_model.clone(),})}- SettingsModelTargetFacts::Qoder { .. } => {- SettingsModelAction::Qoder(super::QoderModelFileAction::Restore {+ SettingsModelTargetFacts::Additional {+ pi_settings_content,+ ..+ } => SettingsModelAction::Additional(+ pi_settings_content.clone(),+ super::AdditionalModelFileAction::Restore {original_operation: operation.clone(),- })- }+ },+ ),SettingsModelTargetFacts::Claude(_) => {SettingsModelAction::Claude(ClaudeModelFileAction::Restore {original_operation: operation.clone(),@@ -245,7 +265,7 @@ impl AgentSettingsPlanningInput {.facts.model.as_ref()- .is_some_and(|model| model.login_item_removal_required)+ .is_some_and(|model| model.common.login_item_removal_required){// The last managed connection's restore releases the login item this// feature created in an older version. New connections never create one.@@ -261,7 +281,9 @@ impl AgentSettingsPlanningInput {let model = self.facts.model.as_ref().ok_or_else(invalid)?;match action {SettingsModelAction::Codex(change) => {- if let Some(catalog) = model.model_catalog.as_ref() {+ if let Some(catalog) =+ model.codex().and_then(|facts| facts.model_catalog.as_ref())+ {// The immutable catalog artifact is staged before the managed// configuration so the rendered pointer always has a target.external.push(settings_codex_catalog_intent(@@ -284,13 +306,14 @@ impl AgentSettingsPlanningInput {change,)?);}- SettingsModelAction::Qoder(change) => {- external.push(super::settings_qoder_model_file_intent(+ SettingsModelAction::Additional(pi_settings_content, change) => {+ external.push(super::settings_additional_model_file_intent(control,&self.facts.context_id,file.expected_content.clone(),file.before_fingerprint.clone(),change,+ pi_settings_content,)?);}SettingsModelAction::Claude(change) => {@@ -403,7 +426,7 @@ impl AgentSettingsPlanningInput {}enum SettingsModelAction {- Qoder(super::QoderModelFileAction),+ Additional(Option<CanonicalDigest>, super::AdditionalModelFileAction),Codex(CodexModelFileAction),Claude(ClaudeModelFileAction),}diff --git a/crates/application/src/agent_connection/tests.rs b/crates/application/src/agent_connection/tests.rsindex 77c75ff0..a7dc5619 100644--- a/crates/application/src/agent_connection/tests.rs+++ b/crates/application/src/agent_connection/tests.rs@@ -48,8 +48,8 @@ fn agent_connection_current_proof_allows_unlisted_version_without_version_allowlfn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {let version = match kind {- AgentKindV1::Qoder => {- panic!("model-connection fixture does not support collaboration-only Qoder")+ AgentKindV1::Qoder | AgentKindV1::Pi => {+ panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => CODEX_VERIFIED_VERSION_V1,AgentKindV1::ClaudeCode => CLAUDE_CODE_VERIFIED_VERSION_V1,@@ -85,8 +85,8 @@ fn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {fn profile(kind: AgentKindV1) -> AgentProfileV1 {let precedence = kind.config_precedence().to_vec();match kind {- AgentKindV1::Qoder => {- panic!("model-connection fixture does not support collaboration-only Qoder")+ AgentKindV1::Qoder | AgentKindV1::Pi => {+ panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => {let tool = codex_spawn_agent_tool_v1();@@ -252,8 +252,8 @@ fn facts(kind: AgentKindV1) -> AgentConnectionPlanningFactsV1 {fn spec(kind: AgentKindV1, native: bool, dynamic: bool) -> AgentConnectSpecV1 {let profile = match kind {- AgentKindV1::Qoder => {- panic!("model-connection fixture does not support collaboration-only Qoder")+ AgentKindV1::Qoder | AgentKindV1::Pi => {+ panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => profile(AgentKindV1::Codex),AgentKindV1::ClaudeCode => profile(AgentKindV1::ClaudeCode),@@ -263,8 +263,8 @@ 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 => {- panic!("model-connection fixture does not support collaboration-only Qoder")+ AgentKindV1::Qoder | AgentKindV1::Pi => {+ panic!("this fixture covers default-model replacement, not additional providers")}AgentKindV1::Codex => CODEX_VERIFIED_VERSION_V1,AgentKindV1::ClaudeCode => CLAUDE_CODE_VERIFIED_VERSION_V1,diff --git a/crates/application/src/compute_management/compilation.rs b/crates/application/src/compute_management/compilation.rsindex 8a1f6ef8..6ca75d38 100644--- a/crates/application/src/compute_management/compilation.rs+++ b/crates/application/src/compute_management/compilation.rs@@ -16,6 +16,7 @@ pub enum ComputeManagementEligibilityV2 {CatalogMatched,RuntimeQualified,UserConfirmed,+ NativeObserved,ConnectorVerified,}@@ -208,6 +209,11 @@ fn compile_model({return Err(ComputeManagementCompilationErrorV2::UnknownCapability);}+ if eligibility == ComputeManagementEligibilityV2::NativeObserved+ && !native_observed_model(source, model)+ {+ return Err(ComputeManagementCompilationErrorV2::EligibilityMismatch);+ }let native_reasoning = capabilities.native_reasoning.value@@ -244,6 +250,9 @@ fn eligibility(source: &ComputeManagementSourceV2,model: &ComputeManagedModelV2,) -> Result<ComputeManagementEligibilityV2, ComputeManagementCompilationErrorV2> {+ if native_observed_model(source, model) {+ return Ok(ComputeManagementEligibilityV2::NativeObserved);+ }if (matches!(source.provenance,ComputeManagementProvenanceV2::Registered { .. }@@ -284,6 +293,30 @@ fn eligibility(}}+// A discovered native user source is not a registered runtime fallback. Keep+// its observed/unknown facts and give it the existing source-local authority.+fn native_observed_model(+ source: &ComputeManagementSourceV2,+ model: &ComputeManagedModelV2,+) -> bool {+ model.membership == ComputeManagementMembershipV2::Observed+ && model.catalog_configuration_id.is_none()+ && matches!(+ source.provenance,+ ComputeManagementProvenanceV2::UserConfigured { .. }+ )+ && capability_bases(&model.capabilities)+ .into_iter()+ .all(|basis| {+ matches!(+ basis,+ ComputeManagementFactBasisV2::Observed+ | ComputeManagementFactBasisV2::Unknown+ | ComputeManagementFactBasisV2::UserDeclared+ )+ })+}+fn capability_bases(capabilities: &ComputeManagedCapabilitiesV2,) -> [ComputeManagementFactBasisV2; 6] {diff --git a/crates/application/src/compute_management/mutations.rs b/crates/application/src/compute_management/mutations.rsindex e3646970..ba3c1def 100644--- a/crates/application/src/compute_management/mutations.rs+++ b/crates/application/src/compute_management/mutations.rs@@ -50,6 +50,9 @@ impl ComputeManagementPreparedPreviewV2 {pub(crate) struct ComputePreparedDiscoveryGuardV1 {pub(crate) input_slot: String,pub(crate) evidence_digest: CanonicalDigest,+ /// Materialization also requires the plan's Upsert fingerprint at admission.+ /// A source-only guard can retain an already saved credential unchanged.+ pub(crate) materializes_secret: bool,}pub struct ComputeManagementPlanner<'a, C, R, S, I> {@@ -212,7 +215,9 @@ where});discovery_guards.sort_by(|left, right| left.input_slot.cmp(&right.input_slot));discovery_guards.dedup_by(|left, right| {- left.input_slot == right.input_slot && left.evidence_digest == right.evidence_digest+ left.input_slot == right.input_slot+ && left.evidence_digest == right.evidence_digest+ && left.materializes_secret == right.materializes_secret});let spec = ChangeSpecV1 {@@ -464,6 +469,14 @@ wheresecret_mutations: &mut Vec<SecretMutationV1>,discovery_guards: &mut Vec<ComputePreparedDiscoveryGuardV1>,) -> Result<(), ComputeManagementPlanningErrorV2> {+ // Re-saving an existing lineage can retain its key without materializing+ // a new one. Its native discovery must still match the accepted source.+ if current.is_some()+ && let ComputeCredentialBindingV2::NativeProtected { input_slot, .. } =+ &candidate.credential_binding+ {+ self.guard_discovered_input(candidate, input_slot, false, discovery_guards)?;+ }match &candidate.credential_binding {ComputeCredentialBindingV2::NativeProtected { input_slot, .. }if current.is_none()@@ -665,16 +678,13 @@ whereOk(facts)}- fn materialize_input(+ fn guard_discovered_input(&self,- desired: &ComputeManagementSourceV2,input: &ComputeCandidateFactsV2,- key_id: &str,- expected_generation: u64,input_slot: &str,+ materializes_secret: bool,discovery_guards: &mut Vec<ComputePreparedDiscoveryGuardV1>,- ) -> Result<(ComputeManagedCredentialV2, SecretMutationV1), ComputeManagementPlanningErrorV2>- {+ ) -> Result<(), ComputeManagementPlanningErrorV2> {if let Some(guard) = &input.discovery_guard {self.protected_inputs.validate_discovery_evidence(input_slot, &guard.evidence_digest)@@ -682,8 +692,23 @@ wherediscovery_guards.push(ComputePreparedDiscoveryGuardV1 {input_slot: input_slot.to_owned(),evidence_digest: guard.evidence_digest.clone(),+ materializes_secret,});}+ Ok(())+ }++ fn materialize_input(+ &self,+ desired: &ComputeManagementSourceV2,+ input: &ComputeCandidateFactsV2,+ key_id: &str,+ expected_generation: u64,+ input_slot: &str,+ discovery_guards: &mut Vec<ComputePreparedDiscoveryGuardV1>,+ ) -> Result<(ComputeManagedCredentialV2, SecretMutationV1), ComputeManagementPlanningErrorV2>+ {+ self.guard_discovered_input(input, input_slot, true, discovery_guards)?;let destinations = desired.native_destinations().map_err(|_| ComputeManagementPlanningErrorV2::InvalidCandidate)?;diff --git a/crates/application/src/compute_management/tests.rs b/crates/application/src/compute_management/tests.rsindex c346e44a..627cb6a5 100644--- a/crates/application/src/compute_management/tests.rs+++ b/crates/application/src/compute_management/tests.rs@@ -819,6 +819,51 @@ fn local_compilation_preserves_no_credential_and_user_confirmed_reasoning() {assert_eq!(compiled[0].capabilities.tool.value, None);}+#[test]+fn imported_native_model_keeps_observed_capabilities_when_compiled_for_routing() {+ use hiroute_domain::{ComputeManagementFactBasisV2 as Basis, ComputeManagementMembershipV2};++ let mut source = complete_management_source();+ let model = &mut source.models[0];+ model.membership = ComputeManagementMembershipV2::Observed;+ model.capabilities.vision.basis = Basis::Observed;+ model.capabilities.context_tokens.basis = Basis::Observed;+ model.capabilities.max_output_tokens.basis = Basis::Observed;+ model.capabilities.tool.value = None;+ model.capabilities.tool.basis = Basis::Unknown;+ model.capabilities.streaming.value = None;+ model.capabilities.streaming.basis = Basis::Unknown;+ model.capabilities.native_reasoning.value = None;+ model.capabilities.native_reasoning.basis = Basis::Unknown;++ let facts = compile_compute_management_source(&source).unwrap();+ assert_eq!(facts.len(), 1);+ assert_eq!(+ facts[0].eligibility,+ ComputeManagementEligibilityV2::NativeObserved+ );+ assert_eq!(facts[0].capabilities, source.models[0].capabilities);+ assert_eq!(+ facts[0].upstream_model_id,+ source.models[0].upstream_model_id+ );+ assert_eq!(facts[0].target, source.target);++ // Neither manually declared membership nor a catalog assertion can acquire+ // the native observation path by changing a fact's basis.+ source.models[0].membership = ComputeManagementMembershipV2::UserDeclared;+ assert_eq!(+ compile_compute_management_source(&source),+ Err(ComputeManagementCompilationErrorV2::EligibilityMismatch)+ );+ source.models[0].membership = ComputeManagementMembershipV2::Observed;+ source.models[0].capabilities.vision.basis = Basis::RegisteredCatalog;+ assert_eq!(+ compile_compute_management_source(&source),+ Err(ComputeManagementCompilationErrorV2::EligibilityMismatch)+ );+}+struct OneSourceRepository(hiroute_domain::ComputeManagementSourceV2);impl hiroute_domain::ComputeManagementRepositoryPort for OneSourceRepository {diff --git a/crates/application/src/control_plane/agent_settings.rs b/crates/application/src/control_plane/agent_settings.rsindex ae04b0f5..75fc664c 100644--- a/crates/application/src/control_plane/agent_settings.rs+++ b/crates/application/src/control_plane/agent_settings.rs@@ -47,8 +47,8 @@ pub(crate) fn preview(result["expected_revisions"] = json!(input.expected_revisions);result["applicable"] = json!(preview.blockers.is_empty());result["resident_service"] = json!({- "login_item_required": input.facts.model.as_ref().is_some_and(|model| model.login_item_required),- "login_item_removal_required": input.facts.model.as_ref().is_some_and(|model| model.login_item_removal_required),+ "login_item_required": input.facts.model.as_ref().is_some_and(|model| model.common.login_item_required),+ "login_item_removal_required": input.facts.model.as_ref().is_some_and(|model| model.common.login_item_removal_required),});if matches!(&preview.spec.collaboration,@@ -89,13 +89,14 @@ pub(crate) fn preview(}),(hiroute_application_api::AgentFacetIntent::Configure { settings },- Some(SettingsModelTargetFacts::Qoder {+ Some(SettingsModelTargetFacts::Additional {+ kind,provider_id,endpoint,..}),) => json!({- "action":"configure", "agent_class":"qoder", "provider_id":provider_id, "endpoint":endpoint,+ "action":"configure", "agent_class":kind.as_str(), "provider_id":provider_id, "endpoint":endpoint,"selection":settings, "authentication":"connection_scoped_local_grant",}),(hiroute_application_api::AgentFacetIntent::Restore { restore_point_ref }, Some(_)) => {@@ -178,7 +179,7 @@ pub(crate) fn apply(.facts.model.as_ref()- .is_some_and(|model| model.login_item_removal_required)+ .is_some_and(|model| model.common.login_item_removal_required)&& payload.login_item.is_some(){// New saves do not own startup state; an unsolicited host declaration must not be@@ -189,7 +190,7 @@ pub(crate) fn apply(.facts.model.as_ref()- .is_some_and(|model| model.login_item_removal_required)+ .is_some_and(|model| model.common.login_item_removal_required)&& !payload.login_item.as_ref()diff --git a/crates/application/src/delegation/tasks.rs b/crates/application/src/delegation/tasks.rsindex 35f90f78..8c3d2eea 100644--- a/crates/application/src/delegation/tasks.rs+++ b/crates/application/src/delegation/tasks.rs@@ -810,6 +810,7 @@ mod tests {unavailable(hiroute_domain::delegation::WorkerHarnessV1::CodexCli),unavailable(hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode),unavailable(hiroute_domain::delegation::WorkerHarnessV1::QoderCli),+ unavailable(hiroute_domain::delegation::WorkerHarnessV1::Pi),],})}@@ -877,7 +878,7 @@ mod tests {.iter().map(|executor| executor["harness"].as_str().unwrap()).collect::<Vec<_>>(),- ["codex_cli", "claude_code", "qoder_cli"]+ ["codex_cli", "claude_code", "qoder_cli", "pi"]);let rejected = invoke_worker(diff --git a/crates/application/src/operations/prepared.rs b/crates/application/src/operations/prepared.rsindex c83c81a5..f08f2633 100644--- a/crates/application/src/operations/prepared.rs+++ b/crates/application/src/operations/prepared.rs@@ -312,6 +312,9 @@ whereself.protected_inputs.validate_discovery_evidence(&guard.input_slot, &guard.evidence_digest).map_err(|_| TransactionError::ChangePreviewStale)?;+ if !guard.materializes_secret {+ continue;+ }let mutation = plan.secrets().iter()diff --git a/crates/cli/src/worker/input.rs b/crates/cli/src/worker/input.rsindex 34f7f7de..377d5d1d 100644--- a/crates/cli/src/worker/input.rs+++ b/crates/cli/src/worker/input.rs@@ -25,6 +25,7 @@ pub(super) fn parse_dependencies_discover("codex_cli" => WorkerHarnessV1::CodexCli,"claude_code" => WorkerHarnessV1::ClaudeCode,"qoder_cli" => WorkerHarnessV1::QoderCli,+ "pi" => WorkerHarnessV1::Pi,_ => return Err(ErrorCode::InvalidArguments),};harness = unique(harness, parsed)?;diff --git a/crates/cli/src/worker/render.rs b/crates/cli/src/worker/render.rsindex 767c94a3..9f93cf81 100644--- a/crates/cli/src/worker/render.rs+++ b/crates/cli/src/worker/render.rs@@ -711,6 +711,7 @@ fn worker_harness_wire_name(harness: WorkerHarnessV1) -> &'static str {WorkerHarnessV1::CodexCli => "codex_cli",WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",+ WorkerHarnessV1::Pi => "pi",}}diff --git a/crates/cli/tests/work_plans/support.rs b/crates/cli/tests/work_plans/support.rsdeleted file mode 100644index d88f6276..00000000--- a/crates/cli/tests/work_plans/support.rs+++ /dev/null@@ -1,127 +0,0 @@-#![allow(dead_code)]-use hiroute_domain::*;-use hiroute_local_storage::{ApplyCapabilityRegistrationV1, LocalStorageSet};-use serde_json::json;--fn agent_transaction_plan(- transaction: AgentConnectionTransactionKindV1,- before: Option<CanonicalDigest>,-) -> TransactionPlanV1 {- let spec = ChangeSpecV1 {- schema_version: hiroute_domain::CHANGE_SPEC_SCHEMA_V1,- command_id: transaction.command_id().to_owned(),- resource_id: Some("agent-connection/codex-default".to_owned()),- desired_state: match transaction {- AgentConnectionTransactionKindV1::Settings => {- panic!("legacy fixture does not model independent settings")- }- AgentConnectionTransactionKindV1::Apply => json!({- "agent_id": "agent.codex",- "profile_id": "default",- "default_agent_plan_id": "plan.primary"- }),- AgentConnectionTransactionKindV1::Restore => json!({- "agent_id": "agent.codex",- "profile_id": "default",- "restore_point_ref": "restore.codex.1"- }),- },- };- let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(- "agent.codex",- "default",- "codex.profile.v1",- )- .unwrap();- let control = AgentConnectionControlIntentV1::from_registered_planner(- transaction,- subject,- &spec,- &json!({"connection_revision": 4, "desired_digest": "connection.digest.v4"}),- )- .unwrap();- let external = [- AgentConnectionEffectRoleV1::GrantScopedPublication,- AgentConnectionEffectRoleV1::ManagedConfiguration,- ]- .into_iter()- .map(|role| {- ExternalEffectIntentV1::from_agent_connection_planner(- &control,- role,- if role == AgentConnectionEffectRoleV1::ManagedConfiguration {- before.clone()- } else {- None- },- &json!({"role": format!("{role:?}"), "content_digest": "sha256:fixture"}),- if role == AgentConnectionEffectRoleV1::ManagedConfiguration {- 0o640- } else {- 0o644- },- )- .unwrap()- })- .collect();- TransactionPlanV1::from_agent_connection_planner(spec, control, external).unwrap()-}--pub fn begin(stores: &LocalStorageSet, key: &str) -> OperationV1 {- let workspace = WorkspaceId::default();- let scope =- IdempotencyScopeV1::new("interactive-user", "ApplyAgentConnectionChange", key).unwrap();- let digest = CanonicalDigest::of_bytes(key.as_bytes());- let revisions = stores.control().current_revisions(&workspace).unwrap();- let operation = OperationV1::new(- OperationId::derive(&workspace, &scope, &digest),- workspace.clone(),- scope,- digest.clone(),- digest.clone(),- revisions.clone(),- agent_transaction_plan(AgentConnectionTransactionKindV1::Apply, None),- )- .unwrap();- let capability = format!("fixture-exact-apply-capability-{key}-0123456789");- let expires = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_secs() as i64- + 120;- stores- .apply_capability_registrar()- .register(- ApplyCapabilityRegistrationV1::from_protected_launcher(- capability.clone(),- "interactive-user",- workspace.clone(),- "ApplyAgentConnectionChange",- digest,- revisions,- expires,- )- .unwrap(),- )- .unwrap();- let auth = stores- .control()- .verify_apply_authorization(- &ProtectedApplyCapability::new(capability).unwrap(),- &workspace,- &operation.idempotency.principal,- &operation.idempotency.operation_kind,- &operation.accepted_digest,- &operation.expected_revisions,- )- .unwrap();- assert_eq!(- stores.control().begin_operation(&operation, &auth).unwrap(),- BeginOperationOutcome::Created- );- operation-}-pub fn finish(stores: &LocalStorageSet, mut operation: OperationV1) {- operation.state = OperationState::Succeeded;- stores.control().finish_operation(&mut operation).unwrap();-}diff --git a/crates/client-core/tests/transport.rs b/crates/client-core/tests/transport.rsindex c6a9541f..28f5d3db 100644--- a/crates/client-core/tests/transport.rs+++ b/crates/client-core/tests/transport.rs@@ -400,6 +400,15 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {"cancel": {"state":"ready"},"continue_session": {"state":"unknown","reason":"capability_unverified"},"restricted_policy": {"state":"unknown","reason":"restricted_policy_unverified"}+ },+ {+ "harness": "pi",+ "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"}}]}),@@ -424,7 +433,8 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {[WorkerHarnessV1::CodexCli,WorkerHarnessV1::ClaudeCode,- WorkerHarnessV1::QoderCli+ WorkerHarnessV1::QoderCli,+ WorkerHarnessV1::Pi]);server.await.unwrap();diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rsindex 6e7c047e..132f8efc 100644--- a/crates/daemon/src/control/runtime.rs+++ b/crates/daemon/src/control/runtime.rs@@ -51,6 +51,7 @@ use crate::delegation::installation::{use crate::delegation::local_worker::LocalWorkerPlatform;use crate::delegation::run_authority::DelegationRunAuthority;+mod additional_model_budget;mod agent_connection;mod agent_live_check;mod candidate_execution;@@ -71,16 +72,15 @@ mod effects;mod model_catalog;mod model_connections;mod mutation;+mod native_additional_model;mod native_claude_model;mod native_model;-mod native_qoder_model;mod plan_content;mod plan_content_snapshot;mod plan_versions;mod prices;mod protected_inputs;mod publication;-mod qoder_model_budget;mod release_install;mod routing;mod settings_codex_profile;@@ -311,6 +311,14 @@ impl ProductionControlRuntime {).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));release_agent_scanner(&home,&project,@@ -318,6 +326,7 @@ impl ProductionControlRuntime {overrides.codex_desktop_engine,selected_claude,selected_qoder,+ selected_pi,)?}};@@ -354,11 +363,29 @@ impl ProductionControlRuntime {QODER_INTEGRATION_PROFILE_REF_V1,).map_err(|error| error.to_string())?;+ let pi_subject = AgentConnectionTransactionSubjectV1::from_registered_profile(+ "agent_pi_default",+ hiroute_integrations::PI_PROFILE_ID_V1,+ hiroute_integrations::PI_INTEGRATION_PROFILE_REF_V1,+ )+ .map_err(|error| error.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(&pi_subject)+ .map_err(|error| error.to_string())?,+ scanner.pi_user_models_target(),+ ),+ (+ AgentConnectionEffectRoleV1::RoutingSkill+ .target_for(&pi_subject)+ .map_err(|error| error.to_string())?,+ scanner.pi_user_skill_target(),+ ),(AgentConnectionEffectRoleV1::ManagedConfiguration.target_for(&qoder_subject)@@ -1269,6 +1296,7 @@ fn release_agent_scanner(codex_desktop_engine: Option<PathBuf>,selected_claude: Option<PathBuf>,selected_qoder: Option<PathBuf>,+ selected_pi: Option<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@@ -1286,6 +1314,9 @@ fn release_agent_scanner(if let Some(executable) = selected_qoder {layout.qoder_executable = executable;}+ if let Some(executable) = selected_pi {+ layout.pi_executable = executable;+ }Ok(FilesystemAgentScannerV1::new(layout, index))}@@ -1316,6 +1347,7 @@ fn discovered_agent(AgentKindV1::Codex => "codex-responses-v1",AgentKindV1::ClaudeCode => "claude-messages-v1",AgentKindV1::Qoder => QODER_PROFILE_ID_V1,+ AgentKindV1::Pi => hiroute_integrations::PI_PROFILE_ID_V1,}.to_owned(),version.clone(),diff --git a/crates/daemon/src/control/runtime/qoder_model_budget.rs b/crates/daemon/src/control/runtime/additional_model_budget.rssimilarity index 80%rename from crates/daemon/src/control/runtime/qoder_model_budget.rsrename to crates/daemon/src/control/runtime/additional_model_budget.rsindex 115ad939..86cd4cb6 100644--- a/crates/daemon/src/control/runtime/qoder_model_budget.rs+++ b/crates/daemon/src/control/runtime/additional_model_budget.rs@@ -1,7 +1,7 @@//! Installed native catalog budgets constrain subsequent publication updates.use super::LocalControlAdapter;use hiroute_application::agent_connection::{- QoderModelFileAction, settings_qoder_model_file_for_operation,+ AdditionalModelFileAction, settings_additional_model_file_for_operation,};use hiroute_domain::{AgentAccessGrantRefV1, AgentModelRouteV2, ControlRepositoryPort, OperationStepKind, PortError,@@ -12,7 +12,7 @@ use hiroute_domain::{impl LocalControlAdapter {/// A completed service segment still owns its native tail until exact recovery finishes./// Do not reinterpret a pending generation as an unconfigured native catalog.- pub(super) fn guard_qoder_pending_model_change(+ pub(super) fn guard_additional_pending_model_change(&self,same_operation: Option<&hiroute_domain::OperationId>,) -> PortResult<()> {@@ -21,7 +21,7 @@ impl LocalControlAdapter {/// Run at admission and again before sealing Install. A published smaller budget would/// otherwise leave Qoder sending requests under a larger persisted native declaration.- pub(super) fn validate_qoder_installed_model_budgets(+ pub(super) fn validate_additional_installed_model_budgets(&self,record: &PublicationRecordV1,) -> PortResult<()> {@@ -31,16 +31,14 @@ impl LocalControlAdapter {&WorkspaceId::default(),"ApplyAgentConnectionChange",)? {- let Some(intent) = operation- .plan- .external()- .iter()- .find(|intent| super::native_qoder_model::is_settings_qoder_model(intent))- else {+ let Some(intent) = operation.plan.external().iter().find(|intent| {+ super::native_additional_model::is_settings_additional_model(intent)+ }) else {continue;};- let payload = settings_qoder_model_file_for_operation(&operation, intent)?;- let QoderModelFileAction::Configure { models, .. } = payload.change else {+ let payload = settings_additional_model_file_for_operation(&operation, intent)?;+ let kind = hiroute_application::agent_connection::additional_model_kind(intent)?;+ let AdditionalModelFileAction::Configure { models, .. } = payload.change else {continue;};let [mutation] = operation.plan.agent_access_grants() else {@@ -81,8 +79,12 @@ impl LocalControlAdapter {.clone().into_current().map_err(|_| shrinking())?;- let budget = hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)- .map_err(|_| shrinking())?;+ let budget = (if kind == hiroute_domain::AgentKindV1::Pi {+ hiroute_integrations::pi_plan_token_budget(&plan.body.materialized)+ } else {+ hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)+ })+ .map_err(|_| shrinking())?;if budget.context_window_tokens < model.context_window_tokens|| budget.max_output_tokens < model.max_output_tokens{@@ -114,7 +116,7 @@ pub(super) fn guard_pending_model_change(.plan.external().iter()- .any(super::native_qoder_model::is_settings_qoder_model)+ .any(super::native_additional_model::is_settings_additional_model){return Err(PortError::new(PortErrorCode::Conflict,diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rsindex 3c5a6d8c..a793d8f7 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_pi_default" {+ return self+ .scanner+ .check_pi_collaboration(&cli)+ .map_err(|_| ControlReadError::Unavailable.into());+ }if agent_id == "agent_qoder_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 93f10290..b20b795b 100644--- a/crates/daemon/src/control/runtime/agent_live_check.rs+++ b/crates/daemon/src/control/runtime/agent_live_check.rs@@ -101,6 +101,7 @@ 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::QoderCli => {self.execute_qoder_live_attempt(&target.context_id, model, trust, deadline)}diff --git a/crates/daemon/src/control/runtime/agent_live_check_qoder.rs b/crates/daemon/src/control/runtime/agent_live_check_qoder.rsindex 55c5ddbf..e90c4592 100644--- a/crates/daemon/src/control/runtime/agent_live_check_qoder.rs+++ b/crates/daemon/src/control/runtime/agent_live_check_qoder.rs@@ -48,7 +48,7 @@ impl LocalControlAdapter {.map_err(|_| unavailable())?;let native_model = format!("{}/{}",- hiroute_application::agent_connection::qoder_model_provider_id(context_id),+ hiroute_application::agent_connection::additional_model_provider_id(context_id),model);let mut command = Command::new(executable);diff --git a/crates/daemon/src/control/runtime/candidate_execution.rs b/crates/daemon/src/control/runtime/candidate_execution.rsindex 092ff5cf..ec678895 100644--- a/crates/daemon/src/control/runtime/candidate_execution.rs+++ b/crates/daemon/src/control/runtime/candidate_execution.rs@@ -272,6 +272,7 @@ pub(super) fn materialize_management_candidate((hiroute_domain::ComputeManagementProvenanceV2::UserConfigured { .. },ComputeManagementEligibilityV2::UserConfirmed+ | ComputeManagementEligibilityV2::NativeObserved| ComputeManagementEligibilityV2::RuntimeQualified,) => None,(diff --git a/crates/daemon/src/control/runtime/candidate_execution_tests.rs b/crates/daemon/src/control/runtime/candidate_execution_tests.rsindex a9b5e719..1be546fe 100644--- a/crates/daemon/src/control/runtime/candidate_execution_tests.rs+++ b/crates/daemon/src/control/runtime/candidate_execution_tests.rs@@ -1224,6 +1224,77 @@ fn unknown_native_text_uses_execution_defaults_without_overwriting_unknown_factsassert!(fact.capabilities.tool.value.is_none());assert!(candidate.free_evidence.is_none());assert!(candidate.ordering_price.is_none());+ // Native observations keep their measured limits and source-local target,+ // including a loopback HTTP API, rather than acquiring Registry authority.+ let mut imported = fact.clone();+ imported.eligibility = ComputeManagementEligibilityV2::NativeObserved;+ imported.capabilities.context_tokens = hiroute_domain::ComputeManagementFactValueV2 {+ value: Some(16_384),+ basis: hiroute_domain::ComputeManagementFactBasisV2::Observed,+ };+ imported.capabilities.max_output_tokens = hiroute_domain::ComputeManagementFactValueV2 {+ value: Some(4_096),+ basis: hiroute_domain::ComputeManagementFactBasisV2::Observed,+ };+ let native = materialize_management_candidate(&imported, None).unwrap();+ assert_eq!(native.authority, CandidateFactAuthorityV1::SourceLocalUser);+ assert_eq!(native.model.capabilities.context_tokens, 16_384);+ assert_eq!(native.model.capabilities.max_output_tokens, 4_096);+ assert_eq!(native.operational_target, candidate.operational_target);+ for (protocol, path) in [+ (UpstreamProtocol::Responses, "/v1/responses"),+ (UpstreamProtocol::ChatCompletions, "/v1/chat/completions"),+ (UpstreamProtocol::Messages, "/v1/messages"),+ ] {+ for parameter in [+ "enable_thinking",+ "deepseek_thinking",+ "reasoning_effort",+ "thinking_budget",+ "custom_toggle",+ ] {+ let mut toggled = imported.clone();+ toggled.target.upstream_protocol = protocol;+ toggled.target.request_path = path.into();+ toggled.native_reasoning = NativeReasoningCapabilityV1::Toggle {+ parameter: parameter.into(),+ };+ let native = materialize_management_candidate(&toggled, None).unwrap();+ for enabled in [false, true] {+ let selection = hiroute_domain::AgentFixedModelSelectionV2 {+ client_model_id: "native-route".into(),+ candidate: hiroute_domain::CandidateSelectionV1 {+ binding_id: native.binding.binding_id.clone(),+ reasoning: Some(hiroute_domain::ReasoningSelectionV1::Toggle { enabled }),+ },+ };+ // Follow actual renderer output through both the compiler and+ // Gateway ingestion; matching the Domain alone is insufficient.+ let routes = hiroute_application::compiler::compile_fixed_model_bindings(+ &[selection],+ std::slice::from_ref(&native),+ )+ .unwrap();+ assert_eq!(+ routes["native-route"].operational_target,+ native.operational_target+ );+ for profile in &routes["native-route"].protocol_profiles {+ let gateway: hiroute_gateway::server::core_runtime::profiles::CandidateProtocolProfile =+ serde_json::from_value(serde_json::to_value(profile).unwrap()).unwrap();+ assert!(+ gateway+ .capability+ .reasoning_profiles+ .iter()+ .all(|reasoning| reasoning+ .validate_for(gateway.capability.upstream_protocol)),+ "{parameter} {protocol:?} {enabled}"+ );+ }+ }+ }+ }let mut second_source = fact.clone();second_source.source_id = "second-source-same-model".into();second_source.binding_id = "binding/second-source".into();diff --git a/crates/daemon/src/control/runtime/candidate_protocol_profiles.rs b/crates/daemon/src/control/runtime/candidate_protocol_profiles.rsindex 649d4f13..e895354a 100644--- a/crates/daemon/src/control/runtime/candidate_protocol_profiles.rs+++ b/crates/daemon/src/control/runtime/candidate_protocol_profiles.rs@@ -407,18 +407,5 @@ pub(super) fn field(}pub(super) fn parameter_path(parameter: &str, protocol: UpstreamProtocol) -> Vec<String> {- // ModelData names the portable discrete control. The exact protocol- // renderer owns its wire location: OpenAI Responses nests effort while- // Chat Completions keeps the historical top-level field.- if protocol == UpstreamProtocol::Responses && parameter == "reasoning_effort" {- return vec!["reasoning".into(), "effort".into()];- }- if parameter == "thinking_budget" {- return match protocol {- UpstreamProtocol::Responses => vec!["reasoning".into(), "max_output_tokens".into()],- UpstreamProtocol::Messages => vec!["thinking".into(), "budget_tokens".into()],- UpstreamProtocol::ChatCompletions => vec!["thinking_budget".into()],- };- }- parameter.split('.').map(str::to_owned).collect()+ GatewayNativeReasoningFieldAssignmentV1::parameter_path(parameter, protocol)}diff --git a/crates/daemon/src/control/runtime/collaboration_installation.rs b/crates/daemon/src/control/runtime/collaboration_installation.rsindex 3b95fa96..9ec363f8 100644--- a/crates/daemon/src/control/runtime/collaboration_installation.rs+++ b/crates/daemon/src/control/runtime/collaboration_installation.rs@@ -81,7 +81,7 @@ impl LocalControlAdapter {)?;}// Only historical clients ever owned sealed collaboration credentials.- if class == SettingsAgentClass::Qoder {+ if matches!(class, SettingsAgentClass::Qoder | SettingsAgentClass::Pi) {return Ok(());}let legacy = self.legacy_collaboration_artifact_path(&spec.context_id)?;@@ -109,7 +109,7 @@ impl LocalControlAdapter {self.scanner.codex_user_config_target()}SettingsAgentClass::Claude => self.scanner.claude_user_settings_target(),- SettingsAgentClass::Qoder => return Err(error()),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi => return Err(error()),};let home = native.parent()@@ -121,7 +121,7 @@ impl LocalControlAdapter {.join(match class {SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => "codex.sealed",SettingsAgentClass::Claude => "claude-code.sealed",- SettingsAgentClass::Qoder => return Err(error()),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi => return Err(error()),}))}}diff --git a/crates/daemon/src/control/runtime/compute_routing.rs b/crates/daemon/src/control/runtime/compute_routing.rsindex 046f18da..e406fc43 100644--- a/crates/daemon/src/control/runtime/compute_routing.rs+++ b/crates/daemon/src/control/runtime/compute_routing.rs@@ -62,6 +62,19 @@ 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);+ }let catalog = self.release_catalog.as_ref()@@ -241,6 +254,7 @@ impl ComputeFactsPort for LocalControlAdapter {.iter().map(|discovery| scan_item(catalog, discovery)).collect::<Result<Vec<_>, _>>()?;+ items.extend(self.pi_compute_scan_items()?);// 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));@@ -517,6 +531,7 @@ fn scan_item(agent_id,supported,configuration_state,+ native_provider_id: None,discovered_source_ref: if protected_prepare {None} else {diff --git a/crates/daemon/src/control/runtime/compute_routing/tests.rs b/crates/daemon/src/control/runtime/compute_routing/tests.rsindex 416c5227..610797e3 100644--- a/crates/daemon/src/control/runtime/compute_routing/tests.rs+++ b/crates/daemon/src/control/runtime/compute_routing/tests.rs@@ -304,7 +304,8 @@ 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).unwrap();+ super::super::release_agent_scanner(&home, &project, &catalog, None, None, None, None)+ .unwrap();assert_eq!(scanner.claude_executable_target(),std::path::PathBuf::from("claude")@@ -317,6 +318,7 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot()None,Some(selected_claude.clone()),None,+ None,).unwrap();assert_eq!(selected_scanner.claude_executable_target(), selected_claude);diff --git a/crates/daemon/src/control/runtime/delegation_continue.rs b/crates/daemon/src/control/runtime/delegation_continue.rsindex 452c0a13..232469db 100644--- a/crates/daemon/src/control/runtime/delegation_continue.rs+++ b/crates/daemon/src/control/runtime/delegation_continue.rs@@ -121,7 +121,7 @@ impl LocalControlAdapter {&request.submission_key,).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;- self.ensure_worker_dependencies(prior_task.plan.harness)?;+ self.ensure_worker_dependencies(prior_task.plan.harness, true)?;let execution = request.execution(prior_task.workspace.root_identity.clone());let deadline_ms = now_ms.checked_add(execution.duration_ms)diff --git a/crates/daemon/src/control/runtime/delegation_task_queries.rs b/crates/daemon/src/control/runtime/delegation_task_queries.rsindex 2172cd6b..1fc02b2f 100644--- a/crates/daemon/src/control/runtime/delegation_task_queries.rs+++ b/crates/daemon/src/control/runtime/delegation_task_queries.rs@@ -257,6 +257,7 @@ pub(super) fn run_view(task: &DelegationTaskV1, run: &DelegationRunV1) -> Delegahiroute_domain::delegation::WorkerHarnessV1::CodexCli => "Codex",hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode => "Claude Code",hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "Qoder",+ hiroute_domain::delegation::WorkerHarnessV1::Pi => "Pi",};DelegationRunViewV1 {task_id: run.task_id.clone(),diff --git a/crates/daemon/src/control/runtime/delegation_worker.rs b/crates/daemon/src/control/runtime/delegation_worker.rsindex 9fa0a194..8527eb56 100644--- a/crates/daemon/src/control/runtime/delegation_worker.rs+++ b/crates/daemon/src/control/runtime/delegation_worker.rs@@ -120,7 +120,7 @@ impl LocalControlAdapter {AdmissionAction::Start,&request.submission_key,)?;- self.ensure_worker_dependencies(selected.binding.harness)?;+ self.ensure_worker_dependencies(selected.binding.harness, false)?;let deadline_ms = now_ms.checked_add(execution.duration_ms).ok_or(DelegationErrorV1::DeadlineExceeded)?;@@ -371,14 +371,18 @@ impl LocalControlAdapter {pub(super) fn ensure_worker_dependencies(&self,harness: hiroute_domain::delegation::WorkerHarnessV1,+ continuing: bool,) -> Result<(), DelegationErrorV1> {let selection =crate::delegation::installation::WorkerInstallationSelectionSource::selection(self, harness,)?.ok_or(DelegationErrorV1::DependenciesMissing)?;- crate::delegation::installation::validate_persisted_installation(&selection.config)- .map(|_| ())+ crate::delegation::installation::validate_persisted_installation_for_run(+ &selection.config,+ continuing,+ )+ .map(|_| ())}}diff --git a/crates/daemon/src/control/runtime/effects.rs b/crates/daemon/src/control/runtime/effects.rsindex 04117789..977ed148 100644--- a/crates/daemon/src/control/runtime/effects.rs+++ b/crates/daemon/src/control/runtime/effects.rs@@ -109,8 +109,8 @@ impl LocalControlAdapter {hiroute_application::agent_connection::decode_settings_claude_model_file(intent)?;return Ok(None);}- if super::native_qoder_model::is_settings_qoder_model(intent) {- hiroute_application::agent_connection::decode_settings_qoder_model_file(intent)?;+ if super::native_additional_model::is_settings_additional_model(intent) {+ hiroute_application::agent_connection::decode_settings_additional_model_file(intent)?;return Ok(None);}let envelope: AgentConfigurationEnvelopeV1 =@@ -244,6 +244,9 @@ impl ExternalEffectPort for LocalControlAdapter {intent: &ExternalEffectIntentV1,) -> PortResult<()> {self.acknowledge_clean_codex_restoration(operation, intent)?;+ if super::native_additional_model::is_settings_additional_model(intent) {+ self.validate_additional_model_dependencies(operation, intent)?;+ }if intent.effect_id() == "agent-connection-routing-skill"&& intent.desired()["transaction"] == "settings"{@@ -365,8 +368,8 @@ impl ExternalEffectPort for LocalControlAdapter {if super::native_claude_model::is_settings_claude_model(intent) {return self.stage_settings_claude_model(operation, intent);}- if super::native_qoder_model::is_settings_qoder_model(intent) {- return self.stage_settings_qoder_model(operation, intent);+ if super::native_additional_model::is_settings_additional_model(intent) {+ return self.stage_settings_additional_model(operation, intent);}let Some(permission) = self.permission_intent(intent)? else {if let Some(change) = self.native_claude_change(intent)? {@@ -477,6 +480,12 @@ impl ExternalEffectPort for LocalControlAdapter {return self.activate_publication(operation, effect);}if effect.effect_id != EFFECT_ID {+ for intent in operation.plan.external().iter().filter(|intent| {+ intent.target() == effect.target+ && super::native_additional_model::is_settings_additional_model(intent)+ }) {+ self.validate_additional_model_dependencies(operation, intent)?;+ }return self.artifacts.activate_artifact(effect);}let (operation_id, intent) = self.permission_marker(effect)?;diff --git a/crates/daemon/src/control/runtime/model_connections.rs b/crates/daemon/src/control/runtime/model_connections.rsindex 12bc156d..5a7c563a 100644--- a/crates/daemon/src/control/runtime/model_connections.rs+++ b/crates/daemon/src/control/runtime/model_connections.rs@@ -35,6 +35,7 @@ use super::LocalControlAdapter;mod discovered;mod key_inputs;+mod pi_discovered;mod presentation;mod registered;mod saved;diff --git a/crates/daemon/src/control/runtime/model_connections/discovered.rs b/crates/daemon/src/control/runtime/model_connections/discovered.rsindex bf588215..e12fa0b2 100644--- a/crates/daemon/src/control/runtime/model_connections/discovered.rs+++ b/crates/daemon/src/control/runtime/model_connections/discovered.rs@@ -130,6 +130,18 @@ impl LocalControlAdapter {candidate.discovery.discovery_ref == request.discovery.discovery_ref&& candidate.discovery.discovery_revision == request.discovery.discovery_revision}) else {+ if let Some(source) = self+ .scanner+ .pi_api_sources()+ // An unreadable unrelated source must not replace the selected+ // discovery result (including stale/forged Claude handles).+ // No matching Pi source still fails below; no candidate is created.+ .unwrap_or_default()+ .into_iter()+ .find(|source| super::pi_discovered::pi_discovery(source) == request.discovery)+ {+ return self.prepare_pi_discovered_candidate(source, &request.prepare_id);+ }return Err(if current_exists {ComputeManagementControlError::DiscoveryChanged} else if recognized_configuration {diff --git a/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs b/crates/daemon/src/control/runtime/model_connections/pi_discovered.rsnew file mode 100644index 00000000..5da29101--- /dev/null+++ b/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs@@ -0,0 +1,233 @@+//! Pi sources use the same closed prepare/save transaction as other native API discoveries.+use super::*;+use hiroute_application_api::{ComputeDiscoveryRefV1, ComputeScanItemV1};+use hiroute_integrations::{DiscoveredAuthSource, PiApiSource};++pub(super) fn pi_discovery(source: &PiApiSource) -> ComputeDiscoveryRefV1 {+ ComputeDiscoveryRefV1 {+ discovery_ref: format!("discovery/{}", &source.evidence_digest.as_str()[7..]),+ discovery_revision: source.revision,+ }+}+impl LocalControlAdapter {+ pub(in crate::control::runtime) fn pi_compute_scan_items(+ &self,+ ) -> Result<Vec<ComputeScanItemV1>, hiroute_application::control::ControlReadError> {+ let sources = match self.scanner.pi_api_sources() {+ Ok(sources) => sources,+ Err(_) => {+ return Ok(vec![ComputeScanItemV1 {+ agent_id: "agent_pi_default".into(),+ supported: false,+ native_provider_id: None,+ configuration_state: "configuration_unavailable".into(),+ discovered_source_ref: None,+ connection_option_id: None,+ endpoint_profile_id: None,+ registered_base_url: None,+ observed_model_id: None,+ model_configuration_id: None,+ inventory_eligible: false,+ discovery: None,+ actions_required: vec!["check_pi_configuration".into()],+ permission_action: None,+ credential_import: None,+ }]);+ }+ };+ sources+ .into_iter()+ .map(|source| {+ let ready = source.supported_auth+ && source.protocol.is_some()+ && source.credential.is_some();+ let reason = if !source.supported_auth || source.protocol.is_none() {+ "native_configuration_not_importable"+ } else {+ match source.authentication {+ DiscoveredAuthSource::HelperNeedsInput => {+ "credential_helper_requires_input"+ }+ DiscoveredAuthSource::NativeSessionNeedsConfirmation => {+ "native_oauth_not_imported"+ }+ _ => "credential_import_required",+ }+ };+ let discovery = ready.then(|| pi_discovery(&source));+ Ok(ComputeScanItemV1 {+ agent_id: "agent_pi_default".into(),+ supported: true,+ native_provider_id: Some(source.provider_id),+ configuration_state: if ready {+ "static_api_with_protected_input"+ } else {+ reason+ }+ .into(),+ discovered_source_ref: None,+ connection_option_id: None,+ endpoint_profile_id: None,+ registered_base_url: None,+ observed_model_id: Some(source.model_id),+ model_configuration_id: None,+ inventory_eligible: ready,+ discovery,+ actions_required: if ready {+ Vec::new()+ } else {+ vec![reason.into()]+ },+ permission_action: None,+ credential_import: None,+ })+ })+ .collect()+ }+ pub(super) fn prepare_pi_discovered_candidate(+ &self,+ source: PiApiSource,+ prepare_id: &str,+ ) -> Result<ComputeCandidateViewV2, ComputeManagementControlError> {+ if !source.supported_auth || source.credential.is_none() {+ return Err(ComputeManagementControlError::DiscoveryNotImportable);+ }+ let protocol = source+ .protocol+ .ok_or(ComputeManagementControlError::DiscoveryNotImportable)?;+ let (base_url, secret) = self+ .scanner+ .read_pi_api_source(&source)+ .map_err(|_| ComputeManagementControlError::DiscoveryChanged)?;+ let credential = source+ .credential+ .as_ref()+ .ok_or(ComputeManagementControlError::DiscoveryNotImportable)?;+ let input_slot = super::super::mutation::protected_input_slot(credential)+ .map_err(|_| ComputeManagementControlError::Corrupt)?;+ let descriptor = ProtectedInputSourceDescriptorV1::DiscoveredConfig {+ scanner_id: credential.scanner_id.clone(),+ scanner_version: credential.scanner_version.clone(),+ source_ref: credential.discovered_source_ref.clone(),+ field_selector: credential.field_selector.clone(),+ observed_revision: credential.observed_revision,+ };+ let candidate_digest = hiroute_domain::CanonicalDigest::of(&(+ "pi-discovered-candidate/v1",+ &source.evidence_digest,+ prepare_id,+ ))+ .map_err(|_| ComputeManagementControlError::Corrupt)?;+ let candidate = ComputeCandidateRefV2 {+ candidate_ref: format!(+ "candidate/native-discovery/{}",+ &candidate_digest.as_str()[7..]+ ),+ candidate_revision: 1,+ };+ if let Ok(view) = self+ .model_connections+ .candidate_port()+ .get_compute_candidate(&candidate)+ {+ return Ok(view);+ }+ self.model_connections+ .reserve_candidate_ref(&candidate)+ .map_err(|_| ComputeManagementControlError::Conflict)?;+ let observed = |v| NativeCandidateFactValueV1 {+ value: v,+ basis: if v.is_some() {+ NativeCandidateFactBasisV1::Observed+ } else {+ NativeCandidateFactBasisV1::Unknown+ },+ };+ let capability = NativeModelCapabilityDeclarationV1 {+ tool: NativeCandidateFactValueV1::unknown(),+ vision: observed(source.vision),+ streaming: NativeCandidateFactValueV1::unknown(),+ context_tokens: NativeCandidateFactValueV1 {+ value: source.context_tokens,+ basis: if source.context_tokens.is_some() {+ NativeCandidateFactBasisV1::Observed+ } else {+ NativeCandidateFactBasisV1::Unknown+ },+ },+ max_output_tokens: NativeCandidateFactValueV1 {+ value: source.max_output_tokens,+ basis: if source.max_output_tokens.is_some() {+ NativeCandidateFactBasisV1::Observed+ } else {+ NativeCandidateFactBasisV1::Unknown+ },+ },+ native_reasoning: NativeCandidateFactValueV1::unknown(),+ };+ let draft = NativeModelConnectionDraftV1 {+ display_template_id: None,+ inference_model_id: None,+ candidate_ref: Some(candidate.candidate_ref),+ lineage_ref: pi_discovery(&source).discovery_ref,+ trusted_lineage_digest: None,+ display_name: format!("Pi · {}", source.provider_id),+ existing_source_id: None,+ edit_revision: source.revision,+ check_id: prepare_id.into(),+ base_url: base_url.to_string(),+ base_kind: if protocol == UpstreamProtocol::Messages {+ ModelConnectionBaseKindV1::NativeMessagesBase+ } else {+ ModelConnectionBaseKindV1::NativeResponsesBase+ },+ request_path_override: None,+ inventory_path_override: None,+ protocol,+ protocol_profile_id: match protocol {+ UpstreamProtocol::Responses => "adapter.openai-responses.v1",+ UpstreamProtocol::Messages => "adapter.anthropic-messages.v1",+ UpstreamProtocol::ChatCompletions => "adapter.openai-chat-completions.v1",+ }+ .into(),+ protocol_profile_revision: 1,+ protocol_header_semantics: super::custom_endpoint_headers(protocol),+ authentication: if protocol == UpstreamProtocol::Messages {+ GatewayAuthenticationSemanticsV1::ApiKeyHeader {+ header: "x-api-key".into(),+ }+ } else {+ GatewayAuthenticationSemanticsV1::Bearer+ },+ additional_native_endpoints: Vec::new(),+ provenance: NativeConnectionProvenanceInputV1::UserConfigured {+ configuration_revision: source.revision,+ },+ qualification: NativeConnectionQualificationV1 {+ free_access: None,+ evidence_ref: None,+ },+ runtime_fallback_denied_model_ids: super::runtime_fallback_denied_model_ids(+ self.release_catalog.as_ref(),+ ),+ models: vec![NativeModelDeclarationV1 {+ upstream_model_id: source.model_id,+ display_name: source.display_name,+ catalog_configuration_id: None,+ membership: ComputeModelMembershipV2::Observed,+ capabilities: capability,+ }],+ };+ self.model_connections+ .prepare_observed_discovery(+ draft,+ NativeModelConnectionCredentialV1::Protected {+ descriptor,+ input_slot,+ secret: &secret,+ },+ source.evidence_digest,+ )+ .map_err(|_| ComputeManagementControlError::Corrupt)+ }+}diff --git a/crates/daemon/src/control/runtime/mutation.rs b/crates/daemon/src/control/runtime/mutation.rsindex 87f54b94..a1c8f54f 100644--- a/crates/daemon/src/control/runtime/mutation.rs+++ b/crates/daemon/src/control/runtime/mutation.rs@@ -132,6 +132,14 @@ impl LocalControlAdapter {return Err("protected discovery slot collision".to_owned());}}+ for source in self.scanner.pi_api_sources().unwrap_or_default() {+ if let Some(descriptor) = source.credential {+ let slot = protected_input_slot(&descriptor)?;+ if inputs.insert(slot, descriptor).is_some() {+ return Err("protected discovery slot collision".into());+ }+ }+ }*self.permission_findings.lock()@@ -221,7 +229,7 @@ impl ControlRepositoryPort for LocalControlAdapter {fn begin_local_operation(&self, operation: &OperationV1) -> PortResult<BeginOperationOutcome> {self.guard_codex_pending_change(Some(&operation.operation_id))?;let stores = self.stores_lock()?;- super::qoder_model_budget::guard_pending_model_change(+ super::additional_model_budget::guard_pending_model_change(stores.control(),Some(&operation.operation_id),)?;@@ -254,7 +262,7 @@ impl ControlRepositoryPort for LocalControlAdapter {) -> PortResult<BeginOperationOutcome> {self.guard_codex_pending_change(Some(&operation.operation_id))?;let stores = self.stores_lock()?;- super::qoder_model_budget::guard_pending_model_change(+ super::additional_model_budget::guard_pending_model_change(stores.control(),Some(&operation.operation_id),)?;diff --git a/crates/daemon/src/control/runtime/native_qoder_model.rs b/crates/daemon/src/control/runtime/native_additional_model.rssimilarity index 64%rename from crates/daemon/src/control/runtime/native_qoder_model.rsrename to crates/daemon/src/control/runtime/native_additional_model.rsindex 37cfa5dc..19c4308b 100644--- a/crates/daemon/src/control/runtime/native_qoder_model.rs+++ b/crates/daemon/src/control/runtime/native_additional_model.rs@@ -1,32 +1,42 @@-//! Qoder's additive model file is an ordinary protected settings effect.+//! Shared additional-provider settings effects; native cross-file dependencies remain explicit.use super::LocalControlAdapter;use hiroute_application::agent_connection::{- QoderModelFileAction, settings_qoder_model_file_for_operation,+ AdditionalModelFileAction, additional_model_kind, settings_additional_model_file_for_operation,};use hiroute_domain::{- AgentAccessGrantRefV1, AgentIngressProtocolV1, AgentModelGrantV2, AgentModelRouteV2,- ControlRepositoryPort, ExternalEffectIntentV1, GatewayPublicationV1, OperationState,- OperationStepKind, OperationV1, OwnedEffectV1, PortError, PortErrorCode, PortResult,- QoderAdditionalModelV1, SecretStorePort, WorkspaceId, is_agent_access_grant_effect,+ AdditionalAgentModelV1, AgentAccessGrantRefV1, AgentIngressProtocolV1, AgentKindV1,+ AgentModelGrantV2, AgentModelRouteV2, ControlRepositoryPort, ExternalEffectIntentV1,+ GatewayPublicationV1, OperationState, OperationStepKind, OperationV1, OwnedEffectV1, PortError,+ PortErrorCode, PortResult, SecretStorePort, WorkspaceId, is_agent_access_grant_effect,};-pub(super) fn is_settings_qoder_model(intent: &ExternalEffectIntentV1) -> bool {+pub(super) fn is_settings_additional_model(intent: &ExternalEffectIntentV1) -> bool {intent.effect_id() == "agent-connection-managed-configuration"&& intent.desired()["transaction"] == "settings"- && intent.desired()["subject"]["agent_id"] == "agent_qoder_default"+ && matches!(+ intent.desired()["subject"]["agent_id"].as_str(),+ Some("agent_qoder_default" | "agent_pi_default")+ )}-pub(super) fn qoder_model_endpoint(gateway_base_url: &str) -> PortResult<String> {+pub(super) fn additional_model_endpoint(+ kind: AgentKindV1,+ gateway_base_url: &str,+) -> PortResult<String> {+ if kind == AgentKindV1::Pi {+ return Ok(gateway_base_url.to_owned());+ }let origin = gateway_base_url.strip_suffix("/v1").ok_or_else(|| conflict("qoder.settings.endpoint"))?;Ok(format!("{origin}{}", hiroute_domain::QODER_MODEL_BASE_PATH))}-pub(super) fn qoder_models_for_grant(+pub(super) fn additional_models_for_grant(+ kind: AgentKindV1,publication: &GatewayPublicationV1,grant: &AgentModelGrantV2,-) -> PortResult<Vec<QoderAdditionalModelV1>> {+) -> PortResult<Vec<AdditionalAgentModelV1>> {grant.routes.iter()@@ -53,9 +63,13 @@ pub(super) fn qoder_models_for_grant(if &plan.body.materialized_route_digest != semantic_digest {return Err(conflict("qoder.models.plan.digest"));}- let budget = hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)- .map_err(|_| conflict("qoder.models.budget"))?;- Ok(QoderAdditionalModelV1 {+ let budget = (if kind == AgentKindV1::Pi {+ hiroute_integrations::pi_plan_token_budget(&plan.body.materialized)+ } else {+ hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)+ })+ .map_err(|_| conflict("qoder.models.budget"))?;+ Ok(AdditionalAgentModelV1 {alias: name.clone(),context_window_tokens: budget.context_window_tokens,max_output_tokens: budget.max_output_tokens,@@ -65,7 +79,37 @@ pub(super) fn qoder_models_for_grant(}impl LocalControlAdapter {- pub(super) fn stage_settings_qoder_model(+ /// Recheck independent native files at stage and final activation, including recovery.+ pub(super) fn validate_additional_model_dependencies(+ &self,+ operation: &OperationV1,+ intent: &ExternalEffectIntentV1,+ ) -> PortResult<()> {+ let payload = settings_additional_model_file_for_operation(operation, intent)?;+ if let Some(expected) = &payload.pi_settings_content {+ let settings = self+ .scanner+ .pi_default_model()+ .map_err(|_| conflict("pi.settings.default"))?;+ let models = match &payload.change {+ AdditionalModelFileAction::Configure { models, .. } => models.as_slice(),+ _ => &[],+ };+ if &settings.content_digest != expected+ || settings.removes_default(+ &hiroute_application::agent_connection::additional_model_provider_id(+ &payload.context_id,+ ),+ models,+ )+ {+ return Err(conflict("pi.settings.default.changed"));+ }+ }+ Ok(())+ }++ pub(super) fn stage_settings_additional_model(&self,operation: &OperationV1,intent: &ExternalEffectIntentV1,@@ -73,10 +117,12 @@ impl LocalControlAdapter {if operation.state != OperationState::ApplyingAgentArtifacts {return Err(conflict("qoder.settings.phase"));}- let payload = settings_qoder_model_file_for_operation(operation, intent)?;+ let payload = settings_additional_model_file_for_operation(operation, intent)?;+ let kind = additional_model_kind(intent)?;+ self.validate_additional_model_dependencies(operation, intent)?;let stores = self.stores_lock()?;match &payload.change {- QoderModelFileAction::Configure {+ AdditionalModelFileAction::Configure {previous_operation,provider_id,endpoint,@@ -101,7 +147,7 @@ impl LocalControlAdapter {.as_ref().map(|runtime| runtime.gateway_base_url.clone()).ok_or_else(|| conflict("qoder.settings.runtime"))?;- if qoder_model_endpoint(&gateway_base_url)? != *endpoint {+ if additional_model_endpoint(kind, &gateway_base_url)? != *endpoint {return Err(conflict("qoder.settings.endpoint"));}let active = stores@@ -112,7 +158,7 @@ impl LocalControlAdapter {.control().load_operation(id)?.ok_or_else(|| conflict("qoder.settings.previous"))?;- let previous_intent = qoder_original_intent(&original, operation, intent)?;+ let previous_intent = additional_original_intent(&original, operation, intent)?;let [previous_mutation] = original.plan.agent_access_grants() else {return Err(conflict("qoder.settings.previous.grant"));};@@ -141,7 +187,7 @@ impl LocalControlAdapter {.secrets().resolve_prepared_agent_access_grant(&operation.operation_id, mutation)?;drop(stores);- let configuration = hiroute_integrations::QoderFileConfiguration {+ let configuration = hiroute_integrations::AdditionalFileConfiguration {expected_content: &payload.expected_content,provider_id,endpoint,@@ -150,7 +196,7 @@ impl LocalControlAdapter {};match previous {Some((original, previous_intent)) => {- hiroute_integrations::stage_qoder_reconfiguration(+ hiroute_integrations::stage_additional_reconfiguration(&self.artifacts,&operation.operation_id,intent,@@ -159,7 +205,7 @@ impl LocalControlAdapter {configuration,)}- None => hiroute_integrations::stage_qoder_configuration(+ None => hiroute_integrations::stage_additional_configuration(&self.artifacts,&operation.operation_id,intent,@@ -167,14 +213,14 @@ impl LocalControlAdapter {),}}- QoderModelFileAction::Restore { original_operation } => {+ AdditionalModelFileAction::Restore { original_operation } => {let original = stores.control().load_operation(original_operation)?.ok_or_else(|| conflict("qoder.settings.restore.original"))?;- let original_intent = qoder_original_intent(&original, operation, intent)?;+ let original_intent = additional_original_intent(&original, operation, intent)?;drop(stores);- hiroute_integrations::stage_qoder_restoration(+ hiroute_integrations::stage_additional_restoration(&self.artifacts,&operation.operation_id,intent,@@ -186,7 +232,7 @@ impl LocalControlAdapter {}}-fn qoder_original_intent(+fn additional_original_intent(original: &OperationV1,operation: &OperationV1,intent: &ExternalEffectIntentV1,@@ -202,13 +248,13 @@ fn qoder_original_intent(.external().iter().find(|candidate| {- candidate.target() == intent.target() && is_settings_qoder_model(candidate)+ candidate.target() == intent.target() && is_settings_additional_model(candidate)}).ok_or_else(|| conflict("qoder.settings.original.intent"))?;- let before = settings_qoder_model_file_for_operation(original, original_intent)?;- let after = settings_qoder_model_file_for_operation(operation, intent)?;+ let before = settings_additional_model_file_for_operation(original, original_intent)?;+ let after = settings_additional_model_file_for_operation(operation, intent)?;if before.context_id != after.context_id- || !matches!(before.change, QoderModelFileAction::Configure { .. })+ || !matches!(before.change, AdditionalModelFileAction::Configure { .. }){return Err(conflict("qoder.settings.original.context"));}diff --git a/crates/daemon/src/control/runtime/publication/lifecycle.rs b/crates/daemon/src/control/runtime/publication/lifecycle.rsindex b0c40de3..0e19e33b 100644--- a/crates/daemon/src/control/runtime/publication/lifecycle.rs+++ b/crates/daemon/src/control/runtime/publication/lifecycle.rs@@ -20,7 +20,7 @@ impl LocalControlAdapter {return Ok(());}self.guard_codex_pending_change(None)?;- self.guard_qoder_pending_model_change(None)?;+ self.guard_additional_pending_model_change(None)?;if intent.desired()["transaction"] == "settings" {hiroute_domain::validate_settings_model_publication_intent(intent).map_err(|_| invalid("publication.settings.admission"))?;@@ -28,7 +28,7 @@ impl LocalControlAdapter {if let Some(record) = routing_publication_record(intent).map_err(|_| invalid("publication.admission.record"))?{- self.validate_qoder_installed_model_budgets(&record)?;+ self.validate_additional_installed_model_budgets(&record)?;record.verify().map_err(|_| invalid("publication.admission.verify"))?@@ -75,7 +75,7 @@ impl LocalControlAdapter {) -> PortResult<()> {self.require_current_operation(operation)?;self.guard_codex_pending_change(Some(&operation.operation_id))?;- self.guard_qoder_pending_model_change(Some(&operation.operation_id))?;+ self.guard_additional_pending_model_change(Some(&operation.operation_id))?;self.begin_plan_content_activation(operation)?;// Settings model publications are hot-swappable: the aggregate ArcSwap cutover keeps// every in-flight pin on its old root, so normal B updates never suspend admission.@@ -119,7 +119,7 @@ impl LocalControlAdapter {.record.as_ref().expect("publication_marker always returns the current shape");- self.validate_qoder_installed_model_budgets(record)?;+ self.validate_additional_installed_model_budgets(record)?;record.verify().map_err(|_| invalid("publication.install.record"))?diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rsindex e6e08c7d..f7590353 100644--- a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs@@ -39,6 +39,94 @@ fn restore_spec(fixture: &QoderFixture, status: &serde_json::Value) -> serde_jsojson!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context,"model":{"intent":"restore","restore_point_ref":status["restore_point_ref"]}})}+#[test]+fn pi_default_selected_after_prepare_blocks_final_removal_without_losing_models() {+ // Supply only the model-capability receipt, without a machine-wide Node dependency.+ // SDK imports/semantics are independently covered by the SDK contract and native E2E.+ let tools = crate::test_support::private_tempdir();+ let node = tools.path().join("node");+ private_file(&node, b"#!/bin/sh\nif [ \"$1\" = --version ]; then echo v22.19.0; elif [ \"$2\" = --check ] && [ \"$4\" = models ]; then echo hiroute.pi-sdk-capability/v1:ok; else exit 97; fi\n");+ fs::set_permissions(&node, fs::Permissions::from_mode(0o700)).unwrap();+ let path =+ std::env::join_paths([tools.path(), Path::new("/usr/bin"), Path::new("/bin")]).unwrap();+ if crate::test_support::isolated_agent_home_with_path(+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::pi_default_selected_after_prepare_blocks_final_removal_without_losing_models",+ &path,+ ) {+ return;+ }+ let fixture = QoderFixture::with_kind(true, AgentKindV1::Pi);+ let mut spec = model_spec(&fixture);+ spec["model"]["settings"]["mode"] = json!("pi_additional");+ apply(&fixture.service, &fixture.runtime, spec, "pi-race-enable");+ let models_before = fs::read(&fixture.native_config).unwrap();+ let models: serde_json::Value = serde_json::from_slice(&models_before).unwrap();+ let (provider, declaration) = models["providers"]+ .as_object()+ .unwrap()+ .iter()+ .find(|(id, _)| id.starts_with("hiroute-main-"))+ .unwrap();+ let default_file = fixture+ .native_config+ .parent()+ .unwrap()+ .join("settings.json");+ let default_before = fs::read(&default_file).unwrap();+ let status = model_status(&fixture);+ let restore = restore_spec(&fixture, &status);+ let mut ports = fixture.runtime.application_ports();+ ports.mutation = Some(Arc::new(fault::FileRace {+ adapter: fixture.runtime.adapter.clone(),+ path: default_file.clone(),+ fail_after_file: false,+ replacement: Some(+ serde_json::to_vec(&json!({"defaultProvider":provider,+ "defaultModel":declaration["models"][0]["id"],"theme":"user-edited"}))+ .unwrap(),+ ),+ }));+ let racing = LocalControlDaemon::new(ApplicationService::new(ports));+ let preview = racing+ .dispatch_wire(request(+ "PreviewAgentConnectionRestore",+ json!({"spec":restore}),+ None,+ ))+ .data+ .unwrap();+ assert_eq!(preview["applicable"], true);+ let response = racing.dispatch_wire(request(+ "ApplyAgentConnectionRestore",+ json!({"spec":restore,+ "accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],+ "expected_revisions":preview["expected_revisions"],"idempotency_key":"pi-race-restore"}),+ None,+ ));+ assert!(response.error.is_none(), "{response:?}");+ let pending = response.data.unwrap();+ assert_eq!(+ pending["state"], "rolled_back",+ "a restore rejected before its file switch must roll back safely"+ );+ assert_eq!(fs::read(&fixture.native_config).unwrap(), models_before);+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&fs::read(&default_file).unwrap()).unwrap()["theme"],+ "user-edited"+ );+ assert_eq!(model_status(&fixture)["state"], "configured");+ fs::write(&default_file, &default_before).unwrap();+ let retry = apply(+ &fixture.service,+ &fixture.runtime,+ restore,+ "pi-race-safe-restore",+ );+ assert_eq!(retry["state"], "succeeded");+ assert_eq!(model_status(&fixture)["state"], "not_configured");+ assert_eq!(fs::read(default_file).unwrap(), default_before);+}+#[test]fn qoder_additional_models_preserve_native_default_and_restore_independently_of_skill() {if crate::test_support::isolated_agent_home(@@ -85,7 +173,8 @@ fn qoder_additional_models_preserve_native_default_and_restore_independently_of_0o600);assert_eq!(fs::read(&fixture.skill).unwrap(), skill);- let provider = hiroute_application::agent_connection::qoder_model_provider_id(&fixture.context);+ let provider =+ hiroute_application::agent_connection::additional_model_provider_id(&fixture.context);assert_eq!(configured["providers"][&provider]["baseUrl"],"http://127.0.0.1:5837/_hiroute/qoder/v1"@@ -156,7 +245,8 @@ fn qoder_restore_rejects_native_default_reference_then_preserves_unrelated_edits);let status = model_status(&fixture);let restore = restore_spec(&fixture, &status);- let provider = hiroute_application::agent_connection::qoder_model_provider_id(&fixture.context);+ let provider =+ hiroute_application::agent_connection::additional_model_provider_id(&fixture.context);let alias = status["live_check_targets"][0]["client_model_ids"][0].as_str().unwrap();@@ -445,6 +535,7 @@ fn qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_eadapter: fixture.runtime.adapter.clone(),path: fixture.native_config.clone(),fail_after_file: false,+ replacement: None,}));let racing = LocalControlDaemon::new(ApplicationService::new(ports));let preview = racing.dispatch_wire(request(@@ -471,14 +562,14 @@ fn qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_efixture.runtime.adapter- .guard_qoder_pending_model_change(None)+ .guard_additional_pending_model_change(None).is_err());assert!(fixture.runtime.adapter- .guard_qoder_pending_model_change(Some(&id))+ .guard_additional_pending_model_change(Some(&id)).is_ok());let blocked = fixture.service.dispatch_wire(request(@@ -556,7 +647,7 @@ fn qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_efixture.runtime.adapter- .guard_qoder_pending_model_change(None)+ .guard_additional_pending_model_change(None).is_ok());apply(@@ -609,6 +700,7 @@ fn qoder_managed_bearer_permission_drift_revokes_live_eligibility_but_allows_reslet restored: serde_json::Value =serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();assert_eq!(restored["model"]["name"], "native/default");- let provider = hiroute_application::agent_connection::qoder_model_provider_id(&fixture.context);+ let provider =+ hiroute_application::agent_connection::additional_model_provider_id(&fixture.context);assert!(restored["providers"].get(&provider).is_none());}diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rsindex 17e7c201..6632883c 100644--- a/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs@@ -21,10 +21,15 @@ impl QoderFixture {}fn with_models(models: bool) -> Self {+ Self::with_kind(models, AgentKindV1::Qoder)+ }++ fn with_kind(models: bool, kind: AgentKindV1) -> Self {+ let pi = kind == AgentKindV1::Pi;let root = tempfile::tempdir().unwrap();fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();let home = PathBuf::from(std::env::var_os("HOME").unwrap());- let config_root = home.join("selected-qoder");+ let config_root = home.join(if pi { "selected-pi" } else { "selected-qoder" });private_file(&config_root.join("settings.json"),b"native settings are opaque to HiRoute\n",@@ -35,9 +40,32 @@ impl QoderFixture {let mut layout = AgentFilesystemLayoutV1::from_process(&home, root.path());layout.codex_executable = root.path().join("missing-codex");layout.claude_executable = root.path().join("missing-claude");- layout.qoder_executable = executable;+ if pi {+ let package = root.path().join("selected-pi-package");+ private_file(&package.join("package.json"), br#"{"name":"@earendil-works/pi-coding-agent","version":"1.0.2","bin":{"pi":"dist/bundle/cli.js"}}"#);+ private_file(&package.join("dist/index.js"), b"test SDK location only");+ private_file(&package.join("dist/bundle/cli.js"), b"#!/bin/sh\nexit 97\n");+ fs::set_permissions(+ package.join("dist/bundle/cli.js"),+ fs::Permissions::from_mode(0o700),+ )+ .unwrap();+ layout.pi_executable = package.join("dist/bundle/cli.js");+ layout.pi_config_root = config_root.clone();+ private_file(+ &config_root.join("settings.json"),+ br#"{"defaultProvider":"native","defaultModel":"default","theme":"dark"}"#,+ );+ } else {+ layout.pi_executable = root.path().join("missing-pi");+ layout.qoder_executable = executable;+ }layout.qoder_home = home.clone();- layout.qoder_config_root = config_root.clone();+ if !pi {+ layout.qoder_config_root = config_root.clone();+ } else {+ layout.qoder_executable = root.path().join("missing-qoder");+ }let registry = serde_json::from_slice(include_bytes!("../../../../../assets/connector-registry/current/registry-seed.json"))@@ -51,8 +79,16 @@ impl QoderFixture {ClaudeRegistrationIndexV1::from_verified_model_data(®istry, &model_data.data).unwrap(),);- let native_config = scanner.qoder_user_config_target();- let skill = scanner.qoder_user_skill_target();+ let native_config = if pi {+ scanner.pi_user_models_target()+ } else {+ scanner.qoder_user_config_target()+ };+ let skill = if pi {+ scanner.pi_user_skill_target()+ } else {+ scanner.qoder_user_skill_target()+ };// Native executables/workspace are not storage contents. Production deliberately// refuses to initialize a store over an unrelated pre-existing file tree.let storage = root.path().join("storage");@@ -69,12 +105,23 @@ impl QoderFixture {runtime};if models {- private_file(&native_config, br#"{"model":{"name":"native/default"},"providers":{"native":{"user":"preserved"}},"unknown":{"keep":true}}"#);+ private_file(+ &native_config,+ if pi {+ br#"{"providers":{"native":{"user":"preserved"}},"unknown":{"keep":true}}"#+ } else {+ br#"{"model":{"name":"native/default"},"providers":{"native":{"user":"preserved"}},"unknown":{"keep":true}}"#+ },+ );}runtime.adapter.reconcile_startup_and_open().unwrap();let context = runtime.adapter- .settings_context_for_agent("agent_qoder_default")+ .settings_context_for_agent(if pi {+ "agent_pi_default"+ } else {+ "agent_qoder_default"+ }).unwrap();let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports().with_agent_connection(Arc::new(diff --git a/crates/daemon/src/control/runtime/settings_facts.rs b/crates/daemon/src/control/runtime/settings_facts.rsindex c5af3490..aa4681f8 100644--- a/crates/daemon/src/control/runtime/settings_facts.rs+++ b/crates/daemon/src/control/runtime/settings_facts.rs@@ -2,12 +2,13 @@use super::*;use hiroute_application::agent_connection::{AgentSettingsFacts, AgentSettingsPlanningInput, CodexModelFileAction,- CollaborationSkillTemplate, SettingsClaudeModelFacts, SettingsModelCatalogFacts,- SettingsModelFacts, SettingsModelFileFacts, SettingsModelTargetFacts, SettingsSkillFileFacts,- SkillFileAction, codex_model_restore_point_ref, decode_settings_login_item,- is_settings_login_item, plan_skill_install, plan_skill_remove,- settings_claude_model_file_for_operation, settings_codex_catalog_target,- settings_codex_model_file_for_operation,+ CollaborationSkillTemplate, SettingsAdditionalModelFacts, SettingsClaudeModelFacts,+ SettingsClaudeNativeFacts, SettingsCodexModelFacts, SettingsModelCatalogFacts,+ SettingsModelCommonFacts, SettingsModelFacts, SettingsModelFileFacts, SettingsModelNativeFacts,+ SettingsModelTargetFacts, SettingsSkillFileFacts, SkillFileAction,+ codex_model_restore_point_ref, decode_settings_login_item, is_settings_login_item,+ plan_skill_install, plan_skill_remove, settings_claude_model_file_for_operation,+ settings_codex_catalog_target, settings_codex_model_file_for_operation,};use hiroute_application::control::RoutingFactsPort;use hiroute_application_api::{@@ -28,12 +29,12 @@ use hiroute_integrations::{};use std::collections::{BTreeMap, BTreeSet};+mod additional_model;#[path = "settings_codex_association.rs"]mod codex_association;#[path = "settings_facts/codex_models.rs"]mod codex_models;mod qoder;-mod qoder_model;use codex_association::{connector_account_matches, endpoint_matches_target, mark_catalog_structure_proven,};@@ -55,6 +56,7 @@ pub(super) enum SettingsAgentClass {CodexProfile,Claude,Qoder,+ Pi,}impl SettingsAgentClass {@@ -67,6 +69,7 @@ impl SettingsAgentClass {Self::Codex | Self::CodexProfile => "agent_codex_default",Self::Claude => "agent_claude_default",Self::Qoder => "agent_qoder_default",+ Self::Pi => "agent_pi_default",}}@@ -75,6 +78,7 @@ impl SettingsAgentClass {Self::Codex | Self::CodexProfile => "codex",Self::Claude => "claude",Self::Qoder => "qoder",+ Self::Pi => "pi",}}@@ -84,6 +88,7 @@ impl SettingsAgentClass {Self::CodexProfile => scanner.codex_profile_config_target(),Self::Claude => scanner.claude_user_settings_target(),Self::Qoder => scanner.qoder_user_config_target(),+ Self::Pi => scanner.pi_user_models_target(),}}@@ -92,6 +97,7 @@ impl SettingsAgentClass {Self::Codex | Self::CodexProfile => "skill-root/agent_codex_default",Self::Claude => "skill-root/agent_claude_default",Self::Qoder => "skill-root/agent_qoder_default",+ Self::Pi => "skill-root/agent_pi_default",}}@@ -105,6 +111,10 @@ impl SettingsAgentClass {hiroute_integrations::CLAUDE_PROFILE_ID_V1,hiroute_integrations::CLAUDE_INTEGRATION_PROFILE_REF_V1,),+ Self::Pi => (+ hiroute_integrations::PI_PROFILE_ID_V1,+ hiroute_integrations::PI_INTEGRATION_PROFILE_REF_V1,+ ),Self::Qoder => (hiroute_integrations::QODER_PROFILE_ID_V1,hiroute_integrations::QODER_INTEGRATION_PROFILE_REF_V1,@@ -125,6 +135,7 @@ impl LocalControlAdapter {"agent_codex_default" => SettingsAgentClass::Codex,"agent_claude_default" => SettingsAgentClass::Claude,"agent_qoder_default" => SettingsAgentClass::Qoder,+ "agent_pi_default" => SettingsAgentClass::Pi,_ => return None,};Some(self.settings_context(class))@@ -136,6 +147,7 @@ impl LocalControlAdapter {SettingsAgentClass::CodexProfile,SettingsAgentClass::Claude,SettingsAgentClass::Qoder,+ SettingsAgentClass::Pi,].into_iter().find(|class| context == self.settings_context(*class))@@ -172,8 +184,12 @@ impl LocalControlAdapter {spec: &AgentSettingsSpecV2,class: SettingsAgentClass,) -> Result<AgentSettingsPlanningInput, ControlReadError> {- if class == SettingsAgentClass::Qoder {- return self.attach_qoder_model_facts(spec, self.qoder_settings_snapshot(spec)?);+ if matches!(class, SettingsAgentClass::Qoder | SettingsAgentClass::Pi) {+ return self.attach_additional_model_facts(+ spec,+ class,+ self.additional_settings_snapshot(spec, class)?,+ );}let owned_claude = if class == SettingsAgentClass::Claude {if let Some(join) = self.configured_model_settings_join(&spec.context_id)? {@@ -378,7 +394,9 @@ impl LocalControlAdapter {SettingsAgentClass::Claude}SettingsAgentClass::Claude => SettingsAgentClass::Codex,- SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi => {+ return Err(ControlReadError::Denied);+ }};let other_grant = stores.secrets()@@ -444,7 +462,7 @@ impl LocalControlAdapter {selected_collaboration_restore = Some(original.operation_id.clone());}let model = match class {- SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi => return Err(ControlReadError::Denied),SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => original.plan.external()@@ -580,7 +598,9 @@ impl LocalControlAdapter {None};let native_default_model = match class {- SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi => {+ return Err(ControlReadError::Denied);+ }SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => codex_catalog_summary.as_ref().map(|catalog| catalog.native_default_model.clone()),@@ -868,7 +888,9 @@ impl LocalControlAdapter {)).map_err(|_| ControlReadError::Corrupt)?;let model_target = match class {- SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi => {+ return Err(ControlReadError::Denied);+ }SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => {SettingsModelTargetFacts::Codex {provider_id: "hiroute".into(),@@ -917,33 +939,42 @@ impl LocalControlAdapter {collaboration_file_conflict,restore_points,model: Some(SettingsModelFacts {- qoder_model_conflict: None,- codex_context_override,- claude_context_override,- claude_plan_capability_unavailable,- ingress: installation- .profile- .model_connection()- .map_err(|_| ControlReadError::Corrupt)?- .ok_or(ControlReadError::Denied)?- .ingress_protocol,- available_surfaces: self.scanner.available_model_surfaces(class.agent_id()),- model_publication: active,- model_catalog,- login_item_required,- login_item_removal_required,- fixed_candidate_facts,- preserved_codex_models,- preserved_codex_bindings,- required_native_model_ids,- require_native_model_routes: preserve_native_models,- unproven_native_model_ids,- native_default_must_be_original,- native_default_model,- native_claude_presets,- restore_native_model_ids,- restore_inherits_root: class == SettingsAgentClass::CodexProfile,- restored_native_model,+ common: SettingsModelCommonFacts {+ ingress: installation+ .profile+ .model_connection()+ .map_err(|_| ControlReadError::Corrupt)?+ .ok_or(ControlReadError::Denied)?+ .ingress_protocol,+ available_surfaces: self.scanner.available_model_surfaces(class.agent_id()),+ model_publication: active,+ login_item_required,+ login_item_removal_required,+ fixed_candidate_facts,+ },+ native: if class.is_codex() {+ SettingsModelNativeFacts::Codex(Box::new(SettingsCodexModelFacts {+ context_override: codex_context_override,+ model_catalog,+ preserved_codex_models,+ preserved_codex_bindings,+ required_native_model_ids,+ unproven_native_model_ids,+ require_native_model_routes: preserve_native_models,+ native_default_must_be_original,+ native_default_model,+ restore_native_model_ids,+ restore_inherits_root: class == SettingsAgentClass::CodexProfile,+ restored_native_model,+ }))+ } else {+ SettingsModelNativeFacts::Claude(SettingsClaudeNativeFacts {+ context_override: claude_context_override,+ plan_capability_unavailable: claude_plan_capability_unavailable,+ native_default_model,+ presets: native_claude_presets,+ })+ },}),},})diff --git a/crates/daemon/src/control/runtime/settings_facts/qoder_model.rs b/crates/daemon/src/control/runtime/settings_facts/additional_model.rssimilarity index 73%rename from crates/daemon/src/control/runtime/settings_facts/qoder_model.rsrename to crates/daemon/src/control/runtime/settings_facts/additional_model.rsindex f7972e37..d4750ce2 100644--- a/crates/daemon/src/control/runtime/settings_facts/qoder_model.rs+++ b/crates/daemon/src/control/runtime/settings_facts/additional_model.rs@@ -1,7 +1,8 @@//! Optional Qoder model facts. Pure collaboration never enters this file reader.use super::*;use hiroute_application::agent_connection::{- QoderModelFileAction, qoder_model_provider_id, settings_qoder_model_file_for_operation,+ AdditionalModelFileAction, additional_model_provider_id,+ settings_additional_model_file_for_operation,};use hiroute_domain::{AgentCapability, AgentIngressProtocolV1, AgentModelSelectionV2, AgentModelSurfaceV2,@@ -9,9 +10,10 @@ use hiroute_domain::{};impl LocalControlAdapter {- pub(super) fn attach_qoder_model_facts(+ pub(super) fn attach_additional_model_facts(&self,spec: &AgentSettingsSpecV2,+ class: SettingsAgentClass,mut input: AgentSettingsPlanningInput,) -> Result<AgentSettingsPlanningInput, ControlReadError> {// A model-capable installation does not make unrelated native settings a dependency@@ -23,11 +25,38 @@ impl LocalControlAdapter {return Ok(input);}if let AgentFacetIntent::Configure { settings } = &spec.model- && !matches!(settings, AgentModelSelectionV2::QoderAdditional { .. })+ && !matches!(+ settings,+ AgentModelSelectionV2::QoderAdditional { .. }+ | AgentModelSelectionV2::PiAdditional { .. }+ ){return Ok(input);}- self.guard_qoder_pending_model_change(None)+ let kind = if class == SettingsAgentClass::Pi {+ hiroute_domain::AgentKindV1::Pi+ } else {+ hiroute_domain::AgentKindV1::Qoder+ };+ // Restore remains available even after the installed SDK becomes incompatible.+ #[cfg(unix)]+ if kind == hiroute_domain::AgentKindV1::Pi+ && matches!(spec.model, AgentFacetIntent::Configure { .. })+ {+ self.scanner+ .check_pi_model_configuration()+ .map_err(|_| ControlReadError::Unavailable)?;+ }+ let pi_settings = if kind == hiroute_domain::AgentKindV1::Pi {+ Some(+ self.scanner+ .pi_default_model()+ .map_err(|_| ControlReadError::Denied)?,+ )+ } else {+ None+ };+ self.guard_additional_pending_model_change(None).map_err(super::super::map_port)?;let target = AgentConnectionEffectRoleV1::ManagedConfiguration.settings_target_for(&input.subject)@@ -104,15 +133,15 @@ impl LocalControlAdapter {.external().iter().find(|intent| {- super::super::native_qoder_model::is_settings_qoder_model(intent)+ super::super::native_additional_model::is_settings_additional_model(intent)}).cloned()else {continue;};- let payload = settings_qoder_model_file_for_operation(&operation, &intent)+ let payload = settings_additional_model_file_for_operation(&operation, &intent).map_err(super::super::map_port)?;- if !matches!(payload.change, QoderModelFileAction::Configure { .. }) {+ if !matches!(payload.change, AdditionalModelFileAction::Configure { .. }) {return Err(ControlReadError::Corrupt);}let [mutation] = operation.plan.agent_access_grants() else {@@ -143,7 +172,7 @@ impl LocalControlAdapter {).map_err(super::super::map_port)?;drop(stores);- let provider_id = qoder_model_provider_id(&spec.context_id);+ let provider_id = additional_model_provider_id(&spec.context_id);let endpoint = self.managed_agent_runtime.lock()@@ -151,8 +180,9 @@ impl LocalControlAdapter {.as_ref().map(|runtime| runtime.gateway_base_url.clone()).ok_or(ControlReadError::Unavailable)?;- let endpoint = super::super::native_qoder_model::qoder_model_endpoint(&endpoint)- .map_err(super::super::map_port)?;+ let endpoint =+ super::super::native_additional_model::additional_model_endpoint(kind, &endpoint)+ .map_err(super::super::map_port)?;let mut restore = None;if let (Some((operation, _)), Some(reference)) = (&previous, ¤t_grant) {input.facts.restore_points.insert(@@ -171,12 +201,14 @@ impl LocalControlAdapter {&BTreeMap::new(),).map_err(|_| ControlReadError::Denied)?;- let models =- super::super::native_qoder_model::qoder_models_for_grant(&active, &grant)- .map_err(super::super::map_port)?;- qoder_model_conflict =- qoder_model_validation(hiroute_integrations::validate_qoder_configuration(+ let models = super::super::native_additional_model::additional_models_for_grant(+ kind, &active, &grant,+ )+ .map_err(super::super::map_port)?;+ qoder_model_conflict = qoder_model_validation(+ hiroute_integrations::validate_additional_configuration(&self.artifacts,+ kind,&target,&provider_id,&endpoint,@@ -184,7 +216,8 @@ impl LocalControlAdapter {previous.as_ref().map(|(op, intent)| (&op.operation_id, intent)),- ))?;+ ),+ )?;models}AgentFacetIntent::Restore { restore_point_ref } => {@@ -195,8 +228,9 @@ impl LocalControlAdapter {}).ok_or(ControlReadError::Denied)?;qoder_model_conflict =- qoder_model_validation(hiroute_integrations::validate_qoder_restoration(+ qoder_model_validation(hiroute_integrations::validate_additional_restoration(&self.artifacts,+ kind,&target,&original.operation_id,intent,@@ -205,11 +239,19 @@ impl LocalControlAdapter {}AgentFacetIntent::Keep => unreachable!(),};+ let qoder_model_conflict = if pi_settings+ .as_ref()+ .is_some_and(|settings| settings.removes_default(&provider_id, &models))+ {+ Some(hiroute_application::agent_connection::SettingsBlockReason::AdditionalDefaultInUse)+ } else {+ qoder_model_conflict+ };let dependency_digest = CanonicalDigest::of(&serde_json::json!({"schema":"qoder-model-facts/v1", "collaboration":input.facts.dependency_digest,"content":expected_content,"fingerprint":before_fingerprint,"publication":publication.digest,"grant":current_grant,"token":token_input_fingerprint,"provider":provider_id,"endpoint":endpoint,- "conflict":qoder_model_conflict,"models":models,"previous":previous.as_ref().map(|(op,_)| &op.operation_id),"restore":restore,+ "conflict":qoder_model_conflict,"models":models,"kind":kind,"pi_settings":pi_settings,"previous":previous.as_ref().map(|(op,_)| &op.operation_id),"restore":restore,})).map_err(|_| ControlReadError::Corrupt)?;let old_digest = input.facts.dependency_digest.clone();let mut capabilities = [@@ -238,7 +280,12 @@ impl LocalControlAdapter {capabilities.push(CapabilityEvidence {capability,state: CapabilityState::Proven,- adapter_contract: "hiroute.qoder-additional-model/v1".into(),+ adapter_contract: if kind == hiroute_domain::AgentKindV1::Pi {+ "hiroute.pi-additional-model/v1"+ } else {+ "hiroute.qoder-additional-model/v1"+ }+ .into(),observed_at_unix_ms: self.now_ms()?.max(1) as u64,dependency_digest: dependency_digest.clone(),reason: None,@@ -248,28 +295,22 @@ impl LocalControlAdapter {AgentCapabilitySet::new(capabilities).map_err(|_| ControlReadError::Corrupt)?;input.facts.dependency_digest = dependency_digest;input.facts.model = Some(SettingsModelFacts {- qoder_model_conflict,- codex_context_override: false,- claude_context_override: false,- claude_plan_capability_unavailable: false,- ingress: AgentIngressProtocolV1::Responses,- available_surfaces: [AgentModelSurfaceV2::QoderCli].into(),- model_publication: Some(active),- model_catalog: None,- login_item_required: false,- login_item_removal_required: false,- fixed_candidate_facts: Vec::new(),- preserved_codex_models: Vec::new(),- preserved_codex_bindings: BTreeMap::new(),- required_native_model_ids: None,- unproven_native_model_ids: Vec::new(),- require_native_model_routes: false,- native_default_must_be_original: false,- native_default_model: None,- restore_native_model_ids: None,- restore_inherits_root: false,- restored_native_model: None,- native_claude_presets: None,+ common: SettingsModelCommonFacts {+ ingress: AgentIngressProtocolV1::Responses,+ available_surfaces: [if kind == hiroute_domain::AgentKindV1::Pi {+ AgentModelSurfaceV2::PiCli+ } else {+ AgentModelSurfaceV2::QoderCli+ }]+ .into(),+ model_publication: Some(active),+ login_item_required: false,+ login_item_removal_required: false,+ fixed_candidate_facts: Vec::new(),+ },+ native: SettingsModelNativeFacts::Additional(SettingsAdditionalModelFacts {+ model_conflict: qoder_model_conflict,+ }),});input.model_file = Some(SettingsModelFileFacts {expected_content,@@ -279,7 +320,9 @@ impl LocalControlAdapter {token_input_fingerprint,active_configuration: previous.as_ref().map(|(op, _)| op.operation_id.clone()),restore,- target: SettingsModelTargetFacts::Qoder {+ target: SettingsModelTargetFacts::Additional {+ kind,+ pi_settings_content: pi_settings.map(|settings| settings.content_digest),provider_id,endpoint,models,diff --git a/crates/daemon/src/control/runtime/settings_facts/qoder.rs b/crates/daemon/src/control/runtime/settings_facts/qoder.rsindex 3fcec855..d226f8e9 100644--- a/crates/daemon/src/control/runtime/settings_facts/qoder.rs+++ b/crates/daemon/src/control/runtime/settings_facts/qoder.rs@@ -3,15 +3,19 @@ use super::*;use hiroute_integrations::QoderCollaborationProbeTarget;impl LocalControlAdapter {- pub(super) fn qoder_settings_snapshot(+ pub(super) fn additional_settings_snapshot(&self,spec: &AgentSettingsSpecV2,+ class: SettingsAgentClass,) -> Result<AgentSettingsPlanningInput, ControlReadError> {- let class = SettingsAgentClass::Qoder;- let discovery = self.scanner.qoder_settings_discovery(matches!(- spec.collaboration,- AgentFacetIntent::Configure { .. }- ));+ let discovery = if class == SettingsAgentClass::Pi {+ self.scanner.pi_settings_discovery()+ } else {+ self.scanner.qoder_settings_discovery(matches!(+ spec.collaboration,+ AgentFacetIntent::Configure { .. }+ ))+ };let AgentDiscoveryOutcomeV1::Supported { installation } = discovery.outcome else {return Err(ControlReadError::NotFound);};diff --git a/crates/daemon/src/control/runtime/settings_profile_fault.rs b/crates/daemon/src/control/runtime/settings_profile_fault.rsindex 4a4e5b64..87978f95 100644--- a/crates/daemon/src/control/runtime/settings_profile_fault.rs+++ b/crates/daemon/src/control/runtime/settings_profile_fault.rs@@ -13,6 +13,7 @@ pub(super) struct FileRace {pub adapter: Arc<LocalControlAdapter>,pub path: std::path::PathBuf,pub fail_after_file: bool,+ pub replacement: Option<Vec<u8>>,}impl ApplicationMutationPort for FileRace {fn preview_change(@@ -116,11 +117,12 @@ impl ExternalEffectPort for FileRace {&& op.plan.external().iter().any(|i| {i.target() == e.target&& (crate::control::runtime::native_model::is_settings_codex_model(i)- || crate::control::runtime::native_qoder_model::is_settings_qoder_model(i))+ || crate::control::runtime::native_additional_model::is_settings_additional_model(i))}){let original = fs::read_to_string(&self.path).unwrap();- fs::write(&self.path, format!("# user's concurrent edit\n{original}")).unwrap();+ fs::write(&self.path, self.replacement.clone().unwrap_or_else(||+ format!("# user's concurrent edit\n{original}").into_bytes())).unwrap();return self.adapter.activate_external(op, e);}self.adapter.activate_external(op, e)diff --git a/crates/daemon/src/control/runtime/settings_profile_tests.rs b/crates/daemon/src/control/runtime/settings_profile_tests.rsindex e2bdd4c1..e28bd594 100644--- a/crates/daemon/src/control/runtime/settings_profile_tests.rs+++ b/crates/daemon/src/control/runtime/settings_profile_tests.rs@@ -114,6 +114,7 @@ fn profile_lifecycle_inheritance_slot_and_safe_restore() {adapter: runtime.adapter.clone(),path: profile.clone(),fail_after_file: false,+ replacement: None,}));let editing = LocalControlDaemon::new(ApplicationService::new(edit_ports));let edit_preview = editing@@ -151,6 +152,7 @@ fn profile_lifecycle_inheritance_slot_and_safe_restore() {adapter: runtime.adapter.clone(),path: profile.clone(),fail_after_file: false,+ replacement: None,}));let racing = LocalControlDaemon::new(ApplicationService::new(ports));let preview = racing@@ -438,6 +440,7 @@ fn preexisting_profile_conflict_preserves_connection_and_other_writes() {adapter: runtime.adapter.clone(),path: profile.clone(),fail_after_file: true,+ replacement: None,}));let fault_service = LocalControlDaemon::new(ApplicationService::new(fault_ports));let preview = fault_service@@ -554,6 +557,7 @@ fn profile_delete_race_rolls_back_and_releases_writer() {adapter: runtime.adapter.clone(),path: profile.clone(),fail_after_file: false,+ replacement: None,}));let racing = LocalControlDaemon::new(ApplicationService::new(ports));let preview = racingdiff --git a/crates/daemon/src/control/runtime/settings_retry.rs b/crates/daemon/src/control/runtime/settings_retry.rsindex d21da490..cb4f2157 100644--- a/crates/daemon/src/control/runtime/settings_retry.rs+++ b/crates/daemon/src/control/runtime/settings_retry.rs@@ -11,7 +11,10 @@ impl LocalControlAdapter {if request.schema != "hiroute.agent-settings-retry/v1"|| self.settings_agent_for_context(&request.context_id)- .is_none_or(|class| !class.is_codex() && class != SettingsAgentClass::Qoder)+ .is_none_or(|class| {+ !class.is_codex()+ && !matches!(class, SettingsAgentClass::Qoder | SettingsAgentClass::Pi)+ }){return Err(ControlReadError::Denied);}@@ -33,14 +36,17 @@ impl LocalControlAdapter {if matches!(spec.model, AgentFacetIntent::Keep) {return Err(ControlReadError::Denied);}- if self.settings_agent_for_context(&request.context_id) == Some(SettingsAgentClass::Qoder) {+ if matches!(+ self.settings_agent_for_context(&request.context_id),+ Some(SettingsAgentClass::Qoder | SettingsAgentClass::Pi)+ ) {let intent = op.plan.external().iter()- .find(|intent| super::native_qoder_model::is_settings_qoder_model(intent))+ .find(|intent| super::native_additional_model::is_settings_additional_model(intent)).ok_or(ControlReadError::Denied)?;- hiroute_application::agent_connection::settings_qoder_model_file_for_operation(+ hiroute_application::agent_connection::settings_additional_model_file_for_operation(&op, intent,).map_err(super::map_port)?;diff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rsindex c99004f2..39ad94ae 100644--- a/crates/daemon/src/control/runtime/settings_status.rs+++ b/crates/daemon/src/control/runtime/settings_status.rs@@ -201,8 +201,11 @@ impl LocalControlAdapter {status.operation_state = Some(operation.state.as_str().into());let (active_grant, configured_join) = match action {ModelAction::Configure => {- let file_applied = if class == SettingsAgentClass::Qoder {- hiroute_integrations::qoder_native_configuration_is_applied(+ let file_applied = if matches!(+ class,+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi+ ) {+ hiroute_integrations::additional_native_configuration_is_applied(&self.artifacts,&operation.operation_id,intent,@@ -319,6 +322,10 @@ impl LocalControlAdapter {hiroute_domain::AgentModelSelectionV2::QoderAdditional { .. },SettingsAgentClass::Qoder,) => [hiroute_domain::AgentModelSurfaceV2::QoderCli].into(),+ (+ hiroute_domain::AgentModelSelectionV2::PiAdditional { .. },+ SettingsAgentClass::Pi,+ ) => [hiroute_domain::AgentModelSurfaceV2::PiCli].into(),_ => return Err(ControlReadError::Corrupt),};// The applied revision is the installed publication this configuration was@@ -452,8 +459,9 @@ fn model_intent(super::settings_facts::SettingsAgentClass::Claude => {super::native_claude_model::is_settings_claude_model(intent)}- super::settings_facts::SettingsAgentClass::Qoder => {- super::native_qoder_model::is_settings_qoder_model(intent)+ super::settings_facts::SettingsAgentClass::Qoder+ | super::settings_facts::SettingsAgentClass::Pi => {+ super::native_additional_model::is_settings_additional_model(intent)}})}@@ -464,16 +472,16 @@ fn model_action(intent: &hiroute_domain::ExternalEffectIntentV1,) -> hiroute_domain::PortResult<ModelAction> {match class {- super::settings_facts::SettingsAgentClass::Qoder => {- match hiroute_application::agent_connection::settings_qoder_model_file_for_operation(+ super::settings_facts::SettingsAgentClass::Qoder | super::settings_facts::SettingsAgentClass::Pi => {+ match hiroute_application::agent_connection::settings_additional_model_file_for_operation(operation, intent,)?.change{- hiroute_application::agent_connection::QoderModelFileAction::Configure {+ hiroute_application::agent_connection::AdditionalModelFileAction::Configure {..} => Ok(ModelAction::Configure),- hiroute_application::agent_connection::QoderModelFileAction::Restore { .. } => {+ hiroute_application::agent_connection::AdditionalModelFileAction::Restore { .. } => {Ok(ModelAction::Restore)}}diff --git a/crates/daemon/src/delegation/acp/README.md b/crates/daemon/src/delegation/acp/README.mdindex ceea37f6..c94a68f5 100644--- a/crates/daemon/src/delegation/acp/README.md+++ b/crates/daemon/src/delegation/acp/README.md@@ -32,3 +32,11 @@ correct selection, a corrected selection, and each failure before prompt intent.They prove protocol behavior, not that a real installed Agent loaded user skillsor sent the selected model to Gateway. The real Worker product journey must provethose effects through its actual adapter and native client.++Pi's bundled bridge has a closed `hiroute.pi-worker-failure/v1` error payload.+[Failure ingestion](pi_failure.rs) recognizes only the exact schema, error code+and allowed stage values, and preserves existing public error categories. Unknown+or extended payloads remain protocol failures; raw adapter messages are not copied.+[Protocol tests](tests.rs) verify startup/load errors precede prompt intent and+model errors fail the accepted run without replay. The bridge's process tests live+beside its producer under `profile/pi_worker_bridge.test.mjs`.diff --git a/crates/daemon/src/delegation/acp/mod.rs b/crates/daemon/src/delegation/acp/mod.rsindex 2e15529a..8218d766 100644--- a/crates/daemon/src/delegation/acp/mod.rs+++ b/crates/daemon/src/delegation/acp/mod.rs@@ -21,6 +21,7 @@ use super::progress::ProgressSink;mod identity;mod model;+mod pi_failure;mod transport;pub use identity::AcpNativeIdentityContract;pub use transport::MAX_ACP_FRAME_BYTES;@@ -363,7 +364,7 @@ async fn run_session(biased;_ = input.cancellation.cancelled() => None,_ = tokio::time::sleep_until(input.deadline) => None,- response = &mut prompt => Some(response.map_err(|_| DelegationErrorV1::ProtocolFailed)?),+ response = &mut prompt => Some(response.map_err(pi_failure::map_error)?),};let stop_reason = if let Some(response) = response {let prompt_failed = prompt_session_failure(response.meta.as_ref())?;@@ -500,7 +501,7 @@ async fn phase<T>(biased;_ = cancellation.cancelled() => Err(DelegationErrorV1::Cancelled),_ = tokio::time::sleep_until(deadline) => Err(DelegationErrorV1::DeadlineExceeded),- result = future => result.map_err(|_| DelegationErrorV1::ProtocolFailed),+ result = future => result.map_err(pi_failure::map_error),}}diff --git a/crates/daemon/src/delegation/acp/pi_failure.rs b/crates/daemon/src/delegation/acp/pi_failure.rsnew file mode 100644index 00000000..85c8c890--- /dev/null+++ b/crates/daemon/src/delegation/acp/pi_failure.rs@@ -0,0 +1,50 @@+//! Only the Pi bridge's closed failure vocabulary is allowed through this boundary.+//! Native messages/data are never copied into task results or diagnostics.+use hiroute_domain::delegation::DelegationErrorV1;++pub(super) fn map_error(error: agent_client_protocol::Error) -> DelegationErrorV1 {+ let fallback = DelegationErrorV1::ProtocolFailed;+ if error.code != (-32000).into() {+ return fallback;+ }+ let Some(data) = error.data.as_ref().and_then(serde_json::Value::as_object) else {+ return fallback;+ };+ if data.len() != 2+ || data.get("schema").and_then(serde_json::Value::as_str)+ != Some("hiroute.pi-worker-failure/v1")+ {+ return fallback;+ }+ match data.get("stage").and_then(serde_json::Value::as_str) {+ Some("sdk_load") => DelegationErrorV1::DependenciesInvalid,+ Some(+ "configuration" | "sdk_capability" | "route_binding" | "resources" | "session_create",+ ) => DelegationErrorV1::CapabilityUnavailable,+ Some("history" | "session_load") => DelegationErrorV1::ResumeUnavailable,+ Some("prompt") => DelegationErrorV1::PromptFailed,+ Some("request") => DelegationErrorV1::InvalidArguments,+ Some("busy") => DelegationErrorV1::Conflict,+ _ => fallback,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn unrelated_or_open_ended_adapter_errors_are_not_trusted() {+ for data in [+ json!({"schema":"foreign", "stage":"prompt"}),+ json!({"schema":"hiroute.pi-worker-failure/v1", "stage":"future"}),+ json!({"schema":"hiroute.pi-worker-failure/v1", "stage":"prompt", "secret":"never copy"}),+ ] {+ assert_eq!(+ map_error(agent_client_protocol::Error::new(-32000, "secret").data(data)),+ DelegationErrorV1::ProtocolFailed+ );+ }+ }+}diff --git a/crates/daemon/src/delegation/acp/tests.rs b/crates/daemon/src/delegation/acp/tests.rsindex 2f2dcdcc..ba46e436 100644--- a/crates/daemon/src/delegation/acp/tests.rs+++ b/crates/daemon/src/delegation/acp/tests.rs@@ -470,3 +470,83 @@ async fn finite_acp_does_not_replay_after_prompt_disconnect() {);assert_eq!(*journal.0.lock().unwrap(), ["session", "send_intent"]);}++#[tokio::test]+async fn pi_bridge_failure_preserves_the_failed_operation_without_replay() {+ for (stage, failing_method, expected) in [+ (+ "sdk_load",+ "initialize",+ DelegationErrorV1::DependenciesInvalid,+ ),+ (+ "resources",+ "initialize",+ DelegationErrorV1::CapabilityUnavailable,+ ),+ (+ "history",+ "session/load",+ DelegationErrorV1::ResumeUnavailable,+ ),+ ("prompt", "session/prompt", DelegationErrorV1::PromptFailed),+ ] {+ 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 response = if method == failing_method {+ json!({"jsonrpc":"2.0", "id":request["id"], "error":{+ "code":-32000, "message":"opaque native error must not reach results",+ "data":{"schema":"hiroute.pi-worker-failure/v1","stage":stage}+ }})+ } else {+ let result = match method {+ "initialize" => {+ json!({"protocolVersion":1,"agentCapabilities":{"loadSession":true}})+ }+ "session/new" => {+ json!({"sessionId":"acp-a","_meta":{"agentSessionId":"native-a"}})+ }+ other => panic!("unexpected request after failure: {other}"),+ };+ json!({"jsonrpc":"2.0", "id":request["id"], "result":result})+ };+ writer+ .write_all(format!("{response}\n").as_bytes())+ .await+ .unwrap();+ }+ methods+ });+ let (reader, writer) = tokio::io::split(client);+ let mut request = input();+ if failing_method == "session/load" {+ request.session = AcpSessionStart::Load(AcpSessionBinding {+ acp_session_id: "acp-a".into(),+ native_session_id: Some("native-a".into()),+ });+ }+ let journal = Arc::new(Journal::default());+ let result = run_acp(reader, writer, request, journal.clone()).await;+ assert_eq!(result.err(), Some(expected));+ let methods = server.await.unwrap();+ assert_eq!(methods.last().map(String::as_str), Some(failing_method));+ assert_eq!(+ methods+ .iter()+ .filter(|method| *method == failing_method)+ .count(),+ 1+ );+ assert_eq!(+ journal.0.lock().unwrap().contains(&"send_intent"),+ failing_method == "session/prompt"+ );+ }+}diff --git a/crates/daemon/src/delegation/installation.rs b/crates/daemon/src/delegation/installation.rsindex 932051be..3fa78474 100644--- a/crates/daemon/src/delegation/installation.rs+++ b/crates/daemon/src/delegation/installation.rs@@ -26,13 +26,15 @@ mod installation_probe;mod probe_server;pub(crate) use availability::WorkerExecutorAvailabilityRegistry;pub(crate) use discovery::{- discover as discover_worker_dependencies, validate_persisted_installation, validate_selection,+ discover as discover_worker_dependencies, validate_persisted_installation_for_run,+ validate_selection,};-const WORKER_HARNESSES: [WorkerHarnessV1; 3] = [+const WORKER_HARNESSES: [WorkerHarnessV1; 4] = [WorkerHarnessV1::CodexCli,WorkerHarnessV1::ClaudeCode,WorkerHarnessV1::QoderCli,+ WorkerHarnessV1::Pi,];#[derive(Clone, Debug)]@@ -149,6 +151,19 @@ pub(super) fn check_installation(.validated_launch().map_err(|_| DelegationErrorV1::DependenciesInvalid)?{+ WorkerLaunchFormV1::NativeSdk { cli, node } => {+ check_entry(Path::new(cli), true)?;+ check_entry(Path::new(node), true)?;+ hiroute_integrations::agents::pi_cli_installation(Path::new(cli))+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;+ #[cfg(unix)]+ hiroute_integrations::check_pi_sdk_capability(+ Path::new(cli),+ Path::new(node),+ hiroute_integrations::PiSdkCapability::Worker,+ )+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;+ }WorkerLaunchFormV1::NativeAcp { cli } => check_entry(Path::new(cli), true)?,WorkerLaunchFormV1::AdapterAcp { cli, adapter, node } => {check_entry(Path::new(adapter), node.is_none())?;@@ -283,10 +298,15 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {.selections.selection(input.task.plan.harness)?.ok_or(DelegationErrorV1::DependenciesMissing)?;- let installation = discovery::validate_persisted_installation(&selection.config)?;- if installation.harness == WorkerHarnessV1::QoderCli- && input.run.configuration.permission_policy- != hiroute_domain::delegation::WorkerPermissionPolicyV1::ApproveAll+ let installation = discovery::validate_persisted_installation_for_run(+ &selection.config,+ input.run.continued_from.is_some(),+ )?;+ if matches!(+ installation.harness,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ ) && input.run.configuration.permission_policy+ != hiroute_domain::delegation::WorkerPermissionPolicyV1::ApproveAll{return Err(DelegationErrorV1::CapabilityUnavailable);}@@ -431,7 +451,11 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {context.workspace,)}- None if installation.harness == WorkerHarnessV1::QoderCli => {+ None if matches!(+ installation.harness,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ ) =>+ {return Err(DelegationErrorV1::ResumeUnavailable);}None => (@@ -460,14 +484,23 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {{return Err(DelegationErrorV1::CapabilityUnavailable);}- let qoder_budget = (installation.harness == WorkerHarnessV1::QoderCli)- .then(|| {+ let qoder_budget = (matches!(+ installation.harness,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ ))+ .then(|| {+ if installation.harness == WorkerHarnessV1::Pi {+ hiroute_integrations::agents::pi_plan_token_budget(+ &input.compiled_plan.body.materialized,+ )+ } else {hiroute_integrations::agents::qoder_plan_token_budget(&input.compiled_plan.body.materialized,)- })- .transpose()- .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;+ }+ })+ .transpose()+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;CandidateWorkerProfile::build(ProfileInput {context_window_tokens: if let Some(budget) = qoder_budget {Some(budget.context_window_tokens)diff --git a/crates/daemon/src/delegation/installation/discovery.rs b/crates/daemon/src/delegation/installation/discovery.rsindex b89efc3f..30bb2d16 100644--- a/crates/daemon/src/delegation/installation/discovery.rs+++ b/crates/daemon/src/delegation/installation/discovery.rs@@ -107,6 +107,13 @@ impl ScanEnvironment {pub(crate) fn validate_selection(request: &WorkerDependenciesSelectRequestV1,+) -> Result<WorkerDependenciesSelectRequestV1, DelegationErrorV1> {+ validate_selection_for(request, hiroute_integrations::PiSdkCapability::Worker)+}++fn validate_selection_for(+ request: &WorkerDependenciesSelectRequestV1,+ capability: hiroute_integrations::PiSdkCapability,) -> Result<WorkerDependenciesSelectRequestV1, DelegationErrorV1> {if !request.valid() {return Err(DelegationErrorV1::InvalidArguments);@@ -117,11 +124,25 @@ pub(crate) fn validate_selection(.map(|path| normalize_required(Path::new(path), request.node_path.is_none())).transpose()?;let cli = normalize_required(Path::new(&request.cli_path), true)?;+ if request.harness == WorkerHarnessV1::Pi {+ hiroute_integrations::pi_cli_installation(&cli)+ .map_err(|_| DelegationErrorV1::DependenciesInvalid)?;+ }let node = request.node_path.as_deref().map(|path| normalize_required(Path::new(path), true)).transpose()?;+ #[cfg(unix)]+ if request.harness == WorkerHarnessV1::Pi {+ hiroute_integrations::check_pi_sdk_capability(+ &cli,+ node.as_deref()+ .ok_or(DelegationErrorV1::DependenciesInvalid)?,+ capability,+ )+ .map_err(|_| DelegationErrorV1::DependenciesInvalid)?;+ }Ok(WorkerDependenciesSelectRequestV1 {harness: request.harness,adapter_path: adapter.map(path_string).transpose()?,@@ -131,8 +152,16 @@ pub(crate) fn validate_selection(})}-pub(crate) fn validate_persisted_installation(+#[cfg(test)]+fn validate_persisted_installation(+ selection: &WorkerInstallationConfig,+) -> Result<WorkerInstallationConfig, DelegationErrorV1> {+ validate_persisted_installation_for_run(selection, false)+}++pub(crate) fn validate_persisted_installation_for_run(selection: &WorkerInstallationConfig,+ continuing: bool,) -> Result<WorkerInstallationConfig, DelegationErrorV1> {let request = WorkerDependenciesSelectRequestV1 {harness: selection.harness,@@ -147,7 +176,12 @@ pub(crate) fn validate_persisted_installation(.map(|path| path.to_string_lossy().into_owned()),expected_selection_revision: 0,};- let normalized = validate_selection(&request)?;+ let capability = if continuing {+ hiroute_integrations::PiSdkCapability::Continue+ } else {+ hiroute_integrations::PiSdkCapability::Worker+ };+ let normalized = validate_selection_for(&request, capability)?;if normalized.adapter_path != request.adapter_path|| normalized.cli_path != request.cli_path|| normalized.node_path != request.node_path@@ -444,8 +478,13 @@ impl HarnessScan {package_root: &Path,source: WorkerDependencyCandidateSourceV1,) {- let Some(adapter) = names(self.harness).1 else {- return;+ let adapter = if self.harness == WorkerHarnessV1::Pi {+ "pi"+ } else {+ let Some(adapter) = names(self.harness).1 else {+ return;+ };+ adapter};let package_json = package_root.join("package.json");let entry = match package_bin(&package_json, adapter) {@@ -459,7 +498,11 @@ impl HarnessScan {}};self.add_discovered(- WorkerDependencyComponentV1::Adapter,+ if self.harness == WorkerHarnessV1::Pi {+ WorkerDependencyComponentV1::Cli+ } else {+ WorkerDependencyComponentV1::Adapter+ },&package_root.join(entry),source,false,@@ -524,8 +567,10 @@ impl HarnessScan {WorkerDependencyComponentV1::Adapter,WorkerDependencyComponentV1::Node,] {- if self.harness == WorkerHarnessV1::QoderCli- && component != WorkerDependencyComponentV1::Cli+ if (self.harness == WorkerHarnessV1::QoderCli+ && component != WorkerDependencyComponentV1::Cli)+ || (self.harness == WorkerHarnessV1::Pi+ && component == WorkerDependencyComponentV1::Adapter){continue;}@@ -537,7 +582,9 @@ impl HarnessScan {harness: self.harness,component,platform: platform().to_owned(),- command: None,+ command: (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(),});}@@ -671,6 +718,7 @@ fn names(harness: WorkerHarnessV1) -> (&'static [&'static str], Option<&'staticWorkerHarnessV1::CodexCli => (&["codex"], Some("codex-acp")),WorkerHarnessV1::ClaudeCode => (&["claude"], Some("claude-agent-acp")),WorkerHarnessV1::QoderCli => (&["qoder", "qodercli"], None),+ WorkerHarnessV1::Pi => (&["pi"], None),}}@@ -679,6 +727,7 @@ fn package_name(harness: WorkerHarnessV1) -> Option<&'static Path> {WorkerHarnessV1::CodexCli => Some(Path::new("@agentclientprotocol/codex-acp")),WorkerHarnessV1::ClaudeCode => Some(Path::new("@agentclientprotocol/claude-agent-acp")),WorkerHarnessV1::QoderCli => None,+ WorkerHarnessV1::Pi => Some(Path::new("@earendil-works/pi-coding-agent")),}}diff --git a/crates/daemon/src/delegation/installation/discovery/tests.rs b/crates/daemon/src/delegation/installation/discovery/tests.rsindex 1f165d5c..1c84db69 100644--- a/crates/daemon/src/delegation/installation/discovery/tests.rs+++ b/crates/daemon/src/delegation/installation/discovery/tests.rs@@ -28,6 +28,39 @@ fn make_file(path: &Path, mode: u32) {}}+#[test]+#[cfg(unix)]+fn pi_resume_checks_its_own_capability_instead_of_new_session_admission() {+ let root = tempfile::tempdir().unwrap();+ let cli = root.path().join("bin/pi.js");+ let node = root.path().join("bin/node");+ make_file(&cli, 0o700);+ make_file(&node, 0o700);+ fs::write(root.path().join("package.json"), br#"{"name":"@earendil-works/pi-coding-agent","version":"9.0.0-fixture","bin":{"pi":"bin/pi.js"}}"#).unwrap();+ // Emulates only the offline runner receipt. The JS contract tests check the SDK itself.+ fs::write(&node, b"#!/bin/sh\nif [ \"$1\" = --version ]; then echo v22.19.0; elif [ \"$2\" = --check ] && [ \"$4\" = continue ]; then echo hiroute.pi-sdk-capability/v1:ok; else exit 97; fi\n").unwrap();+ let config = WorkerInstallationConfig {+ harness: WorkerHarnessV1::Pi,+ harness_binary: cli,+ adapter: None,+ node_binary: Some(node),+ };+ assert!(validate_persisted_installation_for_run(&config, true).is_ok());+ assert!(matches!(+ validate_persisted_installation_for_run(&config, false),+ Err(DelegationErrorV1::DependenciesInvalid)+ ));+ fs::write(+ config.node_binary.as_ref().unwrap(),+ b"#!/bin/sh\nif [ \"$1\" = --version ]; then echo v22.19.0; else exit 97; fi\n",+ )+ .unwrap();+ assert!(matches!(+ validate_persisted_installation_for_run(&config, true),+ Err(DelegationErrorV1::DependenciesInvalid)+ ));+}+#[test]#[cfg(unix)]fn qoder_discovers_native_aliases_and_official_root_without_inventing_dependencies_or_replacing_selection()diff --git a/crates/daemon/src/delegation/installation/installation_probe.rs b/crates/daemon/src/delegation/installation/installation_probe.rsindex 13fcc69f..bd8f7b4f 100644--- a/crates/daemon/src/delegation/installation/installation_probe.rs+++ b/crates/daemon/src/delegation/installation/installation_probe.rs@@ -258,7 +258,7 @@ 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 => HarnessKind::Unknown,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => HarnessKind::Unknown,}}diff --git a/crates/daemon/src/delegation/installation/probe_server.rs b/crates/daemon/src/delegation/installation/probe_server.rsindex 14d886ea..9f758c67 100644--- a/crates/daemon/src/delegation/installation/probe_server.rs+++ b/crates/daemon/src/delegation/installation/probe_server.rs@@ -327,7 +327,9 @@ fn serve_probe_request(let response = match endpoint.harness {WorkerHarnessV1::CodexCli => responses_stream(endpoint.model),WorkerHarnessV1::ClaudeCode => messages_stream(endpoint.model),- WorkerHarnessV1::QoderCli => return Err(DelegationErrorV1::CapabilityUnavailable),+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => {+ return Err(DelegationErrorV1::CapabilityUnavailable);+ }};write!(stream,diff --git a/crates/daemon/src/delegation/profile/capabilities.rs b/crates/daemon/src/delegation/profile/capabilities.rsindex 9f20896e..6607b480 100644--- a/crates/daemon/src/delegation/profile/capabilities.rs+++ b/crates/daemon/src/delegation/profile/capabilities.rs@@ -3,14 +3,18 @@ use super::*;pub(super) fn identity_contract(input: &ProfileInput<'_>,) -> Result<AcpNativeIdentityContract, DelegationErrorV1> {- if input.harness == WorkerHarnessV1::QoderCli && !input.native_context.is_borrowed() {+ if matches!(+ input.harness,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi+ ) && !input.native_context.is_borrowed()+ {return Err(DelegationErrorV1::CapabilityUnavailable);}// Codex's read-only ACP mode can select workspaceWrite internally. Qoder's restricted// modes have no proven permission contract; neither client may silently upgrade them.if matches!(input.harness,- WorkerHarnessV1::CodexCli | WorkerHarnessV1::QoderCli+ WorkerHarnessV1::CodexCli | WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi) && input.permission_policy != WorkerPermissionPolicyV1::ApproveAll{return Err(DelegationErrorV1::CapabilityUnavailable);@@ -19,5 +23,6 @@ pub(super) fn identity_contract(WorkerHarnessV1::CodexCli => AcpNativeIdentityContract::CodexThreadV1,WorkerHarnessV1::ClaudeCode => AcpNativeIdentityContract::ClaudeSessionV1,WorkerHarnessV1::QoderCli => AcpNativeIdentityContract::QoderSessionV1,+ WorkerHarnessV1::Pi => AcpNativeIdentityContract::ExplicitResponseMetadata,})}diff --git a/crates/daemon/src/delegation/profile/materials.rs b/crates/daemon/src/delegation/profile/materials.rsindex 5327c881..18da8478 100644--- a/crates/daemon/src/delegation/profile/materials.rs+++ b/crates/daemon/src/delegation/profile/materials.rs@@ -380,7 +380,7 @@ 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 harness == WorkerHarnessV1::QoderCli {+ if matches!(harness, WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi) {return Err(DelegationErrorV1::ResumeUnavailable);}if native_session_id.is_empty()@@ -406,7 +406,9 @@ fn legacy_native_history(let durable_root = root.join(match harness {WorkerHarnessV1::CodexCli => "sessions",WorkerHarnessV1::ClaudeCode => "projects",- WorkerHarnessV1::QoderCli => return Err(DelegationErrorV1::ResumeUnavailable),+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => {+ return Err(DelegationErrorV1::ResumeUnavailable);+ }});let metadata =fs::symlink_metadata(&durable_root).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;@@ -447,7 +449,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 => return Err(DelegationErrorV1::ResumeUnavailable),+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => {+ return Err(DelegationErrorV1::ResumeUnavailable);+ }};if !matches_session {continue;diff --git a/crates/daemon/src/delegation/profile/mod.rs b/crates/daemon/src/delegation/profile/mod.rsindex ebfbe1a3..b7029c02 100644--- a/crates/daemon/src/delegation/profile/mod.rs+++ b/crates/daemon/src/delegation/profile/mod.rs@@ -18,6 +18,7 @@ mod claude;mod claude_runtime;mod codex;mod native_context;+mod pi;mod qoder;pub use native_context::NativeWorkerContext;@@ -157,6 +158,8 @@ impl CandidateWorkerProfile {}(WorkerHarnessV1::ClaudeCode, _) => "default",(WorkerHarnessV1::QoderCli, WorkerPermissionPolicyV1::ApproveAll) => "yolo",+ (WorkerHarnessV1::Pi, WorkerPermissionPolicyV1::ApproveAll) => "approve-all",+ (WorkerHarnessV1::Pi, _) => return Err(DelegationErrorV1::CapabilityUnavailable),(WorkerHarnessV1::QoderCli, _) => return Err(DelegationErrorV1::CapabilityUnavailable),};let mut env = BTreeMap::new();@@ -197,9 +200,17 @@ impl CandidateWorkerProfile {}WorkerHarnessV1::ClaudeCode => claude::render(&input, &projected_tools)?,WorkerHarnessV1::QoderCli => qoder::render(&input, &private_root)?,+ WorkerHarnessV1::Pi => pi::render(&input)?,};env.extend(rendered.env);let (executable, args) = match launch {+ WorkerLaunchFormV1::NativeSdk { cli, node } => (+ PathBuf::from(node),+ vec![+ private_root.join("pi-worker-bridge.mjs"),+ PathBuf::from(cli),+ ],+ ),WorkerLaunchFormV1::NativeAcp { cli } => (PathBuf::from(cli), rendered.native_args),WorkerLaunchFormV1::AdapterAcp { adapter, node, .. } => {if let Some(bootstrap) = rendered.adapter_bootstrap {diff --git a/crates/daemon/src/delegation/profile/native_context.rs b/crates/daemon/src/delegation/profile/native_context.rsindex a05e2d0f..44a2bdb1 100644--- a/crates/daemon/src/delegation/profile/native_context.rs+++ b/crates/daemon/src/delegation/profile/native_context.rs@@ -26,6 +26,7 @@ impl NativeWorkerContext {let (variable, default) = match harness {WorkerHarnessV1::CodexCli => ("CODEX_HOME", ".codex"),WorkerHarnessV1::ClaudeCode => ("CLAUDE_CONFIG_DIR", ".claude"),+ WorkerHarnessV1::Pi => ("PI_CODING_AGENT_DIR", ".pi/agent"),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 16881741..35b128d4 100644--- a/crates/daemon/src/delegation/profile/native_history.rs+++ b/crates/daemon/src/delegation/profile/native_history.rs@@ -80,7 +80,7 @@ impl TaskSessionRoot {if binding.native_session_id != native_session_id {return Err(DelegationErrorV1::ResumeUnavailable);}- verify_borrowed_history(&context, native_session_id)+ verify_borrowed_history(&self.path, &context, native_session_id)}None => legacy_native_history(&self.path, self.harness, native_session_id).map(|_| ()),}@@ -94,7 +94,11 @@ impl TaskSessionRoot {native_session_id: &str,) -> Result<PathBuf, DelegationErrorV1> {if let Some(context) = read_context(root, harness)? {- return claude_transcript(&context, native_session_id);+ return if harness == WorkerHarnessV1::Pi {+ pi_transcript(root, &context, native_session_id)+ } else {+ claude_transcript(&context, native_session_id)+ };}legacy_native_history(root, harness, native_session_id)?.pop()@@ -113,7 +117,7 @@ pub(super) fn read_context(return match fs::symlink_metadata(root.join(SESSION_FILE)) {Err(error)if error.kind() == std::io::ErrorKind::NotFound- && harness != WorkerHarnessV1::QoderCli =>+ && !matches!(harness, WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi) =>{Ok(None)}@@ -152,7 +156,7 @@ pub(super) fn retain_borrowed_session(native_session_id: &str,) -> Result<Vec<String>, DelegationErrorV1> {let context = read_context(root, harness)?.ok_or(DelegationErrorV1::ResumeUnavailable)?;- verify_borrowed_history(&context, native_session_id)?;+ verify_borrowed_history(root, &context, native_session_id)?;write_owned_json(root,SESSION_FILE,@@ -162,7 +166,11 @@ pub(super) fn retain_borrowed_session(native_session_id: native_session_id.to_owned(),},)?;- Ok(vec![SESSION_FILE.to_owned()])+ Ok(if harness == WorkerHarnessV1::Pi {+ vec![SESSION_FILE.to_owned(), "native-pi.jsonl".into()]+ } else {+ vec![SESSION_FILE.to_owned()]+ })}pub(super) fn verify_continuation_materials(@@ -171,11 +179,19 @@ pub(super) fn verify_continuation_materials(required: &[PathBuf],) -> Result<(), DelegationErrorV1> {if let Some(context) = read_context(root, harness)? {- if required != [PathBuf::from(SESSION_FILE)] {+ let expected = if harness == WorkerHarnessV1::Pi {+ vec![+ PathBuf::from(SESSION_FILE),+ PathBuf::from("native-pi.jsonl"),+ ]+ } else {+ vec![PathBuf::from(SESSION_FILE)]+ };+ if required != expected {return Err(DelegationErrorV1::ResumeUnavailable);}let binding = read_binding(root, &context)?;- verify_borrowed_history(&context, &binding.native_session_id)?;+ verify_borrowed_history(root, &context, &binding.native_session_id)?;}Ok(())}@@ -197,16 +213,48 @@ fn context_digest(context: &ContextDescriptor) -> Result<CanonicalDigest, Delega}fn verify_borrowed_history(+ root: &Path,context: &ContextDescriptor,native_session_id: &str,) -> Result<(), DelegationErrorV1> {validate_session_id(native_session_id)?;+ if context.harness == WorkerHarnessV1::Pi {+ pi_transcript(root, context, native_session_id)?;+ }if context.harness == WorkerHarnessV1::ClaudeCode {claude_transcript(context, native_session_id)?;}Ok(())}+/// Pi's exact file is owned by this task; native open must never recreate missing history.+fn pi_transcript(+ root: &Path,+ context: &ContextDescriptor,+ id: &str,+) -> Result<PathBuf, DelegationErrorV1> {+ let relative = Path::new("native-pi.jsonl");+ check_history(root, relative).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;+ let path = root.join(relative);+ let file = fs::File::open(&path).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;+ use std::io::BufRead;+ let mut reader = std::io::BufReader::new(file.take(METADATA_LIMIT));+ let mut header = String::new();+ reader+ .read_line(&mut header)+ .map_err(|_| DelegationErrorV1::ResumeUnavailable)?;+ let header: serde_json::Value =+ serde_json::from_str(&header).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;+ if header["type"] != "session"+ || header["version"] != 3+ || header["id"] != id+ || header["cwd"].as_str() != context.context.workspace.to_str()+ {+ return Err(DelegationErrorV1::ResumeUnavailable);+ }+ Ok(path)+}+fn claude_transcript(descriptor: &ContextDescriptor,native_session_id: &str,diff --git a/crates/daemon/src/delegation/profile/pi.rs b/crates/daemon/src/delegation/profile/pi.rsnew file mode 100644index 00000000..90f2fb79--- /dev/null+++ b/crates/daemon/src/delegation/profile/pi.rs@@ -0,0 +1,55 @@+//! Pi's native resources are borrowed; SDK transport and exact history stay task-owned.+use super::*;++pub(super) fn render(+ input: &ProfileInput<'_>,+) -> Result<RenderedHarnessProfile, DelegationErrorV1> {+ hiroute_integrations::agents::pi_cli_installation(input.harness_binary)+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;+ let context = input+ .context_window_tokens+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;+ let output = input+ .max_output_tokens+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;+ if context <= output || context > (1 << 53) - 1 || output == 0 || output > (1 << 53) - 1 {+ return Err(DelegationErrorV1::CapabilityUnavailable);+ }+ let provider = "hiroute-worker";+ let mut rendered = RenderedHarnessProfile {+ native_model_id: format!("{provider}/{}", input.alias),+ files: vec![+ RunMaterialFile {+ relative_path: "pi-worker-bridge.mjs".into(),+ contents: Zeroizing::new(include_bytes!("pi_worker_bridge.mjs").to_vec()),+ executable: false,+ },+ RunMaterialFile {+ relative_path: "pi-sdk-contract.mjs".into(),+ contents: Zeroizing::new(hiroute_integrations::PI_SDK_CONTRACT.as_bytes().to_vec()),+ executable: false,+ },+ ],+ ..Default::default()+ };+ let route = json!({"minimumNode":hiroute_integrations::PI_NODE_MINIMUM,"provider":provider,"endpoint":format!("http://{}/v1",input.gateway),+ "model":{"id":input.alias,"name":"HiRoute frozen Plan","reasoning":false,"input":["text"],+ "cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},"contextWindow":context,"maxTokens":output}});+ for (key, value) in [+ (+ "PI_CODING_AGENT_DIR",+ path_string(input.native_context.config_root())?,+ ),+ (+ "HIROUTE_PI_SESSION_ROOT",+ path_string(input.session_root.path())?,+ ),+ ("HIROUTE_PI_ROUTE", route.to_string()),+ ("HIROUTE_RUN_TOKEN", secret_string(&input.token)?),+ ("PI_OFFLINE", "1".into()),+ ("PI_TELEMETRY", "0".into()),+ ] {+ rendered.env.insert(key.into(), Zeroizing::new(value));+ }+ Ok(rendered)+}diff --git a/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs b/crates/daemon/src/delegation/profile/pi_worker_bridge.mjsnew file mode 100644index 00000000..236ce19a--- /dev/null+++ b/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs@@ -0,0 +1,561 @@+// HiRoute's ACP transport for the explicitly selected official Pi npm SDK.+// The daemon owns admission, credentials, process groups, retention and task state.+import { readFileSync, realpathSync, lstatSync, openSync, readSync, closeSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { createInterface } from "node:readline";+import { loadPiSdk, assertPiCapabilities } from "./pi-sdk-contract.mjs";++process.umask(0o077);+const output = (value) => process.stdout.write(JSON.stringify(value) + "\n");+let closing = false;+const reply = (request, result) => {+ if (!closing) output({ jsonrpc: "2.0", id: request.id, result });+};+const reject = (request, stage) => {+ if (!closing && request.id !== undefined)+ output({+ jsonrpc: "2.0",+ id: request.id,+ error: {+ code: -32000,+ message: "Pi managed operation unavailable",+ data: { schema: "hiroute.pi-worker-failure/v1", stage },+ },+ });+};+let session;+let active = false;+let cancelled = false;+let inFlight;+let stopping;+async function shutdown() {+ if (stopping) return stopping;+ closing = true;+ process.stdin.destroy();+ // The daemon retains process-group authority; this also bounds a broken SDK abort.+ const deadline = setTimeout(() => process.exit(1), 2000);+ deadline.unref();+ stopping = (async () => {+ try {+ if (session) {+ session.clearQueue();+ await session.abort();+ }+ await inFlight;+ } finally {+ // Session creation may have completed after the first abort attempt.+ try {+ if (session) {+ session.clearQueue();+ await session.abort();+ }+ } finally {+ session?.dispose();+ }+ }+ })()+ .catch(() => {+ process.exitCode = 1;+ })+ .finally(() => clearTimeout(deadline));+ return stopping;+}+process.once("SIGTERM", () => {+ void shutdown().then(() => process.exit(process.exitCode ?? 0));+});+process.once("SIGINT", () => {+ void shutdown().then(() => process.exit(process.exitCode ?? 0));+});+process.stdout.on("error", () => {+ void shutdown().then(() => process.exit(1));+});+let startupStage = "configuration";+let startupFailure;+let dispatch;++function messageValid(message) {+ if (!message || !Number.isFinite(message.timestamp)) return false;+ const content = message.content;+ if (message.role === "system")+ return (+ typeof content === "string" &&+ (content.length > 0 || (message.sections && typeof message.sections === "object"))+ );+ if (message.role === "user" && typeof content === "string") return true;+ if (!["user", "assistant", "toolResult"].includes(message.role) || !Array.isArray(content))+ return false;+ for (const part of content) {+ if (!part || typeof part.type !== "string") return false;+ if (part.type === "text") {+ if (typeof part.text !== "string") return false;+ } else if (part.type === "thinking") {+ if (typeof part.thinking !== "string") return false;+ } else if (part.type === "image") {+ if (typeof part.data !== "string" || typeof part.mimeType !== "string") return false;+ } else if (part.type === "toolCall") {+ if (+ typeof part.id !== "string" ||+ typeof part.name !== "string" ||+ !part.arguments ||+ typeof part.arguments !== "object" ||+ Array.isArray(part.arguments)+ )+ return false;+ } else return false;+ }+ if (message.role === "assistant")+ return (+ typeof message.api === "string" &&+ typeof message.provider === "string" &&+ typeof message.model === "string" &&+ message.usage &&+ typeof message.usage === "object" &&+ ["stop", "length", "toolUse", "error", "aborted"].includes(message.stopReason)+ );+ if (message.role === "toolResult")+ return (+ typeof message.toolCallId === "string" &&+ typeof message.toolName === "string" &&+ typeof message.isError === "boolean"+ );+ return true;+}++function ownedFile(path, root) {+ const stat = lstatSync(path);+ if (+ !stat.isFile() ||+ stat.isSymbolicLink() ||+ stat.nlink !== 1 ||+ realpathSync(path) !== path ||+ dirname(path) !== root ||+ stat.uid !== process.getuid() ||+ (stat.mode & 0o077) !== 0+ )+ throw new Error();+ if (stat.size > 64 * 1024 * 1024) throw new Error();+ const lines = readFileSync(path, "utf8").split("\n");+ if (lines.pop() !== "") throw new Error();+ const entries = lines.map((line) => JSON.parse(line));+ if (entries.length > 100000 || lines.some((line) => Buffer.byteLength(line) > 8 * 1024 * 1024))+ throw new Error();+ if (+ entries.length < 2 ||+ !entries.slice(1).some((entry) => entry.type === "message" || entry.type === "compaction")+ )+ throw new Error();+ const seen = new Set();+ const byId = new Map();+ for (const entry of entries.slice(1)) {+ if (+ typeof entry.id !== "string" ||+ !entry.id ||+ seen.has(entry.id) ||+ !Number.isFinite(Date.parse(entry.timestamp)) ||+ (entry.parentId !== null && !seen.has(entry.parentId))+ )+ throw new Error();+ if (entry.type === "message") {+ if (!messageValid(entry.message)) throw new Error();+ } else if (entry.type === "model_change") {+ if (typeof entry.provider !== "string" || typeof entry.modelId !== "string")+ throw new Error();+ } else if (entry.type === "thinking_level_change") {+ if (typeof entry.thinkingLevel !== "string") throw new Error();+ } else if (entry.type === "compaction") {+ if (+ typeof entry.summary !== "string" ||+ !entry.summary ||+ !seen.has(entry.firstKeptEntryId) ||+ !Number.isFinite(entry.tokensBefore) ||+ entry.tokensBefore < 0+ )+ throw new Error();+ } else if (entry.type === "context_edit") {+ const target = byId.get(entry.targetId);+ if (+ target?.type !== "message" ||+ !["user", "assistant", "toolResult"].includes(target.message.role)+ )+ throw new Error();+ let ancestor = entry.parentId;+ while (ancestor !== null && ancestor !== entry.targetId)+ ancestor = byId.get(ancestor).parentId;+ if (ancestor !== entry.targetId) throw new Error();+ if (entry.replacement !== null) {+ const replacement = entry.replacement;+ if (+ !replacement ||+ typeof replacement !== "object" ||+ Array.isArray(replacement) ||+ !("content" in replacement)+ )+ throw new Error();+ let content = replacement.content;+ if (typeof content === "string" && target.message.role !== "user")+ content = [{ type: "text", text: content }];+ if (!messageValid({ ...target.message, content })) throw new Error();+ }+ } else if (entry.type === "usage") {+ if (+ typeof entry.kind !== "string" ||+ typeof entry.provider !== "string" ||+ typeof entry.model !== "string" ||+ !entry.usage ||+ typeof entry.usage !== "object"+ )+ throw new Error();+ } else throw new Error();+ seen.add(entry.id);+ byId.set(entry.id, entry);+ }+ const fd = openSync(path, "r");+ try {+ const bytes = Buffer.alloc(8192);+ const count = readSync(fd, bytes, 0, bytes.length, 0);+ const end = bytes.subarray(0, count).indexOf(10);+ if (end < 0) throw new Error();+ const header = JSON.parse(bytes.subarray(0, end).toString("utf8"));+ if (+ header.type !== "session" ||+ header.version !== 3 ||+ typeof header.id !== "string" ||+ !header.id ||+ !Number.isFinite(Date.parse(header.timestamp)) ||+ header.cwd !== process.cwd()+ )+ throw new Error();+ return header;+ } finally {+ closeSync(fd);+ }+}++try {+ const route = JSON.parse(process.env.HIROUTE_PI_ROUTE);+ const nodeVersion = process.versions.node.split(".").map(Number);+ if (+ nodeVersion.some((part, index) =>+ index === 0+ ? part < route.minimumNode[0]+ : nodeVersion[0] === route.minimumNode[0] && index === 1 && part < route.minimumNode[1],+ )+ )+ throw new Error();+ startupStage = "sdk_load";+ const { sdk, pkg } = await loadPiSdk(process.argv[2]);+ startupStage = "sdk_capability";+ assertPiCapabilities(sdk, "collaboration");+ const {+ createAgentSession,+ ModelRuntime,+ SettingsManager,+ SessionManager,+ DefaultResourceLoader,+ } = sdk;+ const agentDir = resolve(process.env.PI_CODING_AGENT_DIR);+ const root = realpathSync(process.env.HIROUTE_PI_SESSION_ROOT);+ const file = join(root, "native-pi.jsonl");+ const token = process.env.HIROUTE_RUN_TOKEN;+ delete process.env.HIROUTE_RUN_TOKEN;+ delete process.env.HIROUTE_PI_ROUTE;+ const modelId = route.provider + "/" + route.model.id;+ startupStage = "route_binding";+ const credentials = new Map();+ const runtime = await ModelRuntime.create({+ modelsPath: null,+ allowModelNetwork: false,+ refreshOnCreate: false,+ credentials: {+ async read(id) {+ return credentials.get(id);+ },+ async list() {+ return [];+ },+ async modify(id, fn) {+ const next = await fn(credentials.get(id));+ if (next !== undefined) credentials.set(id, next);+ return credentials.get(id);+ },+ async delete(id) {+ credentials.delete(id);+ },+ },+ });+ runtime.registerProvider(route.provider, {+ api: "openai-responses",+ baseUrl: route.endpoint,+ models: [route.model],+ });+ await runtime.setRuntimeApiKey(route.provider, token);+ const model = runtime.getModels(route.provider).find((item) => item.id === route.model.id);+ if (+ !model ||+ model.api !== "openai-responses" ||+ model.baseUrl !== route.endpoint ||+ model.contextWindow !== route.model.contextWindow ||+ model.maxTokens !== route.model.maxTokens+ )+ throw new Error();++ // Read native resource settings without writing them. Snapshot each scope, so reload cannot+ // undo host overrides or turn relative project Skill paths into user paths.+ startupStage = "resources";+ const raw = SettingsManager.create(process.cwd(), agentDir, {+ projectTrusted: true,+ });+ const snapshots = new Map(+ ["global", "project"].map((scope) => {+ const source = scope === "global" ? raw.getGlobalSettings() : raw.getProjectSettings();+ return [+ scope,+ JSON.stringify({+ ...source,+ extensions: [],+ httpProxy: undefined,+ cacheWarming: "off",+ retry: { enabled: false },+ compaction: {+ enabled: true,+ reserveTokens: route.model.maxTokens,+ keepRecentTokens: Math.min(Math.floor(route.model.contextWindow / 4), 20000),+ modelOverrides: {},+ },+ }),+ ];+ }),+ );+ const settingsManager = SettingsManager.fromStorage(+ {+ withLock(scope, fn) {+ const next = fn(snapshots.get(scope));+ if (next !== undefined) snapshots.set(scope, next);+ },+ },+ { projectTrusted: true },+ );+ const resourceLoader = new DefaultResourceLoader({+ cwd: process.cwd(),+ agentDir,+ settingsManager,+ noExtensions: true,+ });+ await resourceLoader.reload();++ function configuration() {+ return [+ {+ id: "model",+ name: "Model",+ type: "select",+ category: "model",+ currentValue: session.model.provider + "/" + session.model.id,+ options: [{ value: modelId, name: "Frozen Plan" }],+ },+ ];+ }+ function ready() {+ return {+ sessionId: session.sessionId,+ _meta: { agentSessionId: session.sessionId },+ configOptions: configuration(),+ modes: {+ currentModeId: "approve-all",+ availableModes: [{ id: "approve-all", name: "Approve all" }],+ },+ };+ }+ function requireSession(params) {+ if (!session || params.sessionId !== session.sessionId) throw new Error();+ }+ let initialized = false;+ dispatch = async (request) => {+ const p = request.params || {};+ let stage = "request";+ try {+ if (request.method === "initialize") {+ if (initialized || p.protocolVersion !== 1) throw new Error();+ initialized = true;+ reply(request, {+ protocolVersion: 1,+ agentInfo: { name: "hiroute-pi-sdk", version: pkg.version },+ agentCapabilities: { loadSession: true },+ });+ return;+ }+ if (!initialized) throw new Error();+ if (request.method === "session/new" || request.method === "session/load") {+ if (session || realpathSync(p.cwd) !== process.cwd() || p.mcpServers?.length)+ throw new Error();+ let manager;+ if (request.method === "session/load") {+ stage = "sdk_capability";+ assertPiCapabilities(sdk, "continue");+ stage = "history";+ const header = ownedFile(file, root);+ if (header.id !== p.sessionId) throw new Error();+ stage = "session_load";+ manager = SessionManager.open(file, root);+ if (+ manager.getSessionId() !== header.id ||+ manager.getSessionFile() !== file ||+ manager.buildSessionContext().messages.length === 0+ )+ throw new Error();+ } else {+ stage = "sdk_capability";+ assertPiCapabilities(sdk, "worker");+ stage = "session_create";+ try {+ lstatSync(file);+ throw new Error("already-exists");+ } catch (error) {+ if (error.code !== "ENOENT") throw error;+ }+ manager = SessionManager.create(process.cwd(), root);+ manager.setSessionFile(file);+ }+ stage = request.method === "session/load" ? "session_load" : "session_create";+ ({ session } = await createAgentSession({+ cwd: process.cwd(),+ agentDir,+ modelRuntime: runtime,+ model,+ thinkingLevel: "off",+ settingsManager,+ resourceLoader,+ sessionManager: manager,+ tools: ["read", "bash", "edit", "write", "grep", "find", "ls"],+ }));+ // SDK load may restore its previous model. Frozen route selection is explicit.+ stage = "route_binding";+ await session.setModel(model);+ if (session.model?.provider !== route.provider || session.model?.id !== route.model.id)+ throw new Error();+ session.subscribe((event) => {+ if (+ !closing &&+ active &&+ event.type === "message_update" &&+ event.assistantMessageEvent?.type === "text_delta"+ ) {+ output({+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: session.sessionId,+ update: {+ sessionUpdate: "agent_message_chunk",+ content: {+ type: "text",+ text: event.assistantMessageEvent.delta,+ },+ },+ },+ });+ }+ });+ reply(request, ready());+ return;+ }+ requireSession(p);+ if (request.method === "session/set_mode") {+ if (p.modeId !== "approve-all") throw new Error();+ reply(request, {});+ return;+ }+ if (request.method === "session/set_config_option") {+ if (p.configId !== "model" || p.value !== modelId) throw new Error();+ reply(request, { configOptions: configuration() });+ return;+ }+ if (request.method === "session/cancel") {+ cancelled = true;+ try {+ session.clearQueue();+ await session.abort();+ } catch {+ process.exitCode = 1;+ void shutdown();+ }+ return;+ }+ if (request.method === "session/prompt") {+ if (active || !Array.isArray(p.prompt) || p.prompt.some((part) => part.type !== "text"))+ throw new Error();+ const text = p.prompt.map((part) => part.text).join("\n");+ if (!text || text.length > 256 * 1024) throw new Error();+ active = true;+ cancelled = false;+ try {+ stage = "prompt";+ try {+ await session.prompt(text);+ } catch (error) {+ if (!cancelled) throw error;+ }+ const last = [...session.messages].reverse().find((item) => item.role === "assistant");+ if (!cancelled && last?.stopReason !== "stop") throw new Error();+ // A cancelled prompt can legitimately have no completed assistant/history yet.+ if (!cancelled) {+ stage = "history";+ const header = ownedFile(file, root);+ if (header.id !== session.sessionId) throw new Error();+ }+ reply(request, { stopReason: cancelled ? "cancelled" : "end_turn" });+ } finally {+ active = false;+ }+ return;+ }+ throw new Error();+ } catch {+ reject(request, stage);+ }+ };+} catch {+ // Keep the transport alive long enough to return a safe correlated initialize error.+ // Raw SDK errors can contain credentials, file contents or model responses.+ startupFailure = startupStage;+}++try {+ const input = createInterface({ input: process.stdin, crlfDelay: Infinity });+ for await (const line of input) {+ if (closing) break;+ if (Buffer.byteLength(line) > 8 * 1024 * 1024) throw new Error();+ const request = JSON.parse(line);+ if (+ !request ||+ request.jsonrpc !== "2.0" ||+ typeof request.method !== "string" ||+ (request.params !== undefined &&+ (!request.params || typeof request.params !== "object" || Array.isArray(request.params))) ||+ (request.id !== undefined &&+ !(+ (typeof request.id === "string" && request.id.length <= 1024) ||+ Number.isSafeInteger(request.id)+ ))+ )+ throw new Error();+ if (startupFailure) {+ reject(request, startupFailure);+ break;+ }+ if (request.method === "session/cancel") {+ // Cancellation must overtake a pending prompt; all other requests are exclusive.+ await dispatch(request);+ } else if (inFlight) {+ reject(request, "busy");+ } else {+ inFlight = dispatch(request).finally(() => {+ inFlight = undefined;+ });+ }+ }+} catch {+ process.exitCode = 1;+} finally {+ await shutdown();+}diff --git a/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs b/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjsnew file mode 100644index 00000000..08fda934--- /dev/null+++ b/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs@@ -0,0 +1,373 @@+import nodeTest from "node:test";+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import {+ mkdtempSync,+ realpathSync,+ mkdirSync,+ writeFileSync,+ readFileSync,+ existsSync,+ rmSync,+ copyFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { createInterface } from "node:readline";+import { once } from "node:events";+const test = (name, fn) => nodeTest(name, { timeout: 5000 }, fn);++// A selected official-package shape with controlled failures, not native product evidence.+const sdk = `+import {appendFileSync,readFileSync} from 'node:fs';+const receipt = event => appendFileSync(process.env.FIXTURE_RECEIPT, event+'\\n');+const secret = 'fixture-private-token-do-not-emit';+export const CURRENT_SESSION_VERSION = 3;+export const createReadTool = () => {};+export const createBashTool = () => {};+export class SettingsManager {+ static create() {return new SettingsManager();}+ static fromStorage() {return new SettingsManager();}+ getGlobalSettings() {return {};}+ getProjectSettings() {return {};}+}+export class DefaultResourceLoader {async reload() {} getSkills() {return {skills:[]};}}+export class ModelRuntime {+ static async create() {return new ModelRuntime();}+ registerProvider(provider, value) {this.models=value.models.map(model=>({...model,provider,api:value.api,baseUrl:value.baseUrl}));}+ setRuntimeApiKey() {}+ getModels() {return this.models;}+}+export class SessionManager {+ static create() {return new SessionManager();}+ static open(file) {receipt('open');const manager=new SessionManager();manager.file=file;return manager;}+ getSessionId() {return 'fixture-session';}+ getSessionFile() {return this.file;}+ setSessionFile(file) {this.file=file;}+ buildSessionContext() {return {messages:[{}]};}+}+export class AgentSession {+ constructor() {this.sessionId='fixture-session';this.messages=[];}+ async setModel(model) {this.model=model;}+ subscribe(handler) {this.handler=handler;}+ async prompt() {+ receipt('prompt');+ if(process.env.FIXTURE_FAILURE==='history') {this.messages=readFileSync('native-pi.jsonl','utf8').trim().split('\\n').map(JSON.parse).filter(e=>e.type==='message').map(e=>e.message);return;}+ if(process.env.FIXTURE_FAILURE==='reject') throw new Error(secret);+ if(process.env.FIXTURE_FAILURE==='terminal') {this.messages=[{role:'assistant',stopReason:'error',errorMessage:secret}];return;}+ return new Promise((resolve,reject)=>{this.pending=reject;});+ }+ clearQueue() {}+ async abort() {receipt('abort');this.pending?.(new Error(secret));}+ dispose() {receipt('dispose');}+}+export async function createAgentSession() {+ receipt('creating');+ await new Promise(resolve=>setTimeout(resolve, Number(process.env.FIXTURE_CREATE_DELAY||0)));+ receipt('created');+ return {session:new AgentSession()};+}+`;++function fixture(t, env = {}) {+ const root = realpathSync(mkdtempSync(join(tmpdir(), "hiroute-pi-bridge-test-")));+ const packageRoot = join(root, "package");+ mkdirSync(packageRoot);+ const cli = join(packageRoot, "cli.mjs");+ writeFileSync(cli, "");+ writeFileSync(+ join(packageRoot, "package.json"),+ JSON.stringify({+ name: "@earendil-works/pi-coding-agent",+ version: "99.0.0-fixture",+ bin: { pi: "cli.mjs" },+ exports: "./sdk.mjs",+ }),+ );+ if (env.FIXTURE_FAILURE !== "sdk_missing") writeFileSync(join(packageRoot, "sdk.mjs"), sdk);+ const bridge = join(root, "bridge.mjs");+ copyFileSync(+ process.env.HIROUTE_TEST_PI_BRIDGE ||+ fileURLToPath(new URL("./pi_worker_bridge.mjs", import.meta.url)),+ bridge,+ );+ copyFileSync(+ fileURLToPath(+ new URL("../../../../integrations/src/agents/pi_sdk_contract.mjs", import.meta.url),+ ),+ join(root, "pi-sdk-contract.mjs"),+ );+ const receipt = join(root, "receipt");+ const child = spawn(process.execPath, [bridge, cli], {+ cwd: root,+ stdio: ["pipe", "pipe", "pipe"],+ env: {+ PATH: process.env.PATH,+ HOME: root,+ PI_CODING_AGENT_DIR: root,+ HIROUTE_PI_SESSION_ROOT: root,+ HIROUTE_RUN_TOKEN: "fixture-private-token-do-not-emit",+ HIROUTE_PI_ROUTE: JSON.stringify({+ minimumNode: [22, 19],+ provider: "managed",+ endpoint: "http://127.0.0.1:1/v1",+ model: { id: "frozen", contextWindow: 16384, maxTokens: 4096 },+ }),+ FIXTURE_RECEIPT: receipt,+ ...env,+ },+ });+ let output = "";+ let stderr = "";+ child.stdout.on("data", (data) => {+ output += data;+ });+ child.stderr.on("data", (data) => {+ stderr += data;+ });+ const exit = once(child, "exit");+ const replies = new Map();+ const waiting = new Map();+ createInterface({ input: child.stdout }).on("line", (line) => {+ const response = JSON.parse(line);+ if (response.id === undefined) return;+ replies.set(response.id, response);+ waiting.get(response.id)?.(response);+ });+ t.after(async () => {+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");+ await exit;+ assert.doesNotMatch(output + stderr, /fixture-private-token-do-not-emit/);+ rmSync(root, { recursive: true, force: true });+ });+ let id = 0;+ return {+ root,+ child,+ exit,+ events: () => (existsSync(receipt) ? readFileSync(receipt, "utf8").trim().split("\n") : []),+ send(method, params, notification = false) {+ const requestId = ++id;+ const response = new Promise((resolve, reject) => {+ if (notification) {+ resolve();+ return;+ }+ const timer = setTimeout(() => reject(new Error("missing ACP response: " + method)), 2000);+ waiting.set(requestId, (value) => {+ clearTimeout(timer);+ resolve(value);+ });+ });+ child.stdin.write(+ JSON.stringify({+ jsonrpc: "2.0",+ ...(notification ? {} : { id: requestId }),+ method,+ params,+ }) + "\n",+ );+ return response;+ },+ async ready() {+ assert.equal(+ (await this.send("initialize", { protocolVersion: 1 })).result.protocolVersion,+ 1,+ );+ return this.send("session/new", { cwd: root, mcpServers: [] });+ },+ async event(value) {+ const deadline = Date.now() + 2000;+ while (!this.events().includes(value)) {+ if (Date.now() > deadline) throw new Error("missing native event: " + value);+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ },+ };+}++function stage(response) {+ return response.error?.data?.stage;+}++test("startup dependency failure reaches the ACP caller without raw exception text", async (t) => {+ const f = fixture(t, { FIXTURE_FAILURE: "sdk_missing" });+ assert.equal(stage(await f.send("initialize", { protocolVersion: 1 })), "sdk_load");+ await f.exit;+});++test("only one native session is created when creation requests overlap", async (t) => {+ const f = fixture(t, { FIXTURE_CREATE_DELAY: "80" });+ await f.send("initialize", { protocolVersion: 1 });+ const first = f.send("session/new", { cwd: f.root, mcpServers: [] });+ await f.event("creating");+ assert.equal(stage(await f.send("session/new", { cwd: f.root, mcpServers: [] })), "busy");+ assert.equal((await first).result.sessionId, "fixture-session");+ assert.equal(f.events().filter((event) => event === "created").length, 1);+});++for (const failure of ["reject", "terminal"])+ test("native " + failure + " is an execution failure, never success", async (t) => {+ const f = fixture(t, { FIXTURE_FAILURE: failure });+ await f.ready();+ assert.equal(+ stage(+ await f.send("session/prompt", {+ sessionId: "fixture-session",+ prompt: [{ type: "text", text: "run" }],+ }),+ ),+ "prompt",+ );+ });++test("cancellation overtakes a prompt and does not require completed history", async (t) => {+ const f = fixture(t);+ await f.ready();+ const result = f.send("session/prompt", {+ sessionId: "fixture-session",+ prompt: [{ type: "text", text: "run" }],+ });+ await f.event("prompt");+ await f.send("session/cancel", { sessionId: "fixture-session" }, true);+ assert.equal((await result).result.stopReason, "cancelled");+ f.child.stdin.end();+ await f.exit;+ assert.equal(f.events().filter((event) => event === "dispose").length, 1);+});++test("disconnect during session creation releases the eventual session", async (t) => {+ const f = fixture(t, { FIXTURE_CREATE_DELAY: "80" });+ await f.send("initialize", { protocolVersion: 1 });+ // Do not await a response after the caller has disconnected.+ f.child.stdin.write(+ JSON.stringify({+ jsonrpc: "2.0",+ id: 99,+ method: "session/new",+ params: { cwd: f.root, mcpServers: [] },+ }) + "\n",+ );+ await f.event("creating");+ f.child.stdin.end();+ await f.exit;+ assert.equal(f.events().filter((event) => event === "dispose").length, 1);+ assert.ok(f.events().includes("abort"));+});++test("malformed input aborts the active work and releases its session", async (t) => {+ const f = fixture(t);+ await f.ready();+ f.child.stdin.write(+ JSON.stringify({+ jsonrpc: "2.0",+ id: 99,+ method: "session/prompt",+ params: { sessionId: "fixture-session", prompt: [{ type: "text", text: "run" }] },+ }) + "\n",+ );+ await f.event("prompt");+ f.child.stdin.write("{invalid\n");+ await f.exit;+ assert.ok(f.events().includes("abort"));+ assert.ok(f.events().includes("dispose"));+});++test("missing exact history is rejected before SDK open or model work", async (t) => {+ const f = fixture(t);+ await f.send("initialize", { protocolVersion: 1 });+ assert.equal(+ stage(await f.send("session/load", { cwd: f.root, mcpServers: [], sessionId: "old" })),+ "history",+ );+ assert.deepEqual(f.events(), []);+});++test("a closed output pipe releases the native session without an unhandled error", async (t) => {+ const f = fixture(t);+ await f.ready();+ f.child.stdout.destroy();+ f.child.stdin.write(+ JSON.stringify({+ jsonrpc: "2.0",+ id: 99,+ method: "session/set_mode",+ params: { sessionId: "fixture-session", modeId: "approve-all" },+ }) + "\n",+ );+ await f.exit;+ assert.ok(f.events().includes("dispose"));+});++function editedHistory(f, replacement = null, targetId = "failed") {+ const timestamp = new Date().toISOString();+ const assistant = (stopReason) => ({+ role: "assistant",+ timestamp: Date.now(),+ content: [{ type: "text", text: "result" }],+ api: "openai-responses",+ provider: "managed",+ model: "frozen",+ usage: {},+ stopReason,+ });+ const entries = [+ { type: "session", version: 3, id: "fixture-session", timestamp, cwd: f.root },+ {+ type: "message",+ id: "user",+ parentId: null,+ timestamp,+ message: { role: "user", timestamp: Date.now(), content: "task" },+ },+ { type: "message", id: "failed", parentId: "user", timestamp, message: assistant("error") },+ { type: "context_edit", id: "omit", parentId: "failed", timestamp, targetId, replacement },+ { type: "message", id: "recovered", parentId: "omit", timestamp, message: assistant("stop") },+ ];+ writeFileSync(join(f.root, "native-pi.jsonl"), entries.map(JSON.stringify).join("\n") + "\n", {+ mode: 0o600,+ });+}++for (const operation of ["prompt", "load"]) {+ for (const replacement of [null, { content: "recovered content" }]) {+ test(`valid context edit survives ${operation}: ${replacement === null ? "omit" : "replace"}`, async (t) => {+ const f = fixture(t, { FIXTURE_FAILURE: "history" });+ if (operation === "prompt") await f.ready();+ else await f.send("initialize", { protocolVersion: 1 });+ editedHistory(f, replacement);+ const response =+ operation === "load"+ ? await f.send("session/load", {+ cwd: f.root,+ mcpServers: [],+ sessionId: "fixture-session",+ })+ : await f.send("session/prompt", {+ sessionId: "fixture-session",+ prompt: [{ type: "text", text: "continue" }],+ });+ assert.ok(response.result, JSON.stringify(response));+ });+ }+}+for (const [replacement, target] of [+ [undefined, "failed"],+ [{ content: 42 }, "failed"],+ [null, "missing"],+ [null, "omit"],+]) {+ test(`invalid context edit refuses native load: ${JSON.stringify([replacement, target])}`, async (t) => {+ const f = fixture(t);+ await f.send("initialize", { protocolVersion: 1 });+ editedHistory(f, replacement === undefined ? {} : replacement, target);+ assert.equal(+ stage(+ await f.send("session/load", { cwd: f.root, mcpServers: [], sessionId: "fixture-session" }),+ ),+ "history",+ );+ assert.deepEqual(f.events(), []);+ });+}diff --git a/crates/daemon/src/delegation/profile/tests.rs b/crates/daemon/src/delegation/profile/tests.rsindex 485ca56f..1efb8fe9 100644--- a/crates/daemon/src/delegation/profile/tests.rs+++ b/crates/daemon/src/delegation/profile/tests.rs@@ -5,6 +5,13 @@ mod qoder;#[cfg(unix)]#[test]fn nested_cli_shebang_resolves_the_selected_node_runtime() {+ // Avoid executing a newly written inode while other test threads fork with+ // its write descriptor inherited (ETXTBSY), without retrying the assertion.+ if crate::test_support::isolated_agent_home(+ "delegation::profile::tests::nested_cli_shebang_resolves_the_selected_node_runtime",+ ) {+ return;+ }use std::os::unix::fs::PermissionsExt;let fixture = private_fixture();let node = fixture.path().join("node");@@ -199,7 +206,7 @@ fn try_request_in_context(WorkerHarnessV1::CodexCli | WorkerHarnessV1::ClaudeCode => {Some(Path::new("/trusted/adapter"))}- WorkerHarnessV1::QoderCli => None,+ WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi => None,},harness_binary,node_binary,diff --git a/crates/daemon/src/delegation/run_authority.rs b/crates/daemon/src/delegation/run_authority.rsindex 58643729..669826c3 100644--- a/crates/daemon/src/delegation/run_authority.rs+++ b/crates/daemon/src/delegation/run_authority.rs@@ -280,6 +280,7 @@ fn build_entry(hiroute_domain::delegation::WorkerHarnessV1::CodexCli => "codex",hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode => "claude",hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "qoder",+ hiroute_domain::delegation::WorkerHarnessV1::Pi => "pi",},task.session.as_ref()diff --git a/crates/daemon/src/test_support.rs b/crates/daemon/src/test_support.rsindex f879adf6..5bc46b39 100644--- a/crates/daemon/src/test_support.rs+++ b/crates/daemon/src/test_support.rs@@ -1,12 +1,19 @@//! Isolate tests that compose production discovery without mutating process-global HOME.pub(crate) fn isolated_agent_home(test_name: &str) -> bool {- isolated_agent_home_inner(test_name, false)+ isolated_agent_home_inner(test_name, false, None)+}+pub(crate) fn isolated_agent_home_with_path(test_name: &str, path: &std::ffi::OsStr) -> bool {+ isolated_agent_home_inner(test_name, false, Some(path))}pub(crate) fn isolated_ignored_agent_home(test_name: &str) -> bool {- isolated_agent_home_inner(test_name, true)+ isolated_agent_home_inner(test_name, true, None)}-fn isolated_agent_home_inner(test_name: &str, ignored: bool) -> bool {+fn isolated_agent_home_inner(+ test_name: &str,+ ignored: bool,+ path: Option<&std::ffi::OsStr>,+) -> bool {const CHILD: &str = "HIROUTE_ISOLATED_DAEMON_TEST";if std::env::var(CHILD).as_deref() == Ok(test_name) {return false;@@ -56,7 +63,10 @@ fn isolated_agent_home_inner(test_name: &str, ignored: bool) -> bool {.env("HOME", &home).env("CODEX_HOME", home.join(".codex")).env("CLAUDE_CONFIG_DIR", &claude_home)- .env("PATH", "/usr/bin:/bin");+ .env(+ "PATH",+ path.unwrap_or(std::ffi::OsStr::new("/usr/bin:/bin")),+ );for name in ["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN",diff --git a/crates/daemon/tests/discovered_model_product.rs b/crates/daemon/tests/discovered_model_product.rsindex ee37e075..e01176db 100644--- a/crates/daemon/tests/discovered_model_product.rs+++ b/crates/daemon/tests/discovered_model_product.rs@@ -190,6 +190,11 @@ fn assert_saved_source(snapshot: &ComputeManagementSnapshotV2, source_id: &str)async fn hirouted_client_core_discovery_save_and_restart_are_closed_and_network_free() {let directory = tempfile::tempdir().unwrap();configure_product_root(directory.path());+ // Unrelated broken native configuration must not block Claude prepare/save/restart.+ let pi_root = directory.path().join("home/.pi/agent");+ std::fs::create_dir_all(&pi_root).unwrap();+ std::fs::write(pi_root.join("models.json"), b"{broken").unwrap();+ std::fs::write(pi_root.join("auth.json"), b"{broken").unwrap();let proxy = TcpListener::bind("127.0.0.1:0").unwrap();proxy.set_nonblocking(true).unwrap();let proxy_address = proxy.local_addr().unwrap();diff --git a/crates/daemon/tests/support/additional_model_fixture.py b/crates/daemon/tests/support/additional_model_fixture.pynew file mode 100644index 00000000..e9206069--- /dev/null+++ b/crates/daemon/tests/support/additional_model_fixture.py@@ -0,0 +1,233 @@+"""Owned native settings and reads for Qoder/Pi persisted-model product journeys.++Only this leaf may write the explicitly selected MODEL context. It never reads+authentication, and it never supplies native provider/settings/credential overrides.+"""+from copy import deepcopy+import json+import os+from pathlib import Path+import secrets+import stat++from agent_product_support import run_native_command+from native_context_fixture import native_text+from qoder_native_context import selected_directory+++CASES = ('agent.models.persisted-routes', 'agent.models.credential-rotation',+ 'agent.models.independent-restore', 'agent.models.default-reference-guard')+LIVE_PROMPT = 'Reply with exactly HIROUTE_LIVE_CHECK_OK. Do not use tools or perform any other action.'+++def select_model_context(product, harness="qoder"):+ product.additional_harness = harness+ if harness == "pi":+ config = Path(product.env["HOME"]) / ".pi/agent"+ config.mkdir(mode=0o700, parents=True)+ product.env["PI_CODING_AGENT_DIR"] = str(config)+ return config+ home = 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), \+ 'model acceptance requires a dedicated context, never the daily HOME/config'+ product.env.update(HOME=str(home), QODER_CONFIG_DIR=str(config))+ return config+++class OwnedModelSettings:+ """Seed a synthetic user baseline; undo only our unchanged final baseline."""+ def __init__(self, config, foreign_endpoint, harness="qoder"):+ self.harness = harness+ self.default_path = Path(config) / "settings.json"+ self.default_original = self.default_path.read_bytes() if harness == "pi" and self.default_path.exists() else None+ self.default_baseline = None+ self.auth_path = Path(config) / "auth.json"+ self.auth_owned = None+ self.path = Path(config) / ('models.json' if harness == 'pi' else 'settings.json')+ assert not self.path.is_symlink(), 'model fixture cannot own a linked settings target'+ self.original = self.path.read_bytes() if self.path.exists() else None+ self.original_mode = stat.S_IMODE(self.path.stat().st_mode) if self.original is not None else None+ self.baseline = json.loads(self.original) if self.original is not None else {}+ assert isinstance(self.baseline, dict), 'dedicated model settings must be a JSON object'+ self.baseline = deepcopy(self.baseline)+ assert not {'hirouteAcceptance', 'hirouteLaterEdit'} & self.baseline.keys(), \+ 'another model fixture owns this context'+ providers = self.baseline.setdefault('providers', {})+ assert isinstance(providers, dict) and 'fixture-native' not in providers+ providers['fixture-native'] = {+ 'type': 'openai-compatible', 'protocol': 'openai-responses', 'authType': 'bearer',+ 'baseUrl': foreign_endpoint, 'apiKey': 'synthetic-unselected-native-key',+ 'models': [{'model': 'native-default', 'contextWindow': 100000,+ 'maxOutputTokens': 4096, 'capabilities': {'tools': True}}],+ 'fixtureUnknownProviderKey': {'preserve': ['native', 'user']},+ }+ self.native_default = 'fixture-native/native-default'+ if harness == 'pi':+ providers['fixture-native'] = {'api':'openai-responses','baseUrl':foreign_endpoint,+ 'apiKey':'synthetic-unselected-native-key','models':[{'id':'native-default','name':'Native default',+ 'reasoning':False,'input':['text'],'cost':{'input':0,'output':0,'cacheRead':0,'cacheWrite':0},+ 'contextWindow':100000,'maxTokens':4096}]}+ self.default_baseline = {'defaultProvider':'fixture-native','defaultModel':'native-default',+ 'retry':{'enabled':False},'compaction':{'enabled':False},'cacheWarming':'off'}+ self.default_path.write_text(json.dumps(self.default_baseline))+ self.default_path.chmod(0o600)+ else:+ self.baseline.setdefault('model', {})['name'] = self.native_default+ self.baseline.setdefault('general', {})['enableAutoUpdate'] = False+ self.baseline.setdefault('hooks', {})+ self.baseline.setdefault('mcpServers', {})+ self.baseline['hirouteAcceptance'] = {'unknown': ['preserve', secrets.token_hex(8)]}+ self.write(self.baseline)++ def install_conflicting_auth(self, provider):+ assert self.harness == "pi" and not self.auth_path.exists()+ self.auth_owned = json.dumps({provider:{"type":"api_key","key":"saved-key-must-not-override-route"}}).encode()+ self.auth_path.write_bytes(self.auth_owned)+ self.auth_path.chmod(0o600)++ def read(self):+ assert not self.path.is_symlink() and self.path.is_file(), 'settings target was replaced'+ return json.loads(self.path.read_text())++ def write(self, value):+ assert not self.path.is_symlink(), 'refusing to write linked fixture settings'+ self.path.write_text(json.dumps(value, indent=2) + '\n')+ self.path.chmod(0o600)++ def assert_preserved(self, provider_id, selected_default=None):+ actual = self.read()+ actual.get('providers', {}).pop(provider_id, None)+ expected = deepcopy(self.baseline)+ if selected_default is not None:+ if self.harness == 'qoder':+ expected['model']['name'] = selected_default+ if self.harness == 'pi':+ default = dict(self.default_baseline)+ if selected_default is not None:+ default['defaultProvider'], default['defaultModel'] = selected_default.split('/',1)+ assert json.loads(self.default_path.read_text()) == default, 'changed separate native defaults'+ assert actual == expected, 'model operation changed native/default/unknown user fields'++ def add_user_edit(self, provider_id):+ self.assert_preserved(provider_id)+ text = self.path.read_text()+ value = {'edited_after_apply': secrets.token_hex(8)}+ # Add one root field without reserializing the managed provider. Otherwise+ # a fixture's unrelated edit could manufacture owned-node formatting drift.+ end = text.rfind('}')+ updated = text[:end].rstrip() + ',\n "hirouteLaterEdit": ' + json.dumps(value) + '\n' + text[end:]+ expected = self.read()+ expected['hirouteLaterEdit'] = value+ assert json.loads(updated) == expected, 'fixture root edit changed another field'+ self.path.write_text(updated)+ self.baseline['hirouteLaterEdit'] = value++ def select_default(self, expected, replacement):+ if self.harness == 'pi':+ actual = json.loads(self.default_path.read_text())+ assert actual['defaultProvider'] + '/' + actual['defaultModel'] == expected+ actual['defaultProvider'], actual['defaultModel'] = replacement.split('/',1)+ self.default_path.write_text(json.dumps(actual))+ return+ actual = self.read()+ assert actual['model']['name'] == expected, 'fixture default changed independently'+ actual['model']['name'] = replacement+ text = self.path.read_text()+ token = json.dumps(expected)+ assert text.count(token) == 1, 'fixture default token is ambiguous'+ updated = text.replace(token, json.dumps(replacement), 1)+ assert json.loads(updated) == actual, 'fixture default edit changed another field'+ self.path.write_text(updated)++ def close(self):+ if self.auth_owned is not None:+ assert self.auth_path.read_bytes() == self.auth_owned+ self.auth_path.unlink()+ assert self.read() == self.baseline, 'cannot undo fixture baseline while managed/drifted fields remain'+ if self.harness == 'pi':+ assert json.loads(self.default_path.read_text()) == self.default_baseline+ if self.default_original is None: self.default_path.unlink()+ else: self.default_path.write_bytes(self.default_original)+ if self.original is None:+ self.path.unlink()+ else:+ self.path.write_bytes(self.original)+ self.path.chmod(self.original_mode)+++class PersistedRouteOracle:+ def __init__(self, model):+ self.model = model+ self.marker = None+ self.receipt = None+ self.calls = []++ def arm(self, label):+ self.marker = 'PERSISTED-INPUT-' + secrets.token_hex(12)+ self.receipt = 'PERSISTED-OUTPUT-' + secrets.token_hex(12)+ self.label = label+ return self.marker++ def reply(self, _fixture, body):+ assert body['model'] == self.model, 'persisted model reached the wrong source'+ text = native_text(body)+ if LIVE_PROMPT in text:+ self.calls.append('live-check')+ return dict(kind='text', text='HIROUTE_LIVE_CHECK_OK', request_kind='live-check')+ assert self.marker is not None and self.marker in text, 'unplanned persisted model request'+ self.calls.append(self.label)+ return dict(kind='text', text=self.receipt, request_kind=self.label)+++def native_command(product, binary, selector, prompt):+ # Ordinary settings precedence remains active. In particular, no --settings,+ # --setting-sources or credential environment can hide a persistence defect.+ if getattr(product, 'additional_harness', 'qoder') == 'pi':+ provider, model = selector.split('/',1)+ return [os.environ['HIROUTE_WORKER_NODE'], str(binary), '--provider', provider, '--model', model,+ '--mode', 'json', '--print', '--no-session', '--no-extensions', '--offline', '--tools', 'read', prompt]+ return [str(binary), '--cwd', str(product.project), '--config-dir', product.env['QODER_CONFIG_DIR'],+ '--model', selector, '--print', '--no-session-persistence', '--output-format', 'stream-json',+ '--tools', 'Read', '--permission-mode', 'dont_ask', '--max-model-request-retries', '0',+ '--max-turns', '2', '-p', prompt]+++def successful_native_result(stdout, receipt, harness='qoder'):+ if harness == 'pi':+ rows = [json.loads(line) for line in stdout.decode().splitlines() if line.startswith('{')]+ headers = [r for r in rows if r.get('type') == 'session']+ endings = [r for r in rows if r.get('type') == 'agent_end']+ assert len(headers) == len(endings) == 1, 'missing ordinary Pi terminal result/session'+ last = endings[0]['messages'][-1]+ assert last['role'] == 'assistant' and last['stopReason'] == 'stop'+ assert ''.join(p.get('text','') for p in last['content']).strip() == receipt+ return headers[0]['id']+ records = []+ for line in stdout.decode().splitlines():+ try:+ value = json.loads(line)+ except ValueError:+ continue+ if isinstance(value, dict) and value.get('type') == 'result':+ records.append(value)+ assert len(records) == 1, 'expected one native Qoder terminal result'+ result = records[0]+ assert result.get('subtype') == 'success' and result.get('is_error') is False, \+ 'native Qoder terminal result is an error'+ assert result.get('result', '').strip() == receipt, 'native result lost the independent source receipt'+ assert isinstance(result.get('session_id'), str) and result['session_id'], 'native result lacks session identity'+ return result['session_id']+++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')+ 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)+ return {'label': label, 'model': source.model, 'native_session_id': native_session_id, 'state': 'green'}diff --git a/crates/daemon/tests/support/additional_model_product.py b/crates/daemon/tests/support/additional_model_product.pynew file mode 100644index 00000000..aedefb1a--- /dev/null+++ b/crates/daemon/tests/support/additional_model_product.py@@ -0,0 +1,329 @@+"""Save additional native models, then read them through ordinary Qoder or Pi.++Uses production Local Control settings, publication and Gateway. Native starts+read only the persisted provider in an explicitly selected native context.+The original four Worker/collaboration journeys remain separate.+"""+import hashlib+import http.client+import json+import os+from pathlib import Path+import secrets+import subprocess+import sys++from model_connections_product import save_native_source+from agent_product_support import apply_settings, settings_status, expose_native_installation+from native_context_boundaries import source_events+from native_context_fixture import NativeContextUpstream, NativeProxyTrap, digest+from native_context_product import report_failure, selected_installation+from publication_process import plan_change+from publication_product import Product, encoded+from collaboration_product import apply_collaboration, check_collaboration as _check_collaboration, restore_skill+from additional_model_fixture import (CASES, OwnedModelSettings, PersistedRouteOracle,+ read_persisted_route, select_model_context)+import qoder_native_context++HARNESS = "qoder"+AGENT = "agent_qoder_default"+MODE = "qoder_additional"+TAIL = "/_hiroute/qoder/v1"++def check_collaboration(product, key):+ return _check_collaboration(product, key, agent=AGENT)+++def model_spec(context, plans=None, restore_ref=None, regenerate=False):+ model = ({'intent': 'restore', 'restore_point_ref': restore_ref} if restore_ref else+ {'intent': 'configure', 'settings': {'mode': MODE, 'allowed_plan_ids': plans}})+ return {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context, 'model': model,+ 'collaboration': {'intent': 'keep'},+ 'access_token': {'intent': 'regenerate' if regenerate else 'keep'}}+++def apply_models(product, spec, key):+ return apply_settings(product, spec, key, 'model')+++def publish_source_plan(product, source, index):+ saved = save_native_source(product, source, token=source.token, upstream_model_id=source.model,+ variant=HARNESS + '-model-' + str(index), context_tokens=100000)+ product.editor = {+ 'schema': 'hiroute.plan-editor/v2', 'display_name': 'Additional ' + HARNESS + ' route ' + str(index),+ 'purpose': 'Read a persisted additional model route', 'mode': 'fixed_model',+ 'candidates': [{'binding_id': saved['binding_id']}],+ 'smart': {'economy': [], 'primary': [], 'primary_fallback': False,+ 'reselect_on_user_message': False, 'classifier': {'kind': 'local_rules'}, 'complex_keywords': []},+ 'free': {'candidates': [], 'primary': [], 'primary_fallback': False},+ 'delegation_enabled': False, 'requirements': {},+ 'limits': {'maximum_attempts': 1, 'request_timeout_ms': 30000, 'attempt_timeout_ms': 30000},+ }+ change = plan_change(product, 'create', HARNESS + '-model-plan-' + str(index))+ preview = product.preview('routing preview', {'change': change})+ product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change': change}, 'model-plan-' + str(index))+ product.plan_id = preview['plan_head']['reference']['plan_id']+ return {'plan_id': product.plan_id, 'alias': preview['plan_head']['model_alias']}+++def assert_configured(status, plans):+ assert status['state'] == 'configured' and status.get('restore_point_ref'), 'model route is not configured'+ assert status['current_selection'] == {'mode': MODE, 'allowed_plan_ids': sorted(plans)}, \+ 'model selection changed the selected Plan set'+++def assert_saved_aliases(settings, provider, aliases):+ models = settings.read()['providers'][provider]['models']+ assert len(models) == len(aliases) and {item['id' if HARNESS == 'pi' else 'model'] for item in models} == set(aliases), \+ 'persisted native choices do not match the selected routes'+++def live_check(product, context, aliases, oracles):+ status = settings_status(product, context)+ targets = [target for target in status.get('live_check_targets', []) if target['surface'] == 'qoder_cli']+ assert len(targets) == 1 and set(targets[0]['client_model_ids']) == set(aliases), 'live scope lost persisted routes'+ check = {'agent_id': AGENT, 'scope': 'live', 'suite': 'quick', 'allow_model_call': True, 'target': targets[0]}+ consent = {'change_digest': 'sha256:' + hashlib.sha256(encoded(check)).hexdigest(),+ 'expected_revisions': product.control('GetClientServiceStatus', {})['data']['revisions']}+ capability = product.grant('CheckAgentConnection', consent, 'qoder-persisted-live')+ before = [len(oracle.calls) for oracle in oracles]+ product.cli('agents check', check, capability)+ status = settings_status(product, context)+ assert status['model_verified'] is True and any(+ row['surface'] == 'qoder_cli' and row['state'] == 'passed'+ and row['applied_revision'] == status['applied_revision'] for row in status['surface_results']), \+ 'real persisted-route Live check did not verify the current publication'+ assert all(oracle.calls[index:] == ['live-check'] for oracle, index in zip(oracles, before)), \+ 'Live verification must actually request each selected persisted route once'+++def reject_gateway_request(product, token, alias, sources, expected_statuses):+ before = [source.request_count() for source in sources]+ client = http.client.HTTPConnection('127.0.0.1', product.port, timeout=10)+ try:+ client.request('POST', TAIL + '/responses', body=encoded({+ 'model': alias, 'input': 'Untrusted removed route', 'max_output_tokens': 16, 'stream': True}),+ headers={'Content-Type': 'application/json', **({'X-HiRoute-Token':token} if HARNESS == 'pi'+ else {'Authorization':'Bearer ' + token})})+ response = client.getresponse()+ response.read()+ assert response.status in expected_statuses, f'obsolete authority or removed alias rejection: {response.status}'+ finally:+ client.close()+ assert [source.request_count() for source in sources] == before, 'rejected request reached a source'+++def assert_default_blocks_removal(product, context, settings, provider, plans, skill):+ selected = provider + '/' + plans[0]['alias']+ settings.select_default(settings.native_default, selected)+ try:+ status = settings_status(product, context)+ before, skill_before = digest(settings.path), digest(skill)+ original_token = product.bearer(product.agent_connection)+ for spec in (model_spec(context, [plans[1]['plan_id']]),+ model_spec(context, restore_ref=status['restore_point_ref'])):+ command = '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']), \+ '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'+ assert product.bearer(product.agent_connection) == original_token, 'blocked removal changed the model token'+ # Keeping the default-selected alias remains a legal user adjustment.+ preview = product.preview('agents connect preview', {'spec': model_spec(context, [p['plan_id'] for p in plans])})+ assert preview['applicable'], 'retaining the selected default was incorrectly rejected'+ settings.assert_preserved(provider, selected_default=selected)+ finally:+ settings.select_default(selected, settings.native_default)+++def restore_models(product, context):+ current = settings_status(product, context)+ _, restored = apply_models(product, model_spec(context, restore_ref=current['restore_point_ref']),+ 'qoder-model-restore')+ assert restored['state'] == 'not_configured' and restored.get('current_selection') is None \+ and restored.get('restore_point_ref') is None, 'model Restore did not release its selection/reference'+++def run(repository, candidate):+ global HARNESS, AGENT, MODE, TAIL+ HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS', 'qoder')+ assert HARNESS in ('qoder', 'pi')+ AGENT = 'agent_' + HARNESS + '_default'+ MODE = HARNESS + '_additional'+ TAIL = '/v1' if HARNESS == 'pi' else '/_hiroute/qoder/v1'+ repo = Path(repository).resolve()+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate+ product = Product(repo)+ sources, oracles, settings, context, skill = [], [], None, None, None+ foreign = None+ model_active = skill_active = False+ before_skill = None+ stage = 'dedicated-model-context'+ report = dict(scenario=HARNESS + '-persisted-model-routes', candidate=candidate, worker_harness=HARNESS,+ required_cases=list(CASES), selected_cases=list(CASES), cases=[], native_reads=[],+ evidence_limit=f'Real persisted settings/native {HARNESS}/Gateway; controlled sources; no Desktop verdict')+ failed = False+ cleanup_errors = []+ try:+ config = select_model_context(product, HARNESS)+ binary, _, node = selected_installation(HARNESS)+ expose_native_installation(product, HARNESS, binary, node)+ foreign = NativeProxyTrap(product.root / 'unselected-native.log')+ settings = OwnedModelSettings(config, foreign.url + '/v1', HARNESS)+ product.enable_debug_diagnostics()+ product.start()+ plans = []+ for index, model in enumerate(('gpt-5.4', 'gpt-5.5')):+ controls = product.root / ('persisted-source-' + str(index))+ controls.mkdir(mode=0o700)+ (controls / 'native-context.json').write_text('{}')+ source = NativeContextUpstream(controls)+ source.model, source.token = model, 'synthetic-persisted-source-' + secrets.token_hex(12)+ oracle = PersistedRouteOracle(model)+ source.reply = oracle.reply+ sources.append(source)+ oracles.append(oracle)+ plans.append(publish_source_plan(product, source, index))+ agent = next(item for item in product.preview('agents scan')['agents'] if item['agent_id'] == AGENT)+ context = agent['context_id']+ product.agent_connection = 'agent-connection/' + context+ stage = 'persist-model-routes'+ plan_ids = [plan['plan_id'] for plan in plans]+ preview, status = apply_models(product, model_spec(context, plan_ids), 'qoder-model-enable')+ model_active = True+ product.bearer(product.agent_connection) # Register the actual secret for output-leak checks immediately.+ provider = preview['model_effect']['provider_id']+ assert preview['model_effect']['endpoint'] == 'http://127.0.0.1:' + str(product.port) + TAIL+ assert_configured(status, plan_ids)+ assert_saved_aliases(settings, provider, [plan['alias'] for plan in plans])+ settings.assert_preserved(provider)+ settings.add_user_edit(provider)+ if HARNESS == 'pi':+ settings.install_conflicting_auth(provider)+ for index, plan in enumerate(plans):+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plan['alias'],+ sources[index], oracles[index], 'persisted-' + str(index)))+ product.stop()+ product.start()+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],+ sources[0], oracles[0], 'after-daemon-restart'))+ if HARNESS == 'qoder':+ live_check(product, context, [plan['alias'] for plan in plans], oracles)+ report['cases'].append({'id': CASES[0], 'state': 'green'})++ stage = 'rotate-only-model-authority'+ old_token = product.bearer(product.agent_connection)+ _, status = apply_models(product, model_spec(context, plan_ids, regenerate=True), 'qoder-model-rotate')+ assert_configured(status, plan_ids)+ new_token = product.bearer(product.agent_connection)+ assert old_token != new_token, 'model token rotation reused the prior credential'+ reject_gateway_request(product, old_token, plans[0]['alias'], sources, (401, 403))+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[1]['alias'],+ sources[1], oracles[1], 'after-token-rotation'))+ settings.assert_preserved(provider)+ report['cases'].append({'id': CASES[1], 'state': 'green'})++ stage = 'independent-model-and-skill'+ (config / 'skills').mkdir(mode=0o700, exist_ok=True)+ skill = (config / 'skills/hiroute-collaboration/SKILL.md' if HARNESS == 'pi' else+ qoder_native_context.prepare_collaboration_target(product))+ before_skill = skill.read_bytes() if skill.exists() else None+ check_collaboration(product, 'model-skill-preflight')+ collaboration = apply_collaboration(product, context,+ {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'model-skill-enable')+ skill_active = True+ check_collaboration(product, 'model-skill-installed')+ restore_skill(product, context, collaboration['restore_point_ref'], before_skill, skill)+ skill_active = False+ assert_configured(settings_status(product, context), plan_ids)+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],+ sources[0], oracles[0], 'after-skill-restore'))+ # Restore invalidates evidence about the formerly installed Skill. A new+ # configuration must prove the current capability rather than reuse it.+ check_collaboration(product, 'model-skill-reenable-preflight')+ collaboration = apply_collaboration(product, context,+ {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'model-skill-enable-again')+ skill_active = True+ skill_digest = digest(skill)+ assert_default_blocks_removal(product, context, settings, provider, plans, skill)+ report['cases'].append({'id': CASES[3], 'state': 'green'})+ _, status = apply_models(product, model_spec(context, [plan_ids[0]]), 'qoder-model-adjust')+ assert_configured(status, [plan_ids[0]])+ assert_saved_aliases(settings, provider, [plans[0]['alias']])+ reject_gateway_request(product, product.bearer(product.agent_connection), plans[1]['alias'], sources, (403, 404))+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],+ sources[0], oracles[0], 'after-route-adjustment'))+ restore_models(product, context)+ model_active = False+ assert settings.read() == settings.baseline, 'model Restore did not preserve unrelated user edits'+ assert digest(skill) == skill_digest, 'model Restore changed the independent Skill'+ remaining = settings_status(product, context)['collaboration']+ assert remaining['state'] == 'configured' and remaining['restore_point_ref'] == collaboration['restore_point_ref']+ check_collaboration(product, 'skill-survives-model-restore')+ report['cases'].append({'id': CASES[2], 'state': 'green'})+ restore_skill(product, context, remaining['restore_point_ref'], before_skill, skill)+ skill_active = False+ assert not foreign.path.read_text().strip(), 'native defaults or providers unexpectedly received requests'+ assert all(event['state'] == 'green' for source in sources for event in source_events(source))+ assert all(source.request_count() == len(source_events(source)) for source in sources), \+ 'an unrecorded rejected request reached the source'+ diagnostics = product.diagnostics_snapshot()+ assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'+ report.update(state='green', diagnostics=diagnostics, persisted_aliases=[p['alias'] for p in plans],+ native_default_preserved=True, unknown_user_fields_preserved=True, foreign_requests=0,+ source_requests=[source.request_count() for source in sources], live_requests=2 if HARNESS == 'qoder' else 0,+ source_context_tokens=100000, source_output_tokens=4096,+ binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},+ harness_sha256=digest(binary))+ except Exception:+ failed = True+ raise+ finally:+ # Restore through production while its daemon is alive. A failed operation+ # never authorizes deleting a managed provider or installed Skill directly.+ for label, active, action in (+ ('restore_model', model_active, lambda: restore_models(product, context)),+ ('restore_skill', skill_active, lambda: restore_skill(product, context,+ settings_status(product, context)['collaboration']['restore_point_ref'], before_skill, skill)),+ ):+ if active:+ try:+ if product.process is None:+ product.start()+ action()+ except Exception as error:+ cleanup_errors.append({'step': label, 'error_type': type(error).__name__})+ if failed or cleanup_errors:+ report['cleanup_failures'] = list(cleanup_errors)+ try:+ report_failure(product, report, stage)+ except Exception as error:+ cleanup_errors.append({'step': 'preserve_failure_report', 'error_type': type(error).__name__})+ actions = []+ if settings is not None:+ actions.append(('owned_settings_baseline', settings.close))+ # Pi owns its fixture HOME under Product's temporary root; release native+ # leaves before Product.close deletes that root. External Qoder roots+ # follow the same ownership order.+ actions.extend([('owned_skill_directory', lambda: qoder_native_context.cleanup_context(product)),+ ('close_product', product.close)])+ actions.extend(('close_source', source.close) for source in sources)+ if foreign is not None:+ actions.append(('close_foreign', foreign.close))+ for label, action in actions:+ try:+ action()+ except Exception as error:+ cleanup_errors.append({'step': label, 'error_type': type(error).__name__})+ if cleanup_errors:+ print(json.dumps({'scenario': 'qoder-model-cleanup', 'state': 'red', 'candidate': candidate,+ 'primary_failure_preserved': failed, 'failures': cleanup_errors}), flush=True)+ if not failed:+ raise AssertionError('model acceptance cleanup failed')+ print(json.dumps(report), flush=True)+++if __name__ == '__main__':+ run(sys.argv[1], sys.argv[2])diff --git a/crates/daemon/tests/support/agent_product_support.py b/crates/daemon/tests/support/agent_product_support.pyindex 2bb004db..e79d4e02 100644--- a/crates/daemon/tests/support/agent_product_support.py+++ b/crates/daemon/tests/support/agent_product_support.py@@ -2,6 +2,18 @@import osimport signalimport subprocess+from pathlib import Path+++def 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 != 'pi' or node is not None, 'Pi fixture requires its selected Node'+ entries = [('pi' if harness == 'pi' else 'qodercli', binary)]+ if harness == 'pi':+ entries.append(('node', node))+ for name, path in entries:+ (product.root / 'bin' / name).symlink_to(Path(path).resolve(strict=True))def settings_status(product, context):diff --git a/crates/daemon/tests/support/collaboration_fixture.py b/crates/daemon/tests/support/collaboration_fixture.pynew file mode 100644index 00000000..f3461908--- /dev/null+++ b/crates/daemon/tests/support/collaboration_fixture.py@@ -0,0 +1,178 @@+"""Two independent model-role oracles for real Qoder Skill → public CLI → Worker.++Only native tool results and the Worker's disk artifact can complete this journey.+This module does not start HiRoute, impersonate an Agent, or write its installed Skill.+"""+import json+from pathlib import Path+import shlex++from native_context_fixture import decision, qoder_skill_expansions, tool_results+++CASES = ('agent.collaboration.user-skill', 'agent.collaboration.public-worker-delegation',+ 'agent.collaboration.disable-owned-skill')+++def successful_envelope(output):+ """Qoder Bash may surround stdout with native timing/status text."""+ assert isinstance(output, str), 'expected a native Bash text result'+ decoder = json.JSONDecoder()+ matches = []+ for index, char in enumerate(output):+ if char != '{':+ continue+ try:+ value, _ = decoder.raw_decode(output[index:])+ except ValueError:+ continue+ if isinstance(value, dict) and 'schema_version' in value and 'status' in value:+ matches.append(value)+ assert len(matches) == 1 and matches[0]['status'] == 'succeeded', \+ 'expected one successful public CLI envelope in the correlated tool result'+ return matches[0]+++def output_envelope(output):+ return successful_envelope(output)['data']+++def worker_decision(fixture, body):+ results = tool_results(body, fixture.get('harness', 'qoder'))+ artifact = fixture['artifact']+ if 'delegated_artifact' in results:+ assert artifact['receipt'] in results['delegated_artifact'], 'Worker tool did not return artifact receipt'+ path = Path(artifact['path'])+ assert path.is_file() and not path.is_symlink() and path.read_text().strip() == artifact['receipt'], \+ 'Worker did not produce the independent disk artifact'+ return dict(kind='text', text=artifact['receipt'], continued=False)+ action = decision(fixture, body)+ if action['kind'] != 'text':+ return action+ command = ('/usr/bin/printf "%s\\n" ' + shlex.quote(artifact['receipt']) + ' > ' ++ shlex.quote(artifact['path']) + ' && /bin/cat ' + shlex.quote(artifact['path']))+ 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})+++class MainAgentOracle:+ def __init__(self, fixture, skill, cli, worker_events):+ self.fixture = fixture+ self.skill = Path(skill)+ self.skill_body = self.skill.read_text().split('---', 2)[-1].strip()+ assert self.skill_body and 'hiroute worker plans' in self.skill_body+ self.cli = str(Path(cli).resolve(strict=True))+ self.worker_events = worker_events+ self.accepted = None+ self.user_skill_proved = False+ self.completed = False+ self.requests = 0++ def reply(self, _unused, body):+ self.requests += 1+ assert self.requests <= 32, 'main Agent exceeded the bounded public observation budget'+ rendered = json.dumps(body)+ 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':+ 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'+ else:+ assert {'Skill', 'Bash'} <= names, 'native main Agent 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={'skill': 'hiroute-collaboration'})+ # Native Qoder returns a correlated launch receipt, then expands the body+ # into a user message. Exact directory excludes a same-named project/plugin.+ contents = qoder_skill_expansions(body, self.skill.parent)+ assert any(text.strip() == self.skill_body for text in contents), \+ 'actual installed user Skill directory and body were not loaded'+ self.user_skill_proved = True+ if 'main_plans' not in results:+ 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', \+ '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']) + \+ ' to complete the delegated native receipt task.'+ command = ('/usr/bin/printf %s ' + shlex.quote(prompt) + ' | ' + shlex.quote(self.cli) ++ ' worker exec --plan ' + shlex.quote(plans[0]['agent_plan_id']) + ' --cwd ' ++ shlex.quote(self.fixture['project']) + ' --run-timeout 120 --wait-timeout 120' ++ ' --submission-key qoder-main-agent-delegation --file - --output json')+ return self.bash('main_exec', command, 150000)+ envelope = successful_envelope(results['main_exec'])+ accepted = envelope['data']+ # Retain the actual public result even on failure for scoped diagnosis;+ # completion still requires success and the independent disk artifact.+ self.accepted = accepted+ assert accepted.get('task_id') and accepted.get('run_id'), 'public Worker acceptance has no identity'+ wait_index = 1+ while 'main_wait_' + str(wait_index) in results:+ envelope = successful_envelope(results['main_wait_' + str(wait_index)])+ self.assert_same_worker(envelope['data'], accepted)+ wait_index += 1+ current = envelope['data']+ self.accepted = current+ if current['run_state'] not in ('succeeded', 'failed', 'cancelled', 'unknown'):+ actions = [action['input'] for action in envelope.get('next_actions', [])+ if action.get('command_id') == 'worker.wait'+ and action.get('input', {}).get('run_id') == accepted['run_id']]+ assert (len(actions) == 1 and type(actions[0].get('after_revision')) is int+ and actions[0]['after_revision'] >= 0), \+ 'active public Worker result must provide its exact wait cursor'+ command = (shlex.quote(self.cli) + ' worker wait --run ' + shlex.quote(accepted['run_id']) ++ ' --after-revision ' + str(actions[0]['after_revision']) ++ ' --wait-timeout 20 --output json')+ return self.bash('main_wait_' + str(wait_index), command, 25000)+ assert current['run_state'] == 'succeeded', 'main Agent did not observe successful public Worker execution'+ if 'result' not in current:+ if 'main_result' not in results:+ return self.bash('main_result', shlex.quote(self.cli) + ' worker result --run ' ++ shlex.quote(accepted['run_id']) + ' --output json')+ current = output_envelope(results['main_result'])+ self.assert_same_worker(current, accepted)+ assert current['run_state'] == 'succeeded', 'public Worker result is not successful'+ receipt = self.fixture['artifact']['receipt']+ assert receipt in current.get('result', ''), 'public Worker result lost its tool artifact'+ assert Path(self.fixture['artifact']['path']).read_text().strip() == receipt, 'disk artifact missing'+ attempts = self.worker_events()+ assert attempts and all(event['state'] == 'green' for event in attempts), 'Worker source is incomplete'+ assert any(event.get('call_id') == 'delegated_artifact' for event in attempts), \+ 'no real Worker tool request produced the artifact'+ self.accepted, self.completed = current, True+ return dict(kind='text', text='MAIN-AGENT-COMPLETED-' + receipt, continued=False)++ @staticmethod+ def assert_same_worker(current, accepted):+ assert all(current.get(key) == accepted[key] for key in ('task_id', 'run_id')), \+ 'public observation switched the accepted Worker identity'++ def bash(self, call_id, command, timeout=10000):+ 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})+++def main_route_settings(endpoint, alias, credential_env):+ """Independent native-main fixture settings; Worker uses the production renderer."""+ provider = 'hiroute-main-acceptance'+ selected = provider + '/' + alias+ own_alias = {'modelConfig': {'model': selected}}+ return selected, {+ 'general': {'enableAutoUpdate': False, 'sessionRetention': {'enabled': False},+ 'plan': {'modelRouting': False}},+ 'disableAllHooks': True, 'promptSuggestionEnabled': False, 'model': {'name': selected},+ 'modelConfigs': {'aliases': {selected: own_alias}, 'customAliases': {selected: own_alias},+ 'overrides': [], 'customOverrides': []},+ 'providers': {provider: {'protocol': 'openai-responses', 'baseUrl': endpoint,+ 'apiKey': '${' + credential_env + '}', 'model': alias,+ 'models': [{'model': alias, 'contextWindow': 100000, 'capabilities': {'tools': True}}],+ 'routing': {purpose: alias for purpose in ('utility', 'session_title', 'summary', 'compact', 'subagent')}}},+ }diff --git a/crates/daemon/tests/support/collaboration_product.py b/crates/daemon/tests/support/collaboration_product.pynew file mode 100644index 00000000..4d44b4a8--- /dev/null+++ b/crates/daemon/tests/support/collaboration_product.py@@ -0,0 +1,249 @@+"""Real main Agent → installed user Skill → public CLI → real Qoder or Pi Worker.++Uses the same Product, managed candidate and native context as the Worker journeys.+Only model upstreams are deterministic. No daily provider/auth settings are edited.+"""+import hashlib+import json+import os+from pathlib import Path+import secrets+import subprocess+import sys++from agent_product_support import apply_settings, run_native_command, expose_native_installation+from delegation_product import configure_worker_installation+from native_context_boundaries import source_events+from native_context_fixture import NativeContextUpstream, assert_preserved, digest, write_new+from native_context_product import prepare_product, report_failure, selected_installation, wait_for_resumable_task+from publication_product import Product, encoded+from collaboration_fixture import CASES, MainAgentOracle, main_route_settings, worker_decision+import qoder_native_context+++HARNESS = 'qoder'+AGENT = 'agent_qoder_default'+++def check_collaboration(product, key, agent=None):+ agent = AGENT if agent is None else agent+ check = {'agent_id': agent, 'scope': 'collaboration', 'suite': 'quick', 'allow_model_call': False}+ consent = {'change_digest': 'sha256:' + hashlib.sha256(encoded(check)).hexdigest(),+ 'expected_revisions': product.control('GetClientServiceStatus', {})['data']['revisions']}+ capability = product.grant('CheckAgentConnection', consent, key)+ _, checked = product.cli('agents check ' + agent + ' --scope collaboration', capability=capability)+ assert checked['data']['skill_loading'] == 'proven' and checked['data']['trusted_cli_execution'] == 'proven', \+ 'native collaboration capability check did not complete'+++def apply_collaboration(product, context, intent, key):+ spec = {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context, 'collaboration': intent}+ _, status = apply_settings(product, spec, key, 'collaboration')+ return status['collaboration']+++def run_main_agent(product, binary, upstream, fixture):+ if HARNESS == 'pi':+ config = Path(fixture['config'])+ models = json.loads((config / 'models.json').read_text())+ models['providers']['hiroute-main-acceptance'] = {'api':'openai-responses',+ 'baseUrl':upstream.base_url,'apiKey':upstream.token,+ 'models':[{'id':upstream.model,'name':'Main acceptance','reasoning':False,'input':['text'],+ 'cost':{'input':0,'output':0,'cacheRead':0,'cacheWrite':0},'contextWindow':100000,'maxTokens':2048}]}+ (config / 'models.json').write_text(json.dumps(models))+ from native_context_fixture import protect_configuration+ protect_configuration(fixture, [config / 'models.json'])+ args = [os.environ['HIROUTE_WORKER_NODE'],str(binary),'--provider','hiroute-main-acceptance',+ '--model',upstream.model,'--print','--mode','json','--no-session','--no-extensions','--offline',+ '--tools','read,bash',fixture['main_marker'] + ': Read hiroute-collaboration and delegate the native receipt task.']+ stdout = run_native_command(product,args,timeout=190,label='native Pi main Agent')+ assert ('MAIN-AGENT-COMPLETED-' + fixture['artifact']['receipt']).encode() in stdout+ return+ native_id, overlay = main_route_settings(upstream.base_url, upstream.model, 'HIROUTE_QODER_MAIN_TOKEN')+ settings = product.root / 'qoder-main-settings.json'+ write_new(settings, json.dumps(overlay))+ temporary = product.root / 'qoder-main-tmp'+ temporary.mkdir(mode=0o700)+ args = [str(binary), '--cwd', str(product.project), '--config-dir', fixture['config'],+ '--setting-sources', 'user', '--settings', str(settings), '--model', native_id,+ '--print', '--no-session-persistence', '--output-format', 'stream-json',+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--tools', 'Skill,Read,Bash',+ '--allowed-tools', 'Skill,Bash', '--permission-mode', 'dont_ask',+ '--max-model-request-retries', '0', '--max-output-tokens', '2048', '--max-turns', '32',+ '-p', fixture['main_marker'] + ': Use hiroute-collaboration and explicitly delegate the native receipt task.']+ env = dict(product.env, HIROUTE_QODER_MAIN_TOKEN=upstream.token, TMPDIR=str(temporary))+ stdout = run_native_command(product, args, env=env, timeout=190, label='native main Agent')+ assert ('MAIN-AGENT-COMPLETED-' + fixture['artifact']['receipt']).encode() in stdout, \+ 'native main Agent did not return the independently verified completion'+++def restore_skill(product, context, restore_ref, before, skill):+ # A journey can configure/restore more than once. Each restoration point+ # represents a distinct operation; do not reuse one global idempotency key.+ key = 'qoder-collaboration-disable-' + hashlib.sha256(encoded(restore_ref)).hexdigest()[:16]+ status = apply_collaboration(product, context, {'intent': 'restore', 'restore_point_ref': restore_ref},+ key)+ assert (status['state'] == 'restored' and status.get('current_selection') is None+ and status.get('restore_point_ref') is None), \+ 'collaboration disable did not restore and release its current selection/reference'+ if before is None:+ assert not skill.exists(), 'product left its owned collaboration Skill installed'+ else:+ assert skill.read_bytes() == before, 'product removed or rewrote a borrowed user Skill'+++def finish_collaboration(product, sources, restore, report, stage, primary_failure):+ """Restore before stopping the service; preserve the first business failure."""+ errors = []+ if restore is not None:+ try:+ if product.process is None:+ product.start()+ restore()+ report['restore_after_failure'] = {'state': 'succeeded'}+ except Exception as error:+ errors.append({'step': 'restore_collaboration', 'error_type': type(error).__name__})+ report['restore_after_failure'] = {'state': 'red'}+ if primary_failure or errors:+ report['cleanup_failures'] = list(errors)+ try:+ report_failure(product, report, stage)+ except Exception as error:+ errors.append({'step': 'preserve_failure_report', 'error_type': type(error).__name__})+ # Try every independently owned cleanup even when another fails. Never remove+ # user material directly to compensate for a failed product Restore.+ actions = [('close_product', product.close),+ ('cleanup_owned_receipts', lambda: qoder_native_context.cleanup_context(product))]+ actions.extend(('close_source', source.close) for source in sources)+ for step, action in actions:+ try:+ action()+ except Exception as error:+ errors.append({'step': step, 'error_type': type(error).__name__})+ if errors:+ print(json.dumps({'scenario': 'qoder-collaboration-cleanup', 'state': 'red',+ 'candidate': report['candidate'], 'failures': errors,+ 'primary_failure_preserved': primary_failure}), flush=True)+ if not primary_failure:+ raise AssertionError('Qoder collaboration cleanup failed; inspect the cleanup report')+++def run(repository, candidate):+ global HARNESS, AGENT+ HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','qoder')+ assert HARNESS in ('qoder','pi')+ AGENT = 'agent_' + HARNESS + '_default'+ repo = Path(repository).resolve()+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate+ product = Product(repo)+ sources = []+ fixture = None+ context = restore_ref = None+ restored = False+ skill = None+ before_skill = None+ primary_failure = False+ oracle = None+ stage = 'explicit-native-context'+ report = dict(scenario=HARNESS + '-main-agent-delegation', candidate=candidate, worker_harness=HARNESS,+ required_cases=list(CASES), selected_cases=list(CASES), cases=[],+ evidence_limit='Real main Agent, user Skill, public CLI, daemon, Gateway and Worker; synthetic models; no Desktop verdict')+ try:+ binary, _, node = selected_installation(HARNESS)+ expose_native_installation(product, HARNESS, binary, node)+ if HARNESS == 'pi':+ product.env['PI_CODING_AGENT_DIR'] = str(Path(product.env['HOME']) / 'selected-pi-config')+ 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)+ 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.+ auth = Path(fixture['config']) / 'auth.json'+ auth.write_text('{}')+ from native_context_fixture import protect_configuration+ protect_configuration(fixture, [auth])+ fixture['main_marker'] = 'QODER-MAIN-' + secrets.token_hex(12)+ fixture['artifact'] = dict(path=str(product.project / 'delegated-native-artifact.txt'),+ 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+ qoder_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+ stage = 'native-collaboration-preflight'+ check_collaboration(product, 'qoder-preflight')+ scan = product.preview('agents scan')+ agents = [agent for agent in scan['agents'] if agent['agent_id'] == AGENT]+ assert len(agents) == 1, HARNESS + ' installation/context was not discovered'+ context = agents[0]['context_id']+ stage = 'install-real-user-collaboration-skill'+ status = apply_collaboration(product, context,+ {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'qoder-collaboration-enable')+ assert status['state'] == 'configured' and status['current_selection']['trigger_mode'] == 'explicit', status+ restore_ref = status['restore_point_ref']+ assert restore_ref and skill.is_file(), 'configured collaboration has no owned restore reference/Skill'+ assert not (product.project / '.qoder/skills/hiroute-collaboration').exists(), 'project Skill shadows user target'+ stage = 'verify-installed-user-skill'+ check_collaboration(product, 'qoder-installed-user-skill')+ if HARNESS == 'qoder':+ qoder_native_context.assert_settings_preserved(fixture)+ controls = product.root / 'main-agent-source'+ controls.mkdir(mode=0o700)+ (controls / 'native-context.json').write_text('{}')+ main_source = NativeContextUpstream(controls)+ sources.append(main_source)+ main_source.token, main_source.model = 'synthetic-main-agent-only-token', 'main-agent/receipt:v1'+ oracle = MainAgentOracle(fixture, skill, product.bin / 'hiroute', lambda: source_events(worker_source))+ main_source.reply = oracle.reply+ stage = 'real-main-agent-to-worker'+ run_main_agent(product, binary, main_source, fixture)+ assert oracle.user_skill_proved and oracle.completed, 'main Agent oracle did not complete all stages'+ assert all(event['state'] == 'green' for source in sources for event in source_events(source))+ fixture['task_id'] = oracle.accepted['task_id']+ 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)),+ 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,+ native_context_setup=fixture.get('native_context_setup', 'fresh-synthetic-context'))+ report['cases'].extend({'id': case, 'state': 'green'} for case in CASES[:2])+ assert_preserved(fixture)+ stage = 'disable-only-owned-collaboration-skill'+ restore_skill(product, context, restore_ref, before_skill, skill)+ restored = True+ if HARNESS == 'qoder':+ qoder_native_context.assert_settings_preserved(fixture)+ report['cases'].append({'id': CASES[2], 'state': 'green'})+ product.stop()+ diagnostics = product.diagnostics_snapshot()+ assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'+ report.update(state='green', user_settings_unchanged=True, diagnostics=diagnostics,+ binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},+ harness_sha256=digest(binary))+ except Exception:+ primary_failure = True+ if oracle is not None:+ report['main_observations'] = {+ 'actual_user_skill_proved': oracle.user_skill_proved,+ 'requests': oracle.requests,+ 'completed': oracle.completed,+ 'public_worker_result': ({key: oracle.accepted.get(key)+ for key in ('task_id', 'run_id', 'run_state')}+ if oracle.accepted is not None else None),+ }+ raise+ finally:+ restore = None+ if restore_ref and not restored:+ restore = lambda: restore_skill(product, context, restore_ref, before_skill, skill)+ finish_collaboration(product, sources, restore, report, stage, primary_failure)+ print(json.dumps(report), flush=True)+++if __name__ == '__main__':+ run(sys.argv[1], sys.argv[2])diff --git a/crates/daemon/tests/support/discovered_model_product_support.rs b/crates/daemon/tests/support/discovered_model_product_support.rsindex ce8c7c72..8525eca7 100644--- a/crates/daemon/tests/support/discovered_model_product_support.rs+++ b/crates/daemon/tests/support/discovered_model_product_support.rs@@ -99,6 +99,7 @@ impl ProductDaemon {]).current_dir(root.join("workspace")).env("HOME", root.join("home"))+ .env("PI_CODING_AGENT_DIR", root.join("home/.pi/agent")).env("PATH", root.join("bin")).env("HTTP_PROXY", format!("http://{proxy}")).env("HTTPS_PROXY", format!("http://{proxy}"))diff --git a/crates/daemon/tests/support/model_connections_product.py b/crates/daemon/tests/support/model_connections_product.pyindex c5c94ba4..4b50e6d7 100644--- a/crates/daemon/tests/support/model_connections_product.py+++ b/crates/daemon/tests/support/model_connections_product.py@@ -232,12 +232,17 @@ def save_native_source(product, upstream, token=None, unknown=False,if model['upstream_model_id'] == upstream_model_id)assert manual['selectable'] and manual['membership'] == 'user_declared', manual+ return save_compute_candidate(product, checked['candidate'], manual['model_ref'], 'native-product-save' + suffix)+++def save_compute_candidate(product, candidate, model_ref, idempotency_key):+ """Complete the public preview/save/result transaction for a prepared native candidate."""snapshot = control(product, 'ListCompute', {})['data']change = {'schema': 'hiroute.compute-management-change/v2',- 'subject': {'kind': 'candidate', 'candidate': checked['candidate']['candidate']},+ 'subject': {'kind': 'candidate', 'candidate': candidate['candidate']},'expected_revisions': snapshot['revisions'],- 'selected_model_refs': [manual['model_ref']],+ 'selected_model_refs': [model_ref],'intent': 'save_ready','key_edits': [],}@@ -246,7 +251,7 @@ def save_native_source(product, upstream, token=None, unknown=False,'spec': preview['spec'],'accept_digest': preview['accept_digest'],'expected_revisions': preview['expected_revisions'],- 'idempotency_key': 'native-product-save' + suffix,+ 'idempotency_key': idempotency_key,})assert applied['data']['state'] == 'succeeded', appliedsaved = control(product, 'GetComputeSaveResult', {diff --git a/crates/daemon/tests/support/native_compaction_product.py b/crates/daemon/tests/support/native_compaction_product.pynew file mode 100644index 00000000..fa1fbaca--- /dev/null+++ b/crates/daemon/tests/support/native_compaction_product.py@@ -0,0 +1,221 @@+"""Automatic native compaction stays on the real Worker's frozen Gateway route.++The synthetic usage receipt triggers Qoder's own compactor inside one public+Worker execution. This is separate from the no-probe Continue/Skill journey.+"""+import json+import os+from pathlib import Path+import secrets+import shlex+import subprocess+import sys++from delegation_product import configure_worker_installation, wait_for_worker_result, worker_cli+from native_context_boundaries import source_events+from native_context_fixture import (assert_preserved, digest, is_native_compaction, native_text,+ protect_configuration, tool_results, write_new)+from native_context_product import (exact_history, prepare_product, report_failure,+ selected_installation, wait_for_resumable_task)+from publication_product import Product+import qoder_native_context+++CASES = ('worker.context.tool-summary-route', 'worker.context.compaction-route')+CONTEXT_TOKENS = 100_000+PRESSURE_TOKENS = 90_000+PI_PRESSURE_TOKENS = 31_000+++class CompactionOracle:+ def __init__(self, fixture, upstream_model):+ self.fixture, self.model = fixture, upstream_model+ self.main_requests = self.compact_requests = self.tool_summary_requests = 0+ self.tool_receipt = 'NATIVE-TOOL-' + secrets.token_hex(12)+ self.summary_receipt = 'NATIVE-COMPACT-' + secrets.token_hex(12)+ self.tool_summary_receipt = 'NATIVE-TOOL-SUMMARY-' + secrets.token_hex(12)++ def reply(self, _fixture, body):+ assert body.get('model') == self.model, 'compaction or main request changed the frozen upstream model'+ results = tool_results(body, 'qoder')+ items = body.get('input', [])+ last = native_text(items[-1]) if isinstance(items, list) and items else native_text(items)+ if 'tool output' in last.lower() and 'summar' in last.lower() and self.tool_receipt in last:+ assert self.main_requests == 1 and self.tool_summary_requests == 0, 'unexpected native tool summarization'+ self.tool_summary_requests += 1+ return dict(kind='text', request_kind='tool_summary', input_tokens=30,+ text=self.tool_summary_receipt + ': The read-only tool returned ' + self.tool_receipt)+ if is_native_compaction(body):+ assert self.main_requests == 1 and self.compact_requests == 0, 'unexpected or repeated native compaction'+ assert self.tool_summary_requests == 1 and self.tool_summary_receipt in results.get('native_compaction_tool', ''), \+ 'native compaction omitted the correlated summarized tool receipt'+ assert self.summary_receipt not in native_text(body), 'summary receipt was present before compaction'+ self.compact_requests += 1+ return dict(kind='text', request_kind='compact', input_tokens=30,+ text='<analysis>Local routing acceptance only.</analysis><summary>' ++ self.summary_receipt + ': The read-only tool returned ' + self.tool_summary_receipt ++ '. Finish the requested native routing receipt.</summary>')+ self.main_requests += 1+ assert self.main_requests <= 3, 'unexpected native main request'+ if self.main_requests == 1:+ assert self.fixture['compaction_prompt'] in native_text(body), 'unknown native task'+ return dict(kind='tool', request_kind='main', id='native_compaction_tool', name='Bash',+ arguments={'command': '/bin/sh ' + shlex.quote(self.fixture['compaction_script']),+ 'timeout': 10000}, input_tokens=PRESSURE_TOKENS)+ assert (self.compact_requests == 1 and self.summary_receipt in native_text(body)+ and self.tool_summary_receipt in native_text(body)), \+ 'main request did not consume the actual native summary'+ return dict(kind='text', request_kind='main', input_tokens=30,+ text='compacted-' + self.fixture['receipt'])+++def assert_native_compaction(path, summary_receipt):+ rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line]+ boundaries = [row.get('compactMetadata', {}) for row in rows if row.get('subtype') == 'compact_boundary']+ assert any(item.get('trigger') == 'auto' and item.get('preTokens', 0) >= PRESSURE_TOKENS+ for item in boundaries), 'native history has no actual automatic compaction boundary'+ assert any(row.get('isCompactSummary') and summary_receipt in json.dumps(row) for row in rows), \+ 'exact native session did not persist the independently issued summary'+ return [{'trigger': item.get('trigger'), 'pre_tokens': item.get('preTokens'),+ 'post_tokens': item.get('postTokens')} for item in boundaries]+++class PiCompactionOracle(CompactionOracle):+ def reply(self, _fixture, body):+ assert body.get('model') == self.model+ text = native_text(body)+ recovery = self.fixture.get('recovery', False)+ if any(signature in text.lower() for signature in ('conversation to summarize',+ 'structured summary with new information', 'earlier context from an ongoing conversation')):+ assert self.main_requests == (3 if recovery else 2) and self.compact_requests == 0, 'unexpected Pi summarization order'+ assert self.tool_receipt in text, 'native summary omitted the actual tool receipt'+ self.compact_requests += 1+ return dict(kind='text',request_kind='compact',input_tokens=30,+ text=self.summary_receipt + ': Executed tool receipt ' + self.tool_receipt)+ self.main_requests += 1+ assert self.main_requests <= (5 if recovery else 4)+ if self.main_requests <= 2:+ assert self.fixture['compaction_prompt'] in text+ if self.main_requests == 2:+ assert self.tool_receipt in tool_results(body, 'pi').get('native_compaction_tool', ''), \+ 'pressure turn lacks the independently executed first tool receipt'+ return dict(kind='tool',request_kind='main',id='native_compaction_tool' + ('' if self.main_requests == 1 else '_pressure'),name='bash',+ arguments={'command':'/bin/sh ' + shlex.quote(self.fixture['compaction_script']),'timeout':10},+ input_tokens=1 if self.main_requests == 1 or recovery else PI_PRESSURE_TOKENS)+ if recovery and self.main_requests == 3:+ return dict(kind='text', request_kind='length', input_tokens=10000, recoverable_length=True, text='incomplete attempt')+ assert self.compact_requests == 1 and self.summary_receipt in text, \+ f'Pi main request lacked native summary: main={self.main_requests}, compact={self.compact_requests}'+ return dict(kind='text',request_kind='main',input_tokens=30,text='compacted-' + self.fixture['receipt'])+++def assert_pi_compaction(path, receipt, recovery=False):+ rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line]+ compact = [row for row in rows if row['type'] == 'compaction']+ assert len(compact) == 1 and compact[0]['tokensBefore'] >= (1 if recovery else PI_PRESSURE_TOKENS)+ if recovery:+ edits = [row for row in rows if row['type'] == 'context_edit']+ assert edits and all(row['replacement'] is None for row in edits), 'native recovery did not persist context edits'+ assert receipt in compact[0]['summary'], 'native history lost the independent summary'+ return [{'pre_tokens':compact[0]['tokensBefore'],'summary_preserved':True}]+++def run(repository, candidate):+ harness = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','qoder')+ recovery = os.environ.get('HIROUTE_PRODUCT_PI_RECOVERY') == '1'+ assert not recovery or harness == 'pi'+ assert harness in ('qoder','pi')+ cases = CASES if harness == 'qoder' else (CASES[1],)+ repo = Path(repository).resolve()+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate+ product, upstream = Product(repo), None+ if harness == 'pi':+ product.env['PI_CODING_AGENT_DIR'] = str(Path(product.env['HOME']) / 'selected-pi-config')+ stage = 'prepare-frozen-worker-source'+ report = dict(scenario=harness + '-worker-compaction-route', candidate=candidate, worker_harness=harness,+ required_cases=list(cases), selected_cases=list(cases), cases=[],+ evidence_limit='Real Plan/admission/profile/native Worker/Gateway; controlled upstream; no Desktop verdict')+ try:+ fixture, upstream = prepare_product(product, harness, context_tokens=32768 if harness == 'pi' else CONTEXT_TOKENS)+ report['source_context_tokens'] = fixture['source_context_tokens']+ binary, _, node = selected_installation(harness)+ configure_worker_installation(product, 'pi' if harness == 'pi' else 'qoder_cli', None, binary, node)+ if harness == 'qoder':+ project_settings = product.project / '.qoder/settings.json'+ settings = json.loads(project_settings.read_text())+ settings['experimental'] = {'contextManagement': True}+ settings['model']['summarizeToolOutput'] = {'Bash': {'tokenBudget': 2000}}+ project_settings.write_text(json.dumps(settings))+ protect_configuration(fixture, [project_settings])+ fixture['recovery'] = recovery+ fixture['compaction_prompt'] = 'QODER-COMPACTION-' + secrets.token_hex(12)+ fixture['compaction_script'] = str(product.project / 'native-compaction-receipt.sh')+ oracle = (PiCompactionOracle if harness == 'pi' else CompactionOracle)(fixture, upstream.model)+ script = Path(fixture['compaction_script'])+ # Pi's compactor estimates actual recent messages as well as provider usage.+ # Two genuine large tool outputs leave an older receipt to summarize and+ # a recent one to retain; fabricated usage alone cannot prove compaction.+ lines = (600 if recovery else 1200) if harness == 'pi' else 300+ write_new(script, '#!/bin/sh\ni=0\nwhile [ "$i" -lt ' + str(lines) + ' ]; do\n' ++ ' /usr/bin/printf "%s\\n" ' + shlex.quote(oracle.tool_receipt) ++ '\n i=$((i + 1))\ndone\n', executable=True)+ protect_configuration(fixture, [script])+ (product.root / 'native-context.json').write_text(json.dumps(fixture))+ upstream.reply = oracle.reply+ stage = 'automatic-compaction-in-real-worker'+ command = ('worker exec --plan ' + product.plan_id + ' --cwd ' + str(product.project) ++ ' --run-timeout 120 --no-wait --submission-key qoder-compaction --file - --output json')+ _, accepted = worker_cli(product, command,+ fixture['compaction_prompt'] + ': Execute the requested read-only receipt tool, then finish the task.')+ first = accepted['data']+ fixture['task_id'] = first['task_id']+ result = wait_for_worker_result(product, first['run_id'], timeout=150)+ assert 'compacted-' + fixture['receipt'] in result['result'], 'missing compacted Worker result'+ wait_for_resumable_task(product, first['task_id'], first['run_id'])+ history = exact_history(fixture)+ report['native_compaction_boundaries'] = (assert_pi_compaction(history[0], oracle.summary_receipt, recovery) if harness == 'pi' else assert_native_compaction(history[0], oracle.summary_receipt))+ report['recovery_context_edit'] = recovery+ stage = 'continue-native-compacted-history'+ command = ('worker continue --task ' + first['task_id'] + ' --expected-latest-run ' + first['run_id'] ++ ' --run-timeout 120 --no-wait --submission-key qoder-compaction-continue --file - --output json')+ _, accepted = worker_cli(product, command, 'Continue the same native task using its compacted summary.')+ continued = accepted['data']+ result = wait_for_worker_result(product, continued['run_id'], timeout=150)+ assert 'compacted-' + fixture['receipt'] in result['result']+ wait_for_resumable_task(product, first['task_id'], continued['run_id'])+ assert exact_history(fixture) == history, 'compacted Continue changed the exact native session'+ assert oracle.main_requests == ((5 if recovery else 4) if harness == 'pi' else 3) and oracle.compact_requests == 1 and oracle.tool_summary_requests == (0 if harness == "pi" else 1), \+ 'required native request kinds missing'+ attempts = source_events(upstream)+ assert [event.get('request_kind') for event in attempts] == ((['main','main','length','compact','main','main'] if recovery else ['main','main','compact','main','main']) if harness == 'pi' else ['main', 'tool_summary', 'compact', 'main', 'main']), attempts+ assert all(event['state'] == 'green' and event['model'] == upstream.model for event in attempts)+ assert_preserved(fixture)+ if harness == 'qoder':+ qoder_native_context.assert_settings_preserved(fixture)+ product.stop()+ diagnostics = product.diagnostics_snapshot()+ assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'+ report.update(state='green', cases=[{'id': case, 'state': 'green'} for case in cases], task_id=first['task_id'],+ run_ids=[first['run_id'], continued['run_id']], native_session_id=history[1],+ main_requests=oracle.main_requests, compact_requests=oracle.compact_requests,+ tool_summary_requests=oracle.tool_summary_requests,+ upstream_model=upstream.model, foreign_requests=0, diagnostics=diagnostics,+ binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},+ harness_sha256=digest(binary))+ print(json.dumps(report), flush=True)+ except Exception:+ report_failure(product, report, stage)+ raise+ finally:+ try:+ product.close()+ finally:+ try:+ qoder_native_context.cleanup_context(product)+ finally:+ if upstream:+ upstream.close()+++if __name__ == '__main__':+ run(sys.argv[1], sys.argv[2])diff --git a/crates/daemon/tests/support/native_context_boundaries.py b/crates/daemon/tests/support/native_context_boundaries.pyindex cdcb12b2..12c89bbe 100644--- a/crates/daemon/tests/support/native_context_boundaries.py+++ b/crates/daemon/tests/support/native_context_boundaries.py@@ -4,6 +4,7 @@ Reuse the core native context transport and product setup. No fake ACP, databaseedits, deletion API, or private execution port. This entry never builds binaries."""import qoder_native_context+import pi_native_contextimport argparsefrom concurrent.futures import ThreadPoolExecutorimport copy@@ -84,6 +85,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'] == 'pi':+ assert 'bash' in names+ name, arguments = 'bash', {'command': command, 'timeout': 120}elif 'exec_command' in names:name, arguments = 'exec_command', {'cmd': command, 'yield_time_ms': 30000,'max_output_tokens': 1000}@@ -131,9 +135,16 @@ def source_events(upstream):return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []+def assert_source_routing(upstream):+ attempts = source_events(upstream)+ assert upstream.rejected_count() == 0, 'rejected model request on concurrent route'+ assert attempts and all(event['state'] == 'green' and event['model'] == upstream.model+ for event in attempts), attempts++def transcript_snapshot(fixture):root = (qoder_native_context.history_directory(fixture) if fixture['harness'] == 'qoder'- else Path(fixture['config']) / ('sessions' if fixture['harness'] == 'codex' else 'projects'))+ 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()}@@ -206,6 +217,8 @@ def run(repository, candidate, harness):repo = Path(repository).resolve()assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidateproduct = Product(repo)+ if harness == "pi":+ product.env["PI_CODING_AGENT_DIR"] = str(Path(product.env["HOME"]) / "selected-pi-config")upstreams, fixtures, runs = [], [], []stage = 'setup'report = dict(scenario='worker-native-context-boundaries', candidate=candidate,@@ -242,9 +255,7 @@ def run(repository, candidate, harness):wait_until(lambda: all(heartbeat_size(item) > 0 and running_child(item) for item in fixtures),'both real Workers did not execute their native tools concurrently', 120)for fixture, source in zip(fixtures, upstreams):- attempts = source_events(source)- assert attempts and all(event['state'] == 'green' and event['model'] == source.model- for event in attempts), attempts+ assert_source_routing(source)assert_preserved(fixture)assert runs[0]['task_id'] != runs[1]['task_id']report['simultaneous_routes'] = [dict(model=source.model, requests_before_cancel=len(source_events(source)))@@ -258,6 +269,8 @@ def run(repository, candidate, harness):Path(neighbor['boundary']['release']).touch()result = wait_for_worker_result(product, runs[1]['run_id'], timeout=45)assert neighbor['receipt'] in result['result']+ for source in upstreams:+ assert_source_routing(source)wait_until(lambda: not running_child(neighbor), 'completed neighbor tool still exists', 10)for fixture in fixtures:assert_preserved(fixture)@@ -276,6 +289,8 @@ def run(repository, candidate, harness):report['run_ids'] = [run['run_id'] for run in runs]stage = 'missing-native-history'report['missing_history'] = missing_history_refuses_new_session(product, neighbor, runs[1], upstreams)+ if harness == 'pi':+ report['corrupt_history'] = pi_native_context.verify_corrupt_history_variants(product, dict(neighbor, plan_id=neighbor_plan), runs[1], upstreams)report['cases'].append({'id': CASES[2], 'state': 'green', 'variant': 'missing-history-no-new'})report.update(state='green', binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},harness_sha256=hashlib.sha256(binary.read_bytes()).hexdigest())@@ -306,6 +321,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'), required=True)+ parser.add_argument('--harness', choices=('codex', 'claude', 'qoder', 'pi'), 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 866ee3e3..9d37f3ed 100644--- a/crates/daemon/tests/support/native_context_fixture.py+++ b/crates/daemon/tests/support/native_context_fixture.py@@ -35,9 +35,26 @@ def write_new(path, text, executable=False):path.chmod(0o700 if executable else 0o600)+def prepare_skill(parent, name, scope, writer=write_new):+ nonce = secrets.token_hex(12)+ directory = parent / name+ discovery, contents, executed = ('discovery-' + nonce, 'contents-' + nonce, 'executed-' + nonce)+ script = directory / 'receipt.sh'+ writer(script, '#!/bin/sh\nprintf "%s\\n" ' + shlex.quote(executed) + '\n', True)+ skill = directory / 'SKILL.md'+ writer(skill, '\n'.join((+ '---', 'name: ' + name,+ 'description: Native context read-only receipt ' + discovery, '---', '',+ 'Read this skill and run its receipt script using the native shell tool.',+ 'Content receipt: ' + contents, 'Script: ' + str(script), '',+ )))+ return dict(name=name, scope=scope, discovery=discovery, contents=contents,+ executed=executed, skill=str(skill), script=str(script))++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')+ assert harness in ('codex', 'claude', 'qoder', 'pi')home, config, project = map(lambda path: Path(path).resolve(), (home, config, project))def owned_write(path, text, executable=False):write_new(path, text, executable)@@ -47,23 +64,9 @@ 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'}[harness]),+ ('project', project / {'codex': '.agents/skills', 'claude': '.claude/skills', 'qoder': '.qoder/skills', 'pi': '.pi/skills'}[harness]),):- nonce = secrets.token_hex(12)- name = 'native-context-' + scope + suffix- directory = parent / name- discovery, contents, executed = ('discovery-' + nonce, 'contents-' + nonce, 'executed-' + nonce)- script = directory / 'receipt.sh'- owned_write(script, '#!/bin/sh\nprintf "%s\\n" ' + shlex.quote(executed) + '\n', True)- skill = directory / 'SKILL.md'- owned_write(skill, '\n'.join((- '---', 'name: ' + name,- 'description: Native context read-only receipt ' + discovery, '---', '',- 'Read this skill and run its receipt script using the native shell tool.',- 'Content receipt: ' + contents, 'Script: ' + str(script), '',- )))- skills.append(dict(name=name, scope=scope, discovery=discovery, contents=contents,- executed=executed, skill=str(skill), script=str(script)))+ skills.append(prepare_skill(parent, 'native-context-' + scope + suffix, scope, owned_write))neighbor = config / ('native-context-neighbor' + suffix + '.txt')owned_write(neighbor, 'A neighboring user file must survive Worker cleanup.\n')protected = [neighbor, *(Path(item[key]) for item in skills for key in ('skill', 'script'))]@@ -93,7 +96,7 @@ def assert_preserved(fixture):def tool_results(body, harness):"""Only correlated tool-result records count, never arbitrary prompt substrings."""- if harness in ('codex', 'qoder'):+ if harness in ('codex', 'qoder', 'pi'):source = body.get('input', [])return {item.get('call_id'): item.get('output', '') for item in sourceif isinstance(item, dict) and item.get('type') == 'function_call_output'} \@@ -178,6 +181,9 @@ def decision(fixture, body):'expected native Skill directory was not loaded'assert 'Bash' in names, 'native Bash tool unavailable'name = 'Bash'+ elif harness == 'pi':+ assert 'bash' in names and 'read' in names, 'native Pi tools unavailable'+ name = 'bash'else:name = next((name for name in ('exec_command', 'shell_command') if name in names), None)assert name, 'native shell tool unavailable'@@ -185,7 +191,7 @@ def decision(fixture, body):+ shlex.quote(skill['script']) for skill in fixture['skills'])arguments = ({'cmd': command, 'max_output_tokens': 2000, 'yield_time_ms': 1000}if name == 'exec_command' else {'command': command, 'timeout_ms': 10000}- if name == 'shell_command' else {'command': command, 'timeout': 10000})+ if name == 'shell_command' else {'command': command, 'timeout': 10 if harness == 'pi' else 10000})return dict(kind='tool', id='native_context_execute', name=name, arguments=arguments)@@ -218,6 +224,8 @@ def events(body, action, protocol):'status': 'completed', 'output': [item],'usage': {'input_tokens': action.get('input_tokens', 1), 'output_tokens': 1,'total_tokens': action.get('input_tokens', 1) + 1}}+ if action.get('recoverable_length'):+ response.update(status='incomplete', incomplete_details={'reason':'max_output_tokens'})added = dict(item, status='in_progress')added['arguments' if action['kind'] == 'tool' else 'content'] = '' if action['kind'] == 'tool' else []middle = ([('response.function_call_arguments.delta', {'item_id': item['id'],@@ -234,7 +242,7 @@ def events(body, action, protocol):return [('response.created', {'response': dict(response, status='in_progress', output=[])}),('response.output_item.added', {'output_index': 0, 'item': added}), *middle,('response.output_item.done', {'output_index': 0, 'item': item}),- ('response.completed', {'response': response})]+ ('response.incomplete' if action.get('recoverable_length') else 'response.completed', {'response': response})]def handle(handler, body, controls, lock, reply=decision):@@ -322,6 +330,7 @@ class NativeContextUpstream:self.lock = threading.Lock()self.reply = decisionself.requests = 0+ self.rejected_requests = 0self.proxy_trap = Noneclass Handler(http.server.BaseHTTPRequestHandler):@@ -340,6 +349,11 @@ class NativeContextUpstream:self.end_headers()self.wfile.write(body)+ def reject(self, reason, status):+ with owner.lock:+ owner.rejected_requests += 1+ self.send({'error': reason}, status)+def do_GET(self):# A manually declared model remains usable without directory discovery.self.send({'error': 'directory not implemented'}, 404)@@ -348,14 +362,14 @@ class NativeContextUpstream:with owner.lock:owner.requests += 1if self.headers.get('Authorization') != 'Bearer ' + owner.token:- return self.send({'error': 'incorrect synthetic source credential'}, 401)+ return self.reject('incorrect synthetic source credential', 401)if self.path not in ('/v1/responses', '/v1/messages'):- return self.send({'error': 'incorrect source endpoint'}, 404)+ return self.reject('incorrect source endpoint', 404)body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))if body.get('model') != owner.model:- return self.send({'error': 'incorrect source model'}, 400)+ return self.reject('incorrect source model', 400)if not handle(self, body, owner.controls, owner.lock, owner.reply):- self.send({'error': 'native context fixture is not prepared'}, 503)+ self.reject('native context fixture is not prepared', 503)def send_messages_stream(self, frames):encoded = []@@ -377,6 +391,10 @@ class NativeContextUpstream:self.thread.start()self.base_url = 'http://%s:%d/v1' % self.server.server_address+ def rejected_count(self):+ with self.lock:+ return self.rejected_requests+def request_count(self):"""All source attempts, including rejected credentials; never record a secret."""with self.lock:diff --git a/crates/daemon/tests/support/native_context_product.py b/crates/daemon/tests/support/native_context_product.pyindex ba7fa710..31e90116 100644--- a/crates/daemon/tests/support/native_context_product.py+++ b/crates/daemon/tests/support/native_context_product.py@@ -21,6 +21,7 @@ from model_connections_product import save_native_sourcefrom publication_product import Productfrom publication_process import plan_changeimport qoder_native_context+import pi_native_contextdef save_context_source(product, upstream, variant='', context_tokens=None):@@ -44,6 +45,8 @@ def selected_installation(harness):binary = Path(os.environ['HIROUTE_WORKER_' + harness.upper() + '_BINARY']).resolve(strict=True)if harness == 'qoder':return binary, None, None+ if harness == 'pi':+ return binary, None, Path(os.environ['HIROUTE_WORKER_NODE']).resolve(strict=True)adapter = Path(os.environ['HIROUTE_WORKER_' + harness.upper() + '_ACP_ADAPTER']).resolve(strict=True)node = Path(os.environ['HIROUTE_WORKER_NODE']).resolve(strict=True)return binary, adapter, node@@ -52,16 +55,18 @@ 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'}+ roots = {'codex': 'CODEX_HOME', 'claude': 'CLAUDE_CONFIG_DIR', 'qoder': 'QODER_CONFIG_DIR', 'pi': 'PI_CODING_AGENT_DIR'}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 == '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'}[harness],+ 'qoder': 'qoder_cli', 'pi': 'pi'}[harness],'protocol': 'messages' if harness == 'claude' else 'responses'}fixture['source_context_tokens'] = (context_tokens if context_tokens is not Noneelse native_context_budget(product))@@ -93,6 +98,8 @@ 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':+ 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','ANTHROPIC_AUTH_TOKEN': 'synthetic-ambient-must-not-authorize-worker',@@ -147,6 +154,8 @@ def assert_frozen_route(original_events, before, replacement):def exact_history(fixture):"""Inspect only this synthetic context's native transcript directory, never auth."""+ if fixture['harness'] == 'pi':+ return pi_native_context.exact_history(fixture)if fixture['harness'] == 'qoder':return qoder_native_context.exact_history(fixture)folder = Path(fixture['config']) / ('sessions' if fixture['harness'] == 'codex' else 'projects')@@ -218,12 +227,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')+ assert harness in ('codex', 'claude', 'qoder', 'pi')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 'CLAUDE_CONFIG_DIR'] = str(+ product.env['CODEX_HOME' if harness == 'codex' else 'PI_CODING_AGENT_DIR' if harness == 'pi' else 'CLAUDE_CONFIG_DIR'] = str(Path(product.env['HOME']) / ('selected-' + harness + '-config'))upstream = replacement = Nonestage = 'prepare-native-context'@@ -236,7 +245,7 @@ def run(repository, candidate):binary, adapter, node = selected_installation(harness)stage = 'real-daemon-and-plan'fixture, upstream = prepare_product(product, harness,- context_tokens=32_768 if harness == 'qoder' else None)+ context_tokens=16_384 if harness == 'pi' else 32_768 if harness == 'qoder' else None)report['source_context_tokens'] = fixture['source_context_tokens']if harness == 'qoder':fixture['expected_max_output_tokens'] = 4096diff --git a/crates/daemon/tests/support/pi_discovery_product.py b/crates/daemon/tests/support/pi_discovery_product.pynew file mode 100644index 00000000..34d54aec--- /dev/null+++ b/crates/daemon/tests/support/pi_discovery_product.py@@ -0,0 +1,151 @@+"""Import Pi's effective static source through real Scan → Prepare → Save.++Only native configuration and the deterministic upstream are fixtures. Protected+input, candidate state, save conflict and restart all use public product entries.+"""+import hashlib+import json+import os+import secrets+from pathlib import Path+import subprocess+import sys++from model_connections_product import control, desktop_grant, save_compute_candidate+from native_context_fixture import NativeContextUpstream, digest, write_new+from native_context_product import report_failure, selected_installation+from publication_product import Product, encoded+from publication_process import plan_change+from agent_product_support import apply_settings, expose_native_installation+from additional_model_fixture import PersistedRouteOracle, read_persisted_route++CASES = ('agent.sources.effective-static-import', 'agent.sources.changed-source-rejected',+ 'agent.sources.imported-route-usable')+++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',+ '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,+ 'classifier':{'kind':'local_rules'},'complex_keywords':[]},+ 'free':{'candidates':[],'primary':[],'primary_fallback':False},+ 'requirements':{}, 'limits':{'maximum_attempts':1,'request_timeout_ms':30000,'attempt_timeout_ms':30000}}+ change = plan_change(product, 'create', 'pi-imported-route')+ 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')+ product.agent_connection = 'agent-connection/' + agent['context_id']+ product.additional_harness = 'pi'+ spec = {'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']]}},+ 'collaboration':{'intent':'keep'}, 'access_token':{'intent':'keep'}}+ configured, status = apply_settings(product, spec, 'pi-imported-model-route', 'model')+ product.bearer(product.agent_connection)+ oracle = PersistedRouteOracle(source.model)+ source.reply = oracle.reply+ try:+ selector = configured['model_effect']['provider_id'] + '/' + plan['model_alias']+ return read_persisted_route(product, binary, selector, source, oracle, 'pi-imported-source-route')+ finally:+ spec['model'] = {'intent':'restore','restore_point_ref':status['restore_point_ref']}+ apply_settings(product, spec, 'pi-imported-model-restore', 'model')+++def prepare(product, discovery, identity):+ payload = {'discovery': discovery, 'prepare_id': identity}+ revisions = control(product, 'GetClientServiceStatus', {})['data']['revisions']+ grant = desktop_grant(product, 'PrepareDiscoveredModelConnection',+ 'sha256:' + hashlib.sha256(encoded(payload)).hexdigest(), revisions, identity + '-grant-' + secrets.token_hex(6))+ return control(product, 'PrepareDiscoveredModelConnection', payload, grant)['data']+++def scan(product):+ items = control(product, 'ScanCompute', {})['data']['items']+ sources = [item for item in items if item['agent_id'] == 'agent_pi_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):+ repo = Path(repository).resolve()+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate+ product = Product(repo)+ source = None+ stage = 'native-static-source'+ report = dict(scenario='pi-static-source-import', candidate=candidate, worker_harness='pi',+ 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'+ config.mkdir(mode=0o700)+ product.env['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', '\ufeff// Native effective endpoint differs from provider default\n' ++ 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()+ product.secrets.update((source.token, 'provider-fallback'))+ product.start()+ stage = 'public-scan-prepare-save'+ discovery = scan(product)+ candidate_view = prepare(product, discovery, 'pi-source-prepare')+ assert prepare(product, discovery, 'pi-source-prepare') == candidate_view, 'prepare retry changed its 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'+ product.stop()+ product.start()+ snapshot = control(product, 'ListCompute', {})['data']+ assert saved['source_id'] in json.dumps(snapshot), 'saved Pi source disappeared after restart'+ report['cases'].append({'id':CASES[0],'state':'green'})+ stage = 'source-rotated-before-save'+ prepared = prepare(product, scan(product), 'pi-source-stale-prepare')+ revision = control(product, 'ListCompute', {})['data']['revisions']+ change = {'schema':'hiroute.compute-management-change/v2',+ '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'}}))+ 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)+ 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'+ 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,+ native_files_preserved_on_import=True, saved_source_survived_restart=True,+ binaries={name:digest(product.bin / name) for name in ('hiroute','hirouted')})+ except Exception:+ report_failure(product, report, stage)+ raise+ finally:+ product.close()+ if source:+ source.close()+ print(json.dumps(report), flush=True)+++if __name__ == '__main__':+ run(sys.argv[1], sys.argv[2])diff --git a/crates/daemon/tests/support/pi_native_context.py b/crates/daemon/tests/support/pi_native_context.pynew file mode 100644index 00000000..ecde0871--- /dev/null+++ b/crates/daemon/tests/support/pi_native_context.py@@ -0,0 +1,110 @@+"""Pi-specific native resources and exact task transcript; reuse common product journeys."""+import json+from pathlib import Path+import shlex+from native_context_fixture import prepare_skill, write_new, protect_configuration, assert_preserved+++def prepare_context(product, fixture):+ root = Path(fixture['config'])+ package = root / 'installed-receipt-package'+ skill = prepare_skill(package / 'skills', 'native-context-package', 'package')+ write_new(package / 'package.json', json.dumps({'name': 'hiroute-acceptance-resources',+ 'version': '1.0.0', 'pi': {'skills': ['./skills']}}))+ fixture['skills'].append(skill)+ fixture['product_storage'] = str(product.storage)+ fixture['credential_helper_trap'] = str(root / 'credential-helper-must-not-run')+ write_new(root / 'auth.json', json.dumps({'anthropic': {'type': 'api_key',+ 'key': '!printf leaked > ' + shlex.quote(fixture['credential_helper_trap'])},+ 'hiroute-worker': {'type': 'api_key', 'key': 'saved-key-must-not-override-run'}}))+ write_new(root / 'models.json', json.dumps({'providers': {'ambient': {+ 'baseUrl': 'http://127.0.0.1:9/v1', 'api': 'openai-responses', 'apiKey': 'wrong-native-key',+ 'models': [{'id': 'wrong-native-model', 'contextWindow': 32768, 'maxTokens': 4096}]}}}))+ write_new(root / 'settings.json', json.dumps({'defaultProvider': 'ambient',+ 'defaultModel': 'wrong-native-model', 'packages': [str(package)],+ 'extensions': [str(root / 'missing-extension-must-not-be-installed')],+ 'compaction': {'enabled': False}, 'retry': {'enabled': True}}))+ protect_configuration(fixture, [root / name for name in ('auth.json', 'models.json', 'settings.json')]+ + [package / 'package.json', Path(skill['skill']), Path(skill['script'])])+++def history_directory(fixture):+ return Path(fixture['product_storage']) / 'delegation-workers/sessions'+++def exact_history(fixture):+ found = []+ for marker in history_directory(fixture).glob('*/.hiroute-native-root-v1.json'):+ assert not marker.is_symlink() and not marker.parent.is_symlink()+ value = json.loads(marker.read_text())+ if value['task_id'] != fixture['task_id']:+ continue+ assert value['harness'] == 'pi'+ path = marker.parent / 'native-pi.jsonl'+ assert path.is_file() and not path.is_symlink()+ rows = [json.loads(line) for line in path.read_text().splitlines()]+ assert rows[0]['type'] == 'session' and rows[0]['cwd'] == fixture['project']+ assert fixture['receipt'] in path.read_text(), 'Pi history lacks this task receipt'+ found.append((str(path), rows[0]['id']))+ assert len(found) == 1, 'expected one exact task-owned Pi transcript'+ assert not Path(fixture['credential_helper_trap']).exists(), 'Worker executed native credential helper'+ return found[0]+++def corrupt_history_refuses_model_call(product, fixture, task, upstreams, variant="truncated-json"):+ from delegation_product import worker_cli, wait_for_worker_result+ path, identity = exact_history(fixture)+ path = Path(path)+ original = path.read_bytes()+ before = [upstream.request_count() for upstream in upstreams]+ try:+ # A correct header with truncated JSON body previously loaded as an empty session.+ if variant == 'truncated-json':+ damaged = original.split(b'\n', 1)[0] + b'\n{"type":"message",broken\n'+ else:+ rows = [json.loads(line) for line in original.splitlines()]+ if variant == 'missing-content':+ entry = next(row for row in rows[1:] if row.get('type') == 'message' and row['message']['role'] == 'user')+ del entry['message']['content']+ elif variant == 'old-session-version':+ rows[0]['version'] = 2+ elif variant == 'unknown-session-version':+ rows[0]['version'] = 4+ else:+ raise AssertionError('unknown native corruption fixture')+ damaged = ('\n'.join(json.dumps(row) for row in rows) + '\n').encode()+ path.write_bytes(damaged)+ corrupt = path.read_bytes()+ command = ('worker continue --task ' + task['task_id'] + ' --expected-latest-run '+ + task['run_id'] + ' --run-timeout 30 --no-wait --submission-key pi-corrupt-history-' + variant + ' --file - --output json')+ status, response = worker_cli(product, command, 'Continue the same task.', success=False)+ if status == 0:+ result = wait_for_worker_result(product, response['data']['run_id'], expected='failed', timeout=45)+ assert not result.get('result')+ else:+ assert response['error']['code'] == 'CAPABILITY_UNAVAILABLE', response+ assert [upstream.request_count() for upstream in upstreams] == before+ assert path.read_bytes() == corrupt, 'corrupt Pi transcript was silently repaired'+ assert_preserved(fixture)+ return {'variant':variant, 'native_session_id': identity, 'model_posts': 0, 'history_unchanged': True}+ finally:+ path.write_bytes(original)+++def verify_corrupt_history_variants(product, fixture, task, upstreams):+ from delegation_product import worker_cli, wait_for_worker_result+ from native_context_product import wait_for_resumable_task+ results = [corrupt_history_refuses_model_call(product, fixture, task, upstreams)]+ for variant in ('missing-content', 'old-session-version', 'unknown-session-version'):+ # Give each corruption an independently healthy task. A previously refused+ # Continue cannot mask a later variant by withdrawing that task's capability.+ command = ('worker exec --plan ' + fixture['plan_id'] + ' --cwd ' + str(product.project)+ + ' --run-timeout 120 --no-wait --submission-key pi-history-' + variant + ' --file - --output json')+ prompt = fixture['boundary']['marker'] + ': use the native context Skills and receipt tool.'+ _, response = worker_cli(product, command, prompt)+ healthy = response['data']+ wait_for_worker_result(product, healthy['run_id'], timeout=130)+ wait_for_resumable_task(product, healthy['task_id'], healthy['run_id'])+ independent = dict(fixture, task_id=healthy['task_id'])+ results.append(corrupt_history_refuses_model_call(product, independent, healthy, upstreams, variant))+ return resultsdiff --git a/crates/daemon/tests/support/publication_product.py b/crates/daemon/tests/support/publication_product.pyindex 46a53a8a..409500c6 100644--- a/crates/daemon/tests/support/publication_product.py+++ b/crates/daemon/tests/support/publication_product.py@@ -140,10 +140,13 @@ finally:'GOOGLE_', 'VERTEX_', 'QODER_'))and k not in ('CODEX_CONFIG', 'CODEX_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN','GEMINI_API_KEY', 'OPENROUTER_API_KEY', 'CLAUDE_CODE_USE_BEDROCK',- 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY')}+ 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',+ 'DEEPSEEK_API_KEY', 'GROQ_API_KEY', 'MISTRAL_API_KEY',+ 'XAI_API_KEY', 'CEREBRAS_API_KEY')}self.env.update(HOME=str(home), CODEX_HOME=str(home / '.codex'),CLAUDE_CONFIG_DIR=str(home / '.claude'),QODER_CONFIG_DIR=str(home / '.qoder'),+ PI_CODING_AGENT_DIR=str(home / '.pi/agent'),PATH=str(bin_dir) + ':/usr/bin:/bin',HIROUTE_RUNTIME_DIR=str(self.root / 'runtime'),HIROUTE_WORKER_RECEIPT_DIR=str(self.root / 'worker-receipts'),diff --git a/crates/daemon/tests/support/qoder_collaboration_fixture.py b/crates/daemon/tests/support/qoder_collaboration_fixture.pyindex 1a8d75eb..92c9a44a 100644--- a/crates/daemon/tests/support/qoder_collaboration_fixture.py+++ b/crates/daemon/tests/support/qoder_collaboration_fixture.py@@ -1,170 +1,2 @@-"""Two independent model-role oracles for real Qoder Skill → public CLI → Worker.--Only native tool results and the Worker's disk artifact can complete this journey.-This module does not start HiRoute, impersonate an Agent, or write its installed Skill.-"""-import json-from pathlib import Path-import shlex--from native_context_fixture import decision, qoder_skill_expansions, tool_results---CASES = ('agent.collaboration.user-skill', 'agent.collaboration.public-worker-delegation',- 'agent.collaboration.disable-owned-skill')---def successful_envelope(output):- """Qoder Bash may surround stdout with native timing/status text."""- assert isinstance(output, str), 'expected a native Bash text result'- decoder = json.JSONDecoder()- matches = []- for index, char in enumerate(output):- if char != '{':- continue- try:- value, _ = decoder.raw_decode(output[index:])- except ValueError:- continue- if isinstance(value, dict) and 'schema_version' in value and 'status' in value:- matches.append(value)- assert len(matches) == 1 and matches[0]['status'] == 'succeeded', \- 'expected one successful public CLI envelope in the correlated tool result'- return matches[0]---def output_envelope(output):- return successful_envelope(output)['data']---def worker_decision(fixture, body):- results = tool_results(body, 'qoder')- artifact = fixture['artifact']- if 'delegated_artifact' in results:- assert artifact['receipt'] in results['delegated_artifact'], 'Worker tool did not return artifact receipt'- path = Path(artifact['path'])- assert path.is_file() and not path.is_symlink() and path.read_text().strip() == artifact['receipt'], \- 'Worker did not produce the independent disk artifact'- return dict(kind='text', text=artifact['receipt'], continued=False)- action = decision(fixture, body)- if action['kind'] != 'text':- return action- command = ('/usr/bin/printf "%s\\n" ' + shlex.quote(artifact['receipt']) + ' > ' +- shlex.quote(artifact['path']) + ' && /bin/cat ' + shlex.quote(artifact['path']))- return dict(kind='tool', id='delegated_artifact', name='Bash',- arguments={'command': command, 'timeout': 10000})---class MainAgentOracle:- def __init__(self, fixture, skill, cli, worker_events):- self.fixture = fixture- self.skill = Path(skill)- self.skill_body = self.skill.read_text().split('---', 2)[-1].strip()- assert self.skill_body and 'hiroute worker plans' in self.skill_body- self.cli = str(Path(cli).resolve(strict=True))- self.worker_events = worker_events- self.accepted = None- self.user_skill_proved = False- self.completed = False- self.requests = 0-- def reply(self, _unused, body):- self.requests += 1- assert self.requests <= 32, 'main Agent exceeded the bounded public observation budget'- rendered = json.dumps(body)- assert self.fixture['main_marker'] in rendered, 'Worker request reached the main Agent source'- results = tool_results(body, 'qoder')- names = {item.get('name') for item in body.get('tools', [])}- assert {'Skill', 'Bash'} <= names, 'native main Agent 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={'skill': 'hiroute-collaboration'})- # Native Qoder returns a correlated launch receipt, then expands the body- # into a user message. Exact directory excludes a same-named project/plugin.- contents = qoder_skill_expansions(body, self.skill.parent)- assert any(text.strip() == self.skill_body for text in contents), \- 'actual installed user Skill directory and body were not loaded'- self.user_skill_proved = True- if 'main_plans' not in results:- 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'] == 'qoder_cli' 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']) + \- ' to complete the delegated native receipt task.'- command = ('/usr/bin/printf %s ' + shlex.quote(prompt) + ' | ' + shlex.quote(self.cli) +- ' worker exec --plan ' + shlex.quote(plans[0]['agent_plan_id']) + ' --cwd ' +- shlex.quote(self.fixture['project']) + ' --run-timeout 120 --wait-timeout 120' +- ' --submission-key qoder-main-agent-delegation --file - --output json')- return self.bash('main_exec', command, 150000)- envelope = successful_envelope(results['main_exec'])- accepted = envelope['data']- # Retain the actual public result even on failure for scoped diagnosis;- # completion still requires success and the independent disk artifact.- self.accepted = accepted- assert accepted.get('task_id') and accepted.get('run_id'), 'public Worker acceptance has no identity'- wait_index = 1- while 'main_wait_' + str(wait_index) in results:- envelope = successful_envelope(results['main_wait_' + str(wait_index)])- self.assert_same_worker(envelope['data'], accepted)- wait_index += 1- current = envelope['data']- self.accepted = current- if current['run_state'] not in ('succeeded', 'failed', 'cancelled', 'unknown'):- actions = [action['input'] for action in envelope.get('next_actions', [])- if action.get('command_id') == 'worker.wait'- and action.get('input', {}).get('run_id') == accepted['run_id']]- assert (len(actions) == 1 and type(actions[0].get('after_revision')) is int- and actions[0]['after_revision'] >= 0), \- 'active public Worker result must provide its exact wait cursor'- command = (shlex.quote(self.cli) + ' worker wait --run ' + shlex.quote(accepted['run_id']) +- ' --after-revision ' + str(actions[0]['after_revision']) +- ' --wait-timeout 20 --output json')- return self.bash('main_wait_' + str(wait_index), command, 25000)- assert current['run_state'] == 'succeeded', 'main Agent did not observe successful public Worker execution'- if 'result' not in current:- if 'main_result' not in results:- return self.bash('main_result', shlex.quote(self.cli) + ' worker result --run ' +- shlex.quote(accepted['run_id']) + ' --output json')- current = output_envelope(results['main_result'])- self.assert_same_worker(current, accepted)- assert current['run_state'] == 'succeeded', 'public Worker result is not successful'- receipt = self.fixture['artifact']['receipt']- assert receipt in current.get('result', ''), 'public Worker result lost its tool artifact'- assert Path(self.fixture['artifact']['path']).read_text().strip() == receipt, 'disk artifact missing'- attempts = self.worker_events()- assert attempts and all(event['state'] == 'green' for event in attempts), 'Worker source is incomplete'- assert any(event.get('call_id') == 'delegated_artifact' for event in attempts), \- 'no real Worker tool request produced the artifact'- self.accepted, self.completed = current, True- return dict(kind='text', text='MAIN-AGENT-COMPLETED-' + receipt, continued=False)-- @staticmethod- def assert_same_worker(current, accepted):- assert all(current.get(key) == accepted[key] for key in ('task_id', 'run_id')), \- 'public observation switched the accepted Worker identity'-- @staticmethod- def bash(call_id, command, timeout=10000):- return dict(kind='tool', id=call_id, name='Bash', arguments={'command': command, 'timeout': timeout})---def main_route_settings(endpoint, alias, credential_env):- """Independent native-main fixture settings; Worker uses the production renderer."""- provider = 'hiroute-main-acceptance'- selected = provider + '/' + alias- own_alias = {'modelConfig': {'model': selected}}- return selected, {- 'general': {'enableAutoUpdate': False, 'sessionRetention': {'enabled': False},- 'plan': {'modelRouting': False}},- 'disableAllHooks': True, 'promptSuggestionEnabled': False, 'model': {'name': selected},- 'modelConfigs': {'aliases': {selected: own_alias}, 'customAliases': {selected: own_alias},- 'overrides': [], 'customOverrides': []},- 'providers': {provider: {'protocol': 'openai-responses', 'baseUrl': endpoint,- 'apiKey': '${' + credential_env + '}', 'model': alias,- 'models': [{'model': alias, 'contextWindow': 100000, 'capabilities': {'tools': True}}],- 'routing': {purpose: alias for purpose in ('utility', 'session_title', 'summary', 'compact', 'subagent')}}},- }+"""Qoder compatibility imports; shared oracle owns public delegation assertions."""+from collaboration_fixture import *diff --git a/crates/daemon/tests/support/qoder_collaboration_product.py b/crates/daemon/tests/support/qoder_collaboration_product.pyindex ac8c11ce..4ba8dd6c 100644--- a/crates/daemon/tests/support/qoder_collaboration_product.py+++ b/crates/daemon/tests/support/qoder_collaboration_product.py@@ -1,213 +1,5 @@-"""Real Qoder main Agent → installed user Skill → public CLI → real Qoder Worker.--Uses the same Product, managed candidate and native context as the Worker journeys.-Only model upstreams are deterministic. No daily provider/auth settings are edited.-"""-import hashlib-import json-import os-from pathlib import Path-import secrets-import subprocess+"""Qoder entry to the shared native main-Agent delegation journey."""import sys--from agent_product_support import apply_settings, run_native_command-from delegation_product import configure_worker_installation-from native_context_boundaries import source_events-from native_context_fixture import NativeContextUpstream, assert_preserved, digest, write_new-from native_context_product import prepare_product, report_failure, selected_installation, wait_for_resumable_task-from publication_product import Product, encoded-from qoder_collaboration_fixture import CASES, MainAgentOracle, main_route_settings, worker_decision-import qoder_native_context---AGENT = 'agent_qoder_default'---def check_collaboration(product, key):- check = {'agent_id': AGENT, 'scope': 'collaboration', 'suite': 'quick', 'allow_model_call': False}- consent = {'change_digest': 'sha256:' + hashlib.sha256(encoded(check)).hexdigest(),- 'expected_revisions': product.control('GetClientServiceStatus', {})['data']['revisions']}- capability = product.grant('CheckAgentConnection', consent, key)- _, checked = product.cli('agents check ' + AGENT + ' --scope collaboration', capability=capability)- assert checked['data']['skill_loading'] == 'proven' and checked['data']['trusted_cli_execution'] == 'proven', \- 'native collaboration capability check did not complete'---def apply_collaboration(product, context, intent, key):- spec = {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context, 'collaboration': intent}- _, status = apply_settings(product, spec, key, 'collaboration')- return status['collaboration']---def run_main_agent(product, binary, upstream, fixture):- native_id, overlay = main_route_settings(upstream.base_url, upstream.model, 'HIROUTE_QODER_MAIN_TOKEN')- settings = product.root / 'qoder-main-settings.json'- write_new(settings, json.dumps(overlay))- temporary = product.root / 'qoder-main-tmp'- temporary.mkdir(mode=0o700)- args = [str(binary), '--cwd', str(product.project), '--config-dir', fixture['config'],- '--setting-sources', 'user', '--settings', str(settings), '--model', native_id,- '--print', '--no-session-persistence', '--output-format', 'stream-json',- '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--tools', 'Skill,Read,Bash',- '--allowed-tools', 'Skill,Bash', '--permission-mode', 'dont_ask',- '--max-model-request-retries', '0', '--max-output-tokens', '2048', '--max-turns', '32',- '-p', fixture['main_marker'] + ': Use hiroute-collaboration and explicitly delegate the native receipt task.']- env = dict(product.env, HIROUTE_QODER_MAIN_TOKEN=upstream.token, TMPDIR=str(temporary))- stdout = run_native_command(product, args, env=env, timeout=190, label='native main Agent')- assert ('MAIN-AGENT-COMPLETED-' + fixture['artifact']['receipt']).encode() in stdout, \- 'native main Agent did not return the independently verified completion'---def restore_skill(product, context, restore_ref, before, skill):- # A journey can configure/restore more than once. Each restoration point- # represents a distinct operation; do not reuse one global idempotency key.- key = 'qoder-collaboration-disable-' + hashlib.sha256(encoded(restore_ref)).hexdigest()[:16]- status = apply_collaboration(product, context, {'intent': 'restore', 'restore_point_ref': restore_ref},- key)- assert (status['state'] == 'restored' and status.get('current_selection') is None- and status.get('restore_point_ref') is None), \- 'collaboration disable did not restore and release its current selection/reference'- if before is None:- assert not skill.exists(), 'product left its owned collaboration Skill installed'- else:- assert skill.read_bytes() == before, 'product removed or rewrote a borrowed user Skill'---def finish_collaboration(product, sources, restore, report, stage, primary_failure):- """Restore before stopping the service; preserve the first business failure."""- errors = []- if restore is not None:- try:- if product.process is None:- product.start()- restore()- report['restore_after_failure'] = {'state': 'succeeded'}- except Exception as error:- errors.append({'step': 'restore_collaboration', 'error_type': type(error).__name__})- report['restore_after_failure'] = {'state': 'red'}- if primary_failure or errors:- report['cleanup_failures'] = list(errors)- try:- report_failure(product, report, stage)- except Exception as error:- errors.append({'step': 'preserve_failure_report', 'error_type': type(error).__name__})- # Try every independently owned cleanup even when another fails. Never remove- # user material directly to compensate for a failed product Restore.- actions = [('close_product', product.close),- ('cleanup_owned_receipts', lambda: qoder_native_context.cleanup_context(product))]- actions.extend(('close_source', source.close) for source in sources)- for step, action in actions:- try:- action()- except Exception as error:- errors.append({'step': step, 'error_type': type(error).__name__})- if errors:- print(json.dumps({'scenario': 'qoder-collaboration-cleanup', 'state': 'red',- 'candidate': report['candidate'], 'failures': errors,- 'primary_failure_preserved': primary_failure}), flush=True)- if not primary_failure:- raise AssertionError('Qoder collaboration cleanup failed; inspect the cleanup report')---def run(repository, candidate):- repo = Path(repository).resolve()- assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate- product = Product(repo)- sources = []- fixture = None- context = restore_ref = None- restored = False- skill = None- before_skill = None- primary_failure = False- oracle = None- stage = 'explicit-qoder-context'- report = dict(scenario='qoder-main-agent-delegation', candidate=candidate, worker_harness='qoder',- required_cases=list(CASES), selected_cases=list(CASES), cases=[],- evidence_limit='Real main Agent, user Skill, public CLI, daemon, Gateway and Worker; synthetic models; no Desktop verdict')- try:- binary, _, _ = selected_installation('qoder')- (product.root / 'bin/qodercli').symlink_to(binary)- fixture, worker_source = prepare_product(product, 'qoder')- report['source_context_tokens'] = fixture['source_context_tokens']- sources.append(worker_source)- configure_worker_installation(product, 'qoder_cli', None, binary, None)- fixture['main_marker'] = 'QODER-MAIN-' + secrets.token_hex(12)- fixture['artifact'] = dict(path=str(product.project / 'delegated-native-artifact.txt'),- receipt='QODER-WORKER-' + secrets.token_hex(16))- (product.root / 'native-context.json').write_text(json.dumps(fixture))- worker_source.reply = worker_decision- skill = qoder_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- stage = 'native-collaboration-preflight'- check_collaboration(product, 'qoder-preflight')- scan = product.preview('agents scan')- agents = [agent for agent in scan['agents'] if agent['agent_id'] == AGENT]- assert len(agents) == 1, 'Qoder installation/context was not discovered'- context = agents[0]['context_id']- stage = 'install-real-user-collaboration-skill'- status = apply_collaboration(product, context,- {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'qoder-collaboration-enable')- assert status['state'] == 'configured' and status['current_selection']['trigger_mode'] == 'explicit', status- restore_ref = status['restore_point_ref']- assert restore_ref and skill.is_file(), 'configured collaboration has no owned restore reference/Skill'- assert not (product.project / '.qoder/skills/hiroute-collaboration').exists(), 'project Skill shadows user target'- stage = 'verify-installed-user-skill'- check_collaboration(product, 'qoder-installed-user-skill')- qoder_native_context.assert_settings_preserved(fixture)- controls = product.root / 'main-agent-source'- controls.mkdir(mode=0o700)- (controls / 'native-context.json').write_text('{}')- main_source = NativeContextUpstream(controls)- sources.append(main_source)- main_source.token, main_source.model = 'synthetic-main-agent-only-token', 'main-agent/receipt:v1'- oracle = MainAgentOracle(fixture, skill, product.bin / 'hiroute', lambda: source_events(worker_source))- main_source.reply = oracle.reply- stage = 'real-main-agent-to-worker'- run_main_agent(product, binary, main_source, fixture)- assert oracle.user_skill_proved and oracle.completed, 'main Agent oracle did not complete all stages'- assert all(event['state'] == 'green' for source in sources for event in source_events(source))- fixture['task_id'] = oracle.accepted['task_id']- 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=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, native_context_setup='explicit-borrowed-login-context')- report['cases'].extend({'id': case, 'state': 'green'} for case in CASES[:2])- assert_preserved(fixture)- stage = 'disable-only-owned-collaboration-skill'- restore_skill(product, context, restore_ref, before_skill, skill)- restored = True- qoder_native_context.assert_settings_preserved(fixture)- report['cases'].append({'id': CASES[2], 'state': 'green'})- product.stop()- diagnostics = product.diagnostics_snapshot()- assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'- report.update(state='green', user_settings_unchanged=True, diagnostics=diagnostics,- binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},- harness_sha256=digest(binary))- except Exception:- primary_failure = True- if oracle is not None:- report['main_observations'] = {- 'actual_user_skill_proved': oracle.user_skill_proved,- 'requests': oracle.requests,- 'completed': oracle.completed,- 'public_worker_result': ({key: oracle.accepted.get(key)- for key in ('task_id', 'run_id', 'run_state')}- if oracle.accepted is not None else None),- }- raise- finally:- restore = None- if restore_ref and not restored:- restore = lambda: restore_skill(product, context, restore_ref, before_skill, skill)- finish_collaboration(product, sources, restore, report, stage, primary_failure)- print(json.dumps(report), flush=True)--+from collaboration_product import check_collaboration, apply_collaboration, restore_skill, runif __name__ == '__main__':run(sys.argv[1], sys.argv[2])diff --git a/crates/daemon/tests/support/qoder_compaction_product.py b/crates/daemon/tests/support/qoder_compaction_product.pyindex e878de28..460e4157 100644--- a/crates/daemon/tests/support/qoder_compaction_product.py+++ b/crates/daemon/tests/support/qoder_compaction_product.py@@ -1,164 +1,5 @@-"""Automatic native compaction stays on the real Worker's frozen Gateway route.--The synthetic usage receipt triggers Qoder's own compactor inside one public-Worker execution. This is separate from the no-probe Continue/Skill journey.-"""-import json-from pathlib import Path-import secrets-import shlex-import subprocess+"""Qoder entry to the shared native compaction product journey."""import sys--from delegation_product import configure_worker_installation, wait_for_worker_result, worker_cli-from native_context_boundaries import source_events-from native_context_fixture import (assert_preserved, digest, is_native_compaction, native_text,- protect_configuration, tool_results, write_new)-from native_context_product import (exact_history, prepare_product, report_failure,- selected_installation, wait_for_resumable_task)-from publication_product import Product-import qoder_native_context---CASES = ('worker.context.tool-summary-route', 'worker.context.compaction-route')-CONTEXT_TOKENS = 100_000-PRESSURE_TOKENS = 90_000---class CompactionOracle:- def __init__(self, fixture, upstream_model):- self.fixture, self.model = fixture, upstream_model- self.main_requests = self.compact_requests = self.tool_summary_requests = 0- self.tool_receipt = 'NATIVE-TOOL-' + secrets.token_hex(12)- self.summary_receipt = 'NATIVE-COMPACT-' + secrets.token_hex(12)- self.tool_summary_receipt = 'NATIVE-TOOL-SUMMARY-' + secrets.token_hex(12)-- def reply(self, _fixture, body):- assert body.get('model') == self.model, 'compaction or main request changed the frozen upstream model'- results = tool_results(body, 'qoder')- items = body.get('input', [])- last = native_text(items[-1]) if isinstance(items, list) and items else native_text(items)- if 'tool output' in last.lower() and 'summar' in last.lower() and self.tool_receipt in last:- assert self.main_requests == 1 and self.tool_summary_requests == 0, 'unexpected native tool summarization'- self.tool_summary_requests += 1- return dict(kind='text', request_kind='tool_summary', input_tokens=30,- text=self.tool_summary_receipt + ': The read-only tool returned ' + self.tool_receipt)- if is_native_compaction(body):- assert self.main_requests == 1 and self.compact_requests == 0, 'unexpected or repeated native compaction'- assert self.tool_summary_requests == 1 and self.tool_summary_receipt in results.get('native_compaction_tool', ''), \- 'native compaction omitted the correlated summarized tool receipt'- assert self.summary_receipt not in native_text(body), 'summary receipt was present before compaction'- self.compact_requests += 1- return dict(kind='text', request_kind='compact', input_tokens=30,- text='<analysis>Local routing acceptance only.</analysis><summary>' +- self.summary_receipt + ': The read-only tool returned ' + self.tool_summary_receipt +- '. Finish the requested native routing receipt.</summary>')- self.main_requests += 1- assert self.main_requests <= 3, 'unexpected native main request'- if self.main_requests == 1:- assert self.fixture['compaction_prompt'] in native_text(body), 'unknown native task'- return dict(kind='tool', request_kind='main', id='native_compaction_tool', name='Bash',- arguments={'command': '/bin/sh ' + shlex.quote(self.fixture['compaction_script']),- 'timeout': 10000}, input_tokens=PRESSURE_TOKENS)- assert (self.compact_requests == 1 and self.summary_receipt in native_text(body)- and self.tool_summary_receipt in native_text(body)), \- 'main request did not consume the actual native summary'- return dict(kind='text', request_kind='main', input_tokens=30,- text='compacted-' + self.fixture['receipt'])---def assert_native_compaction(path, summary_receipt):- rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line]- boundaries = [row.get('compactMetadata', {}) for row in rows if row.get('subtype') == 'compact_boundary']- assert any(item.get('trigger') == 'auto' and item.get('preTokens', 0) >= PRESSURE_TOKENS- for item in boundaries), 'native history has no actual automatic compaction boundary'- assert any(row.get('isCompactSummary') and summary_receipt in json.dumps(row) for row in rows), \- 'exact native session did not persist the independently issued summary'- return [{'trigger': item.get('trigger'), 'pre_tokens': item.get('preTokens'),- 'post_tokens': item.get('postTokens')} for item in boundaries]---def run(repository, candidate):- repo = Path(repository).resolve()- assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate- product, upstream = Product(repo), None- stage = 'prepare-frozen-worker-source'- report = dict(scenario='qoder-worker-compaction-route', candidate=candidate, worker_harness='qoder',- required_cases=list(CASES), selected_cases=list(CASES), cases=[],- evidence_limit='Real Plan/admission/profile/native Worker/Gateway; controlled upstream; no Desktop verdict')- try:- fixture, upstream = prepare_product(product, 'qoder', context_tokens=CONTEXT_TOKENS)- report['source_context_tokens'] = fixture['source_context_tokens']- binary, _, _ = selected_installation('qoder')- configure_worker_installation(product, 'qoder_cli', None, binary, None)- project_settings = product.project / '.qoder/settings.json'- settings = json.loads(project_settings.read_text())- settings['experimental'] = {'contextManagement': True}- settings['model']['summarizeToolOutput'] = {'Bash': {'tokenBudget': 2000}}- project_settings.write_text(json.dumps(settings))- protect_configuration(fixture, [project_settings])- fixture['compaction_prompt'] = 'QODER-COMPACTION-' + secrets.token_hex(12)- fixture['compaction_script'] = str(product.project / 'native-compaction-receipt.sh')- oracle = CompactionOracle(fixture, upstream.model)- script = Path(fixture['compaction_script'])- write_new(script, '#!/bin/sh\ni=0\nwhile [ "$i" -lt 300 ]; do\n' +- ' /usr/bin/printf "%s\\n" ' + shlex.quote(oracle.tool_receipt) +- '\n i=$((i + 1))\ndone\n', executable=True)- protect_configuration(fixture, [script])- (product.root / 'native-context.json').write_text(json.dumps(fixture))- upstream.reply = oracle.reply- stage = 'automatic-compaction-in-real-worker'- command = ('worker exec --plan ' + product.plan_id + ' --cwd ' + str(product.project) +- ' --run-timeout 120 --no-wait --submission-key qoder-compaction --file - --output json')- _, accepted = worker_cli(product, command,- fixture['compaction_prompt'] + ': Execute the requested read-only receipt tool, then finish the task.')- first = accepted['data']- fixture['task_id'] = first['task_id']- result = wait_for_worker_result(product, first['run_id'], timeout=150)- assert 'compacted-' + fixture['receipt'] in result['result'], 'missing compacted Worker result'- wait_for_resumable_task(product, first['task_id'], first['run_id'])- history = exact_history(fixture)- report['native_compaction_boundaries'] = assert_native_compaction(history[0], oracle.summary_receipt)- stage = 'continue-native-compacted-history'- command = ('worker continue --task ' + first['task_id'] + ' --expected-latest-run ' + first['run_id'] +- ' --run-timeout 120 --no-wait --submission-key qoder-compaction-continue --file - --output json')- _, accepted = worker_cli(product, command, 'Continue the same native task using its compacted summary.')- continued = accepted['data']- result = wait_for_worker_result(product, continued['run_id'], timeout=150)- assert 'compacted-' + fixture['receipt'] in result['result']- wait_for_resumable_task(product, first['task_id'], continued['run_id'])- assert exact_history(fixture) == history, 'compacted Continue changed the exact native session'- assert oracle.main_requests == 3 and oracle.compact_requests == oracle.tool_summary_requests == 1, \- 'required native request kinds missing'- attempts = source_events(upstream)- assert [event.get('request_kind') for event in attempts] == ['main', 'tool_summary', 'compact', 'main', 'main'], attempts- assert all(event['state'] == 'green' and event['model'] == upstream.model for event in attempts)- assert_preserved(fixture)- qoder_native_context.assert_settings_preserved(fixture)- product.stop()- diagnostics = product.diagnostics_snapshot()- assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'- report.update(state='green', cases=[{'id': case, 'state': 'green'} for case in CASES], task_id=first['task_id'],- run_ids=[first['run_id'], continued['run_id']], native_session_id=history[1],- main_requests=oracle.main_requests, compact_requests=oracle.compact_requests,- tool_summary_requests=oracle.tool_summary_requests,- upstream_model=upstream.model, foreign_requests=0, diagnostics=diagnostics,- binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},- harness_sha256=digest(binary))- print(json.dumps(report), flush=True)- except Exception:- report_failure(product, report, stage)- raise- finally:- try:- product.close()- finally:- try:- qoder_native_context.cleanup_context(product)- finally:- if upstream:- upstream.close()--+from native_compaction_product import runif __name__ == '__main__':run(sys.argv[1], sys.argv[2])diff --git a/crates/daemon/tests/support/qoder_model_fixture.py b/crates/daemon/tests/support/qoder_model_fixture.pyindex 348c2406..d12d25e2 100644--- a/crates/daemon/tests/support/qoder_model_fixture.py+++ b/crates/daemon/tests/support/qoder_model_fixture.py@@ -1,172 +1,2 @@-"""Owned Qoder settings and native reads for the persisted-model product journey.--Only this leaf may write the explicitly selected MODEL context. It never reads-authentication, and it never supplies native provider/settings/credential overrides.-"""-from copy import deepcopy-import json-import os-from pathlib import Path-import secrets-import stat--from agent_product_support import run_native_command-from native_context_fixture import native_text-from qoder_native_context import selected_directory---CASES = ('agent.models.persisted-routes', 'agent.models.credential-rotation',- 'agent.models.independent-restore', 'agent.models.default-reference-guard')-LIVE_PROMPT = 'Reply with exactly HIROUTE_LIVE_CHECK_OK. Do not use tools or perform any other action.'---def select_model_context(product):- home = 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), \- 'model acceptance requires a dedicated context, never the daily HOME/config'- product.env.update(HOME=str(home), QODER_CONFIG_DIR=str(config))- return config---class OwnedModelSettings:- """Seed a synthetic user baseline; undo only our unchanged final baseline."""- def __init__(self, config, foreign_endpoint):- self.path = Path(config) / 'settings.json'- assert not self.path.is_symlink(), 'model fixture cannot own a linked settings target'- self.original = self.path.read_bytes() if self.path.exists() else None- self.original_mode = stat.S_IMODE(self.path.stat().st_mode) if self.original is not None else None- self.baseline = json.loads(self.original) if self.original is not None else {}- assert isinstance(self.baseline, dict), 'dedicated model settings must be a JSON object'- self.baseline = deepcopy(self.baseline)- assert not {'hirouteAcceptance', 'hirouteLaterEdit'} & self.baseline.keys(), \- 'another model fixture owns this context'- providers = self.baseline.setdefault('providers', {})- assert isinstance(providers, dict) and 'fixture-native' not in providers- providers['fixture-native'] = {- 'type': 'openai-compatible', 'protocol': 'openai-responses', 'authType': 'bearer',- 'baseUrl': foreign_endpoint, 'apiKey': 'synthetic-unselected-native-key',- 'models': [{'model': 'native-default', 'contextWindow': 100000,- 'maxOutputTokens': 4096, 'capabilities': {'tools': True}}],- 'fixtureUnknownProviderKey': {'preserve': ['native', 'user']},- }- self.native_default = 'fixture-native/native-default'- self.baseline.setdefault('model', {})['name'] = self.native_default- self.baseline.setdefault('general', {})['enableAutoUpdate'] = False- self.baseline.setdefault('hooks', {})- self.baseline.setdefault('mcpServers', {})- self.baseline['hirouteAcceptance'] = {'unknown': ['preserve', secrets.token_hex(8)]}- self.write(self.baseline)-- def read(self):- assert not self.path.is_symlink() and self.path.is_file(), 'settings target was replaced'- return json.loads(self.path.read_text())-- def write(self, value):- assert not self.path.is_symlink(), 'refusing to write linked fixture settings'- self.path.write_text(json.dumps(value, indent=2) + '\n')- self.path.chmod(0o600)-- def assert_preserved(self, provider_id, selected_default=None):- actual = self.read()- actual.get('providers', {}).pop(provider_id, None)- expected = deepcopy(self.baseline)- if selected_default is not None:- expected['model']['name'] = selected_default- assert actual == expected, 'model operation changed native/default/unknown user fields'-- def add_user_edit(self, provider_id):- self.assert_preserved(provider_id)- text = self.path.read_text()- value = {'edited_after_apply': secrets.token_hex(8)}- # Add one root field without reserializing the managed provider. Otherwise- # a fixture's unrelated edit could manufacture owned-node formatting drift.- end = text.rfind('}')- updated = text[:end].rstrip() + ',\n "hirouteLaterEdit": ' + json.dumps(value) + '\n' + text[end:]- expected = self.read()- expected['hirouteLaterEdit'] = value- assert json.loads(updated) == expected, 'fixture root edit changed another field'- self.path.write_text(updated)- self.baseline['hirouteLaterEdit'] = value-- def select_default(self, expected, replacement):- actual = self.read()- assert actual['model']['name'] == expected, 'fixture default changed independently'- actual['model']['name'] = replacement- text = self.path.read_text()- token = json.dumps(expected)- assert text.count(token) == 1, 'fixture default token is ambiguous'- updated = text.replace(token, json.dumps(replacement), 1)- assert json.loads(updated) == actual, 'fixture default edit changed another field'- self.path.write_text(updated)-- def close(self):- assert self.read() == self.baseline, 'cannot undo fixture baseline while managed/drifted fields remain'- if self.original is None:- self.path.unlink()- else:- self.path.write_bytes(self.original)- self.path.chmod(self.original_mode)---class PersistedRouteOracle:- def __init__(self, model):- self.model = model- self.marker = None- self.receipt = None- self.calls = []-- def arm(self, label):- self.marker = 'PERSISTED-INPUT-' + secrets.token_hex(12)- self.receipt = 'PERSISTED-OUTPUT-' + secrets.token_hex(12)- self.label = label- return self.marker-- def reply(self, _fixture, body):- assert body['model'] == self.model, 'persisted model reached the wrong source'- text = native_text(body)- if LIVE_PROMPT in text:- self.calls.append('live-check')- return dict(kind='text', text='HIROUTE_LIVE_CHECK_OK', request_kind='live-check')- assert self.marker is not None and self.marker in text, 'unplanned persisted model request'- self.calls.append(self.label)- return dict(kind='text', text=self.receipt, request_kind=self.label)---def native_command(product, binary, selector, prompt):- # Ordinary settings precedence remains active. In particular, no --settings,- # --setting-sources or credential environment can hide a persistence defect.- return [str(binary), '--cwd', str(product.project), '--config-dir', product.env['QODER_CONFIG_DIR'],- '--model', selector, '--print', '--no-session-persistence', '--output-format', 'stream-json',- '--tools', 'Read', '--permission-mode', 'dont_ask', '--max-model-request-retries', '0',- '--max-turns', '2', '-p', prompt]---def successful_native_result(stdout, receipt):- records = []- for line in stdout.decode().splitlines():- try:- value = json.loads(line)- except ValueError:- continue- if isinstance(value, dict) and value.get('type') == 'result':- records.append(value)- assert len(records) == 1, 'expected one native Qoder terminal result'- result = records[0]- assert result.get('subtype') == 'success' and result.get('is_error') is False, \- 'native Qoder terminal result is an error'- assert result.get('result', '').strip() == receipt, 'native result lost the independent source receipt'- assert isinstance(result.get('session_id'), str) and result['session_id'], 'native result lacks session identity'- return result['session_id']---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.- stdout = run_native_command(product, command, timeout=60, label='ordinary Qoder model invocation')- assert oracle.calls[before:] == [label], 'ordinary Qoder did not make one actual persisted-route request'- native_session_id = successful_native_result(stdout, oracle.receipt)- return {'label': label, 'model': source.model, 'native_session_id': native_session_id, 'state': 'green'}+"""Qoder compatibility import for shared product fixture consumers."""+from additional_model_fixture import *diff --git a/crates/daemon/tests/support/qoder_model_product.py b/crates/daemon/tests/support/qoder_model_product.pyindex 26c58ac1..44a817f6 100644--- a/crates/daemon/tests/support/qoder_model_product.py+++ b/crates/daemon/tests/support/qoder_model_product.py@@ -1,304 +1,5 @@-"""Save additional Qoder models, then read them through ordinary native Qoder.--Uses production Local Control settings, publication and Gateway. Native starts-read only the persisted provider in a dedicated, normally logged-in test context.-The original four Worker/collaboration journeys remain separate.-"""-import hashlib-import http.client-import json-from pathlib import Path-import secrets-import subprocess+"""Qoder entry to the shared additional-provider product journey."""import sys--from model_connections_product import save_native_source-from agent_product_support import apply_settings, settings_status-from native_context_boundaries import source_events-from native_context_fixture import NativeContextUpstream, NativeProxyTrap, digest-from native_context_product import report_failure, selected_installation-from publication_process import plan_change-from publication_product import Product, encoded-from qoder_collaboration_product import AGENT, apply_collaboration, check_collaboration, restore_skill-from qoder_model_fixture import (CASES, OwnedModelSettings, PersistedRouteOracle,- read_persisted_route, select_model_context)-import qoder_native_context---def model_spec(context, plans=None, restore_ref=None, regenerate=False):- model = ({'intent': 'restore', 'restore_point_ref': restore_ref} if restore_ref else- {'intent': 'configure', 'settings': {'mode': 'qoder_additional', 'allowed_plan_ids': plans}})- return {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context, 'model': model,- 'collaboration': {'intent': 'keep'},- 'access_token': {'intent': 'regenerate' if regenerate else 'keep'}}---def apply_models(product, spec, key):- return apply_settings(product, spec, key, 'model')---def publish_source_plan(product, source, index):- saved = save_native_source(product, source, token=source.token, upstream_model_id=source.model,- variant='qoder-model-' + str(index), context_tokens=100000)- product.editor = {- 'schema': 'hiroute.plan-editor/v2', 'display_name': 'Additional Qoder route ' + str(index),- 'purpose': 'Read a persisted additional model route', 'mode': 'fixed_model',- 'candidates': [{'binding_id': saved['binding_id']}],- 'smart': {'economy': [], 'primary': [], 'primary_fallback': False,- 'reselect_on_user_message': False, 'classifier': {'kind': 'local_rules'}, 'complex_keywords': []},- 'free': {'candidates': [], 'primary': [], 'primary_fallback': False},- 'delegation_enabled': False, 'requirements': {},- 'limits': {'maximum_attempts': 1, 'request_timeout_ms': 30000, 'attempt_timeout_ms': 30000},- }- change = plan_change(product, 'create', 'qoder-model-plan-' + str(index))- preview = product.preview('routing preview', {'change': change})- product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change': change}, 'model-plan-' + str(index))- product.plan_id = preview['plan_head']['reference']['plan_id']- return {'plan_id': product.plan_id, 'alias': preview['plan_head']['model_alias']}---def assert_configured(status, plans):- assert status['state'] == 'configured' and status.get('restore_point_ref'), 'model route is not configured'- assert status['current_selection'] == {'mode': 'qoder_additional', 'allowed_plan_ids': sorted(plans)}, \- 'model selection changed the selected Plan set'---def assert_saved_aliases(settings, provider, aliases):- models = settings.read()['providers'][provider]['models']- assert len(models) == len(aliases) and {item['model'] for item in models} == set(aliases), \- 'persisted native choices do not match the selected routes'---def live_check(product, context, aliases, oracles):- status = settings_status(product, context)- targets = [target for target in status.get('live_check_targets', []) if target['surface'] == 'qoder_cli']- assert len(targets) == 1 and set(targets[0]['client_model_ids']) == set(aliases), 'live scope lost persisted routes'- check = {'agent_id': AGENT, 'scope': 'live', 'suite': 'quick', 'allow_model_call': True, 'target': targets[0]}- consent = {'change_digest': 'sha256:' + hashlib.sha256(encoded(check)).hexdigest(),- 'expected_revisions': product.control('GetClientServiceStatus', {})['data']['revisions']}- capability = product.grant('CheckAgentConnection', consent, 'qoder-persisted-live')- before = [len(oracle.calls) for oracle in oracles]- product.cli('agents check', check, capability)- status = settings_status(product, context)- assert status['model_verified'] is True and any(- row['surface'] == 'qoder_cli' and row['state'] == 'passed'- and row['applied_revision'] == status['applied_revision'] for row in status['surface_results']), \- 'real persisted-route Live check did not verify the current publication'- assert all(oracle.calls[index:] == ['live-check'] for oracle, index in zip(oracles, before)), \- 'Live verification must actually request each selected persisted route once'---def reject_gateway_request(product, token, alias, sources, expected_statuses):- before = [source.request_count() for source in sources]- client = http.client.HTTPConnection('127.0.0.1', product.port, timeout=10)- try:- client.request('POST', '/_hiroute/qoder/v1/responses', body=encoded({- 'model': alias, 'input': 'Untrusted removed route', 'max_output_tokens': 16, 'stream': True}),- headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token})- response = client.getresponse()- response.read()- assert response.status in expected_statuses, 'obsolete authority or removed alias was not rejected'- finally:- client.close()- assert [source.request_count() for source in sources] == before, 'rejected request reached a source'---def assert_default_blocks_removal(product, context, settings, provider, plans, skill):- selected = provider + '/' + plans[0]['alias']- settings.select_default(settings.native_default, selected)- try:- status = settings_status(product, context)- before, skill_before = digest(settings.path), digest(skill)- original_token = product.bearer(product.agent_connection)- for spec in (model_spec(context, [plans[1]['plan_id']]),- model_spec(context, restore_ref=status['restore_point_ref'])):- command = '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'] == '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'- assert product.bearer(product.agent_connection) == original_token, 'blocked removal changed the model token'- # Keeping the default-selected alias remains a legal user adjustment.- preview = product.preview('agents connect preview', {'spec': model_spec(context, [p['plan_id'] for p in plans])})- assert preview['applicable'], 'retaining the selected default was incorrectly rejected'- settings.assert_preserved(provider, selected_default=selected)- finally:- settings.select_default(selected, settings.native_default)---def restore_models(product, context):- current = settings_status(product, context)- _, restored = apply_models(product, model_spec(context, restore_ref=current['restore_point_ref']),- 'qoder-model-restore')- assert restored['state'] == 'not_configured' and restored.get('current_selection') is None \- and restored.get('restore_point_ref') is None, 'model Restore did not release its selection/reference'---def run(repository, candidate):- repo = Path(repository).resolve()- assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate- product = Product(repo)- sources, oracles, settings, context, skill = [], [], None, None, None- foreign = None- model_active = skill_active = False- before_skill = None- stage = 'dedicated-model-context'- report = dict(scenario='qoder-persisted-model-routes', candidate=candidate, worker_harness='qoder',- required_cases=list(CASES), selected_cases=list(CASES), cases=[], native_reads=[],- evidence_limit='Real persisted settings/native Qoder/Gateway; controlled sources; no Desktop verdict')- failed = False- cleanup_errors = []- try:- config = select_model_context(product)- binary, _, _ = selected_installation('qoder')- (product.root / 'bin/qodercli').symlink_to(binary)- foreign = NativeProxyTrap(product.root / 'unselected-native.log')- settings = OwnedModelSettings(config, foreign.url + '/v1')- product.enable_debug_diagnostics()- product.start()- plans = []- for index, model in enumerate(('gpt-5.4', 'gpt-5.5')):- controls = product.root / ('persisted-source-' + str(index))- controls.mkdir(mode=0o700)- (controls / 'native-context.json').write_text('{}')- source = NativeContextUpstream(controls)- source.model, source.token = model, 'synthetic-persisted-source-' + secrets.token_hex(12)- oracle = PersistedRouteOracle(model)- source.reply = oracle.reply- sources.append(source)- oracles.append(oracle)- plans.append(publish_source_plan(product, source, index))- agent = next(item for item in product.preview('agents scan')['agents'] if item['agent_id'] == AGENT)- context = agent['context_id']- product.agent_connection = 'agent-connection/' + context- stage = 'persist-model-routes'- plan_ids = [plan['plan_id'] for plan in plans]- preview, status = apply_models(product, model_spec(context, plan_ids), 'qoder-model-enable')- model_active = True- product.bearer(product.agent_connection) # Register the actual secret for output-leak checks immediately.- provider = preview['model_effect']['provider_id']- assert preview['model_effect']['endpoint'] == 'http://127.0.0.1:' + str(product.port) + '/_hiroute/qoder/v1'- assert_configured(status, plan_ids)- assert_saved_aliases(settings, provider, [plan['alias'] for plan in plans])- settings.assert_preserved(provider)- settings.add_user_edit(provider)- for index, plan in enumerate(plans):- report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plan['alias'],- sources[index], oracles[index], 'persisted-' + str(index)))- product.stop()- product.start()- report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],- sources[0], oracles[0], 'after-daemon-restart'))- live_check(product, context, [plan['alias'] for plan in plans], oracles)- report['cases'].append({'id': CASES[0], 'state': 'green'})-- stage = 'rotate-only-model-authority'- old_token = product.bearer(product.agent_connection)- _, status = apply_models(product, model_spec(context, plan_ids, regenerate=True), 'qoder-model-rotate')- assert_configured(status, plan_ids)- new_token = product.bearer(product.agent_connection)- assert old_token != new_token, 'model token rotation reused the prior credential'- reject_gateway_request(product, old_token, plans[0]['alias'], sources, (401, 403))- report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[1]['alias'],- sources[1], oracles[1], 'after-token-rotation'))- settings.assert_preserved(provider)- report['cases'].append({'id': CASES[1], 'state': 'green'})-- stage = 'independent-model-and-skill'- (config / 'skills').mkdir(mode=0o700, exist_ok=True)- skill = qoder_native_context.prepare_collaboration_target(product)- before_skill = skill.read_bytes() if skill.exists() else None- check_collaboration(product, 'model-skill-preflight')- collaboration = apply_collaboration(product, context,- {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'model-skill-enable')- skill_active = True- check_collaboration(product, 'model-skill-installed')- restore_skill(product, context, collaboration['restore_point_ref'], before_skill, skill)- skill_active = False- assert_configured(settings_status(product, context), plan_ids)- report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],- sources[0], oracles[0], 'after-skill-restore'))- # Restore invalidates evidence about the formerly installed Skill. A new- # configuration must prove the current capability rather than reuse it.- check_collaboration(product, 'model-skill-reenable-preflight')- collaboration = apply_collaboration(product, context,- {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'model-skill-enable-again')- skill_active = True- skill_digest = digest(skill)- assert_default_blocks_removal(product, context, settings, provider, plans, skill)- report['cases'].append({'id': CASES[3], 'state': 'green'})- _, status = apply_models(product, model_spec(context, [plan_ids[0]]), 'qoder-model-adjust')- assert_configured(status, [plan_ids[0]])- assert_saved_aliases(settings, provider, [plans[0]['alias']])- reject_gateway_request(product, product.bearer(product.agent_connection), plans[1]['alias'], sources, (403, 404))- report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],- sources[0], oracles[0], 'after-route-adjustment'))- restore_models(product, context)- model_active = False- assert settings.read() == settings.baseline, 'model Restore did not preserve unrelated user edits'- assert digest(skill) == skill_digest, 'model Restore changed the independent Skill'- remaining = settings_status(product, context)['collaboration']- assert remaining['state'] == 'configured' and remaining['restore_point_ref'] == collaboration['restore_point_ref']- check_collaboration(product, 'skill-survives-model-restore')- report['cases'].append({'id': CASES[2], 'state': 'green'})- restore_skill(product, context, remaining['restore_point_ref'], before_skill, skill)- skill_active = False- assert not foreign.path.read_text().strip(), 'native defaults or providers unexpectedly received requests'- assert all(event['state'] == 'green' for source in sources for event in source_events(source))- assert all(source.request_count() == len(source_events(source)) for source in sources), \- 'an unrecorded rejected request reached the source'- diagnostics = product.diagnostics_snapshot()- assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'- report.update(state='green', diagnostics=diagnostics, persisted_aliases=[p['alias'] for p in plans],- native_default_preserved=True, unknown_user_fields_preserved=True, foreign_requests=0,- source_requests=[source.request_count() for source in sources], live_requests=2,- source_context_tokens=100000, source_output_tokens=4096,- binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},- harness_sha256=digest(binary))- except Exception:- failed = True- raise- finally:- # Restore through production while its daemon is alive. A failed operation- # never authorizes deleting a managed provider or installed Skill directly.- for label, active, action in (- ('restore_model', model_active, lambda: restore_models(product, context)),- ('restore_skill', skill_active, lambda: restore_skill(product, context,- settings_status(product, context)['collaboration']['restore_point_ref'], before_skill, skill)),- ):- if active:- try:- if product.process is None:- product.start()- action()- except Exception as error:- cleanup_errors.append({'step': label, 'error_type': type(error).__name__})- if failed or cleanup_errors:- report['cleanup_failures'] = list(cleanup_errors)- try:- report_failure(product, report, stage)- except Exception as error:- cleanup_errors.append({'step': 'preserve_failure_report', 'error_type': type(error).__name__})- actions = [('close_product', product.close), ('owned_skill_directory', lambda: qoder_native_context.cleanup_context(product))]- if settings is not None:- actions.append(('owned_settings_baseline', settings.close))- actions.extend(('close_source', source.close) for source in sources)- if foreign is not None:- actions.append(('close_foreign', foreign.close))- for label, action in actions:- try:- action()- except Exception as error:- cleanup_errors.append({'step': label, 'error_type': type(error).__name__})- if cleanup_errors:- print(json.dumps({'scenario': 'qoder-model-cleanup', 'state': 'red', 'candidate': candidate,- 'primary_failure_preserved': failed, 'failures': cleanup_errors}), flush=True)- if not failed:- raise AssertionError('model acceptance cleanup failed')- print(json.dumps(report), flush=True)--+from additional_model_product import runif __name__ == '__main__':run(sys.argv[1], sys.argv[2])diff --git a/crates/domain/src/agents/qoder_model.rs b/crates/domain/src/agents/additional_model.rssimilarity index 82%rename from crates/domain/src/agents/qoder_model.rsrename to crates/domain/src/agents/additional_model.rsindex 583cd244..172f3a6d 100644--- a/crates/domain/src/agents/qoder_model.rs+++ b/crates/domain/src/agents/additional_model.rs@@ -61,13 +61,27 @@ pub fn validate_qoder_output_budget(tokens: u64) -> Result<(), QoderBudgetError>/// Non-secret native model declaration sealed in a settings Operation.#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]-pub struct QoderAdditionalModelV1 {+pub struct AdditionalAgentModelV1 {pub alias: String,pub context_window_tokens: u64,pub max_output_tokens: u64,}-impl QoderAdditionalModelV1 {+pub type QoderAdditionalModelV1 = AdditionalAgentModelV1;++impl AdditionalAgentModelV1 {+ pub fn validate_pi(&self) -> Result<(), crate::AgentConnectionError> {+ crate::ModelAlias::parse(&self.alias)+ .map_err(|_| crate::AgentConnectionError::InvalidGrant)?;+ if self.max_output_tokens == 0+ || self.context_window_tokens <= self.max_output_tokens+ || self.context_window_tokens > MAX_NATIVE_INTEGER+ {+ return Err(crate::AgentConnectionError::InvalidGrant);+ }+ Ok(())+ }+pub fn validate(&self) -> Result<(), crate::AgentConnectionError> {crate::ModelAlias::parse(&self.alias).map_err(|_| crate::AgentConnectionError::InvalidGrant)?;diff --git a/crates/domain/src/agents/mod.rs b/crates/domain/src/agents/mod.rsindex 1029b7f7..ec6d4e83 100644--- a/crates/domain/src/agents/mod.rs+++ b/crates/domain/src/agents/mod.rs@@ -1,5 +1,6 @@//! Exact-version Agent integration profiles and probe contracts.+mod additional_model;mod capability;mod collaboration;mod context_window;@@ -9,11 +10,11 @@ mod model_grant;mod native_artifacts;mod plan_references;mod profile;-mod qoder_model;mod settings;mod skill_installation;mod surface_check;+pub use additional_model::*;pub use capability::*;pub use collaboration::*;pub use context_window::*;@@ -23,7 +24,6 @@ pub use model_grant::*;pub use native_artifacts::*;pub use plan_references::*;pub use profile::*;-pub use qoder_model::*;pub use settings::*;pub use skill_installation::*;pub use surface_check::*;diff --git a/crates/domain/src/agents/model_grant.rs b/crates/domain/src/agents/model_grant.rsindex 93afe5d9..688ccf07 100644--- a/crates/domain/src/agents/model_grant.rs+++ b/crates/domain/src/agents/model_grant.rs@@ -78,7 +78,8 @@ impl AgentModelGrantV2 {(selection, protocol),(AgentModelSelectionV2::CodexDefault { .. }- | AgentModelSelectionV2::QoderAdditional { .. },+ | AgentModelSelectionV2::QoderAdditional { .. }+ | AgentModelSelectionV2::PiAdditional { .. },AgentIngressProtocolV1::Responses) | (AgentModelSelectionV2::ClaudeLauncher { .. },@@ -253,7 +254,8 @@ impl AgentModelGrantV2 {(selection, self.protocol),(AgentModelSelectionV2::CodexDefault { .. }- | AgentModelSelectionV2::QoderAdditional { .. },+ | AgentModelSelectionV2::QoderAdditional { .. }+ | AgentModelSelectionV2::PiAdditional { .. },AgentIngressProtocolV1::Responses) | (AgentModelSelectionV2::ClaudeLauncher { .. },diff --git a/crates/domain/src/agents/profile.rs b/crates/domain/src/agents/profile.rsindex 33757bdc..54751a4b 100644--- a/crates/domain/src/agents/profile.rs+++ b/crates/domain/src/agents/profile.rs@@ -14,6 +14,7 @@ pub enum AgentKindV1 {Codex,ClaudeCode,Qoder,+ Pi,}impl AgentKindV1 {@@ -35,6 +36,12 @@ impl AgentKindV1 {ConfigLayerV1::Project,ConfigLayerV1::User,],+ Self::Pi => &[+ ConfigLayerV1::Process,+ ConfigLayerV1::Launch,+ ConfigLayerV1::Project,+ ConfigLayerV1::User,+ ],Self::Qoder => &[ConfigLayerV1::Process,ConfigLayerV1::Local,@@ -49,6 +56,7 @@ impl AgentKindV1 {Self::Codex => "codex",Self::ClaudeCode => "claude_code",Self::Qoder => "qoder",+ Self::Pi => "pi",}}}@@ -205,7 +213,7 @@ impl AgentProfileV1 {if self.config_precedence.as_slice() != self.kind.config_precedence() {return Err(AgentProfileError::InvalidConfigPrecedence);}- if self.kind == AgentKindV1::Qoder+ if matches!(self.kind, AgentKindV1::Qoder | AgentKindV1::Pi)&& (self.dynamic_catalog|| self.static_catalog_fallback|| self.native_subagent_routing@@ -246,7 +254,10 @@ impl AgentProfileV1 {return Err(AgentProfileError::InvalidManagedLaunch);}match (self.kind, self.ingress_protocol) {- (AgentKindV1::Codex | AgentKindV1::Qoder, Some(AgentIngressProtocolV1::Responses))+ (+ AgentKindV1::Codex | AgentKindV1::Qoder | AgentKindV1::Pi,+ Some(AgentIngressProtocolV1::Responses),+ )| (AgentKindV1::ClaudeCode, Some(AgentIngressProtocolV1::Messages)) => Ok(()),_ => Err(AgentProfileError::ProtocolKindMismatch),}diff --git a/crates/domain/src/agents/settings.rs b/crates/domain/src/agents/settings.rsindex 17faff42..41e7627a 100644--- a/crates/domain/src/agents/settings.rs+++ b/crates/domain/src/agents/settings.rs@@ -26,6 +26,9 @@ pub enum AgentModelSelectionV2 {allowed_plan_ids: BTreeSet<AgentPlanId>,default_selection: AgentModelDefaultSelectionV2,},+ PiAdditional {+ allowed_plan_ids: BTreeSet<AgentPlanId>,+ },QoderAdditional {allowed_plan_ids: BTreeSet<AgentPlanId>,},@@ -50,6 +53,7 @@ pub enum AgentModelSurfaceV2 {CodexDesktop,ClaudeCli,QoderCli,+ PiCli,}#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]@@ -96,7 +100,7 @@ impl AgentModelSelectionV2 {Self::CodexDefault { fixed_models, .. } | Self::ClaudeLauncher { fixed_models, .. } => {fixed_models}- Self::QoderAdditional { .. } => &[],+ Self::QoderAdditional { .. } | Self::PiAdditional { .. } => &[],}}@@ -105,7 +109,8 @@ impl AgentModelSelectionV2 {Self::CodexDefault {allowed_plan_ids, ..}- | Self::QoderAdditional { allowed_plan_ids } => allowed_plan_ids.clone(),+ | Self::QoderAdditional { allowed_plan_ids }+ | Self::PiAdditional { allowed_plan_ids } => allowed_plan_ids.clone(),Self::ClaudeLauncher {preset_mappings, ..} => [@@ -154,7 +159,7 @@ impl AgentModelSelectionV2 {AgentModelDefaultSelectionV2::Plan { plan_id } if plans.contains(plan_id) => {}_ => return Err(invalid),},- Self::QoderAdditional { .. } => {}+ Self::QoderAdditional { .. } | Self::PiAdditional { .. } => {}Self::ClaudeLauncher { surfaces, .. } => {if *surfaces != BTreeSet::from([AgentModelSurfaceV2::ClaudeCli]) {return Err(invalid);diff --git a/crates/domain/src/delegation/installation.rs b/crates/domain/src/delegation/installation.rsindex 5b0b60a0..71f44d55 100644--- a/crates/domain/src/delegation/installation.rs+++ b/crates/domain/src/delegation/installation.rs@@ -12,6 +12,11 @@ pub enum WorkerLaunchFormV1<'a> {NativeAcp {cli: &'a str,},+ /// A product-owned ACP bridge loads the SDK adjacent to this official npm CLI.+ NativeSdk {+ cli: &'a str,+ node: &'a str,+ },}impl<'a> WorkerLaunchFormV1<'a> {@@ -38,6 +43,11 @@ impl<'a> WorkerLaunchFormV1<'a> {Ok(Self::NativeAcp { cli })}WorkerHarnessV1::QoderCli => Err(invalid()),+ WorkerHarnessV1::Pi if adapter.is_none() => Ok(Self::NativeSdk {+ cli,+ node: node.ok_or_else(invalid)?,+ }),+ WorkerHarnessV1::Pi => Err(invalid()),}}}diff --git a/crates/domain/src/delegation/mod.rs b/crates/domain/src/delegation/mod.rsindex 927a8871..3fb2a558 100644--- a/crates/domain/src/delegation/mod.rs+++ b/crates/domain/src/delegation/mod.rs@@ -48,6 +48,7 @@ pub enum WorkerHarnessV1 {CodexCli,ClaudeCode,QoderCli,+ Pi,}#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]diff --git a/crates/domain/src/operation/mod.rs b/crates/domain/src/operation/mod.rsindex cbeb4f38..1ff1654c 100644--- a/crates/domain/src/operation/mod.rs+++ b/crates/domain/src/operation/mod.rs@@ -841,6 +841,7 @@ impl TransactionPlanV1 {let harness = change.after_selection.harness;let resource = match harness {crate::delegation::WorkerHarnessV1::QoderCli => "worker-dependency-selection/qoder_cli",+ crate::delegation::WorkerHarnessV1::Pi => "worker-dependency-selection/pi",crate::delegation::WorkerHarnessV1::CodexCli => "worker-dependency-selection/codex_cli",crate::delegation::WorkerHarnessV1::ClaudeCode => {"worker-dependency-selection/claude_code"diff --git a/crates/domain/src/routing/gateway_execution.rs b/crates/domain/src/routing/gateway_execution.rsindex 01ba00b1..b5f0e65b 100644--- a/crates/domain/src/routing/gateway_execution.rs+++ b/crates/domain/src/routing/gateway_execution.rs@@ -346,6 +346,46 @@ pub struct GatewayNativeReasoningFieldAssignmentV1 {pub value: GatewayNativeReasoningValueV1,}+impl GatewayNativeReasoningFieldAssignmentV1 {+ /// Current native wire locations shared by the renderer and its consumers.+ pub fn parameter_path(parameter: &str, protocol: UpstreamProtocol) -> Vec<String> {+ match (protocol, parameter) {+ (UpstreamProtocol::Responses, "reasoning_effort") => {+ vec!["reasoning".into(), "effort".into()]+ }+ (UpstreamProtocol::Responses, "thinking_budget") => {+ vec!["reasoning".into(), "max_output_tokens".into()]+ }+ (UpstreamProtocol::Messages, "thinking_budget") => {+ vec!["thinking".into(), "budget_tokens".into()]+ }+ _ => parameter.split('.').map(str::to_owned).collect(),+ }+ }++ /// Match a binary native switch, including protocol-owned string controls.+ pub fn matches_toggle_wire(&self, protocol: UpstreamProtocol, enabled: bool) -> bool {+ let string_value = |path: [&str; 2], value: &str| {+ self.path.iter().map(String::as_str).eq(path)+ && matches!(&self.value, GatewayNativeReasoningValueV1::String(actual) if actual == value)+ };+ match &self.value {+ GatewayNativeReasoningValueV1::Bool(value) => *value == enabled,+ GatewayNativeReasoningValueV1::String(_) => match protocol {+ UpstreamProtocol::Responses => string_value(+ ["reasoning", "effort"],+ if enabled { "high" } else { "none" },+ ),+ UpstreamProtocol::Messages | UpstreamProtocol::ChatCompletions => string_value(+ ["thinking", "type"],+ if enabled { "enabled" } else { "disabled" },+ ),+ },+ GatewayNativeReasoningValueV1::U64(_) => false,+ }+ }+}+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]pub enum GatewayNativeReasoningRenderV1 {@@ -630,7 +670,9 @@ fn reasoning_profile_matches(GatewayNativeReasoningRenderV1::NoControlParameter,) => profile.profile_id == *fixed,(- ExactNativeReasoningV1::Toggle { enabled, .. },+ ExactNativeReasoningV1::Toggle {+ parameter, enabled, ..+ },GatewayReasoningControlKindV1::Toggle,GatewayNativeReasoningRenderV1::ExactFields {protocol: rendered,@@ -641,7 +683,7 @@ fn reasoning_profile_matches(&& *rendered == protocol&& fields.iter()- .any(|field| field.value == GatewayNativeReasoningValueV1::Bool(*enabled))+ .any(|field| toggle_field_matches(field, parameter, *enabled, protocol))}(ExactNativeReasoningV1::Profile {@@ -679,6 +721,28 @@ fn reasoning_profile_matches(}}+fn toggle_field_matches(+ field: &GatewayNativeReasoningFieldAssignmentV1,+ parameter: &str,+ enabled: bool,+ protocol: UpstreamProtocol,+) -> bool {+ match (protocol, parameter) {+ (UpstreamProtocol::Responses, "enable_thinking" | "deepseek_thinking")+ | (UpstreamProtocol::Messages, "enable_thinking" | "deepseek_thinking")+ | (UpstreamProtocol::ChatCompletions, "deepseek_thinking") => {+ matches!(field.value, GatewayNativeReasoningValueV1::String(_))+ && field.matches_toggle_wire(protocol, enabled)+ }+ _ => {+ field.path+ == GatewayNativeReasoningFieldAssignmentV1::parameter_path(parameter, protocol)+ && matches!(field.value, GatewayNativeReasoningValueV1::Bool(_))+ && field.matches_toggle_wire(protocol, enabled)+ }+ }+}+pub(super) fn valid_executable_endpoint(value: &str) -> bool {let Some(rest) = value.strip_prefix("https://") else {return false;@@ -821,4 +885,121 @@ mod tests {UpstreamProtocol::Responses));}++ #[test]+ fn native_toggle_selection_matches_exact_protocol_wire_values() {+ for (parameter, protocol, path, values) in [+ (+ "enable_thinking",+ UpstreamProtocol::Responses,+ "reasoning.effort",+ Some(["none", "high"]),+ ),+ (+ "deepseek_thinking",+ UpstreamProtocol::Responses,+ "reasoning.effort",+ Some(["none", "high"]),+ ),+ (+ "enable_thinking",+ UpstreamProtocol::Messages,+ "thinking.type",+ Some(["disabled", "enabled"]),+ ),+ (+ "deepseek_thinking",+ UpstreamProtocol::Messages,+ "thinking.type",+ Some(["disabled", "enabled"]),+ ),+ (+ "deepseek_thinking",+ UpstreamProtocol::ChatCompletions,+ "thinking.type",+ Some(["disabled", "enabled"]),+ ),+ (+ "enable_thinking",+ UpstreamProtocol::ChatCompletions,+ "enable_thinking",+ None,+ ),+ (+ "custom_toggle",+ UpstreamProtocol::Responses,+ "custom_toggle",+ None,+ ),+ (+ "reasoning_effort",+ UpstreamProtocol::Responses,+ "reasoning.effort",+ None,+ ),+ (+ "thinking_budget",+ UpstreamProtocol::Responses,+ "reasoning.max_output_tokens",+ None,+ ),+ (+ "thinking_budget",+ UpstreamProtocol::Messages,+ "thinking.budget_tokens",+ None,+ ),+ ] {+ for enabled in [false, true] {+ let value = |enabled: bool| {+ values.map_or(GatewayNativeReasoningValueV1::Bool(enabled), |values| {+ GatewayNativeReasoningValueV1::String(values[usize::from(enabled)].into())+ })+ };+ let mut profile = GatewayReasoningProfileCapabilityV1 {+ profile_id: if enabled { "enabled" } else { "disabled" }.into(),+ control_kind: GatewayReasoningControlKindV1::Toggle,+ render: GatewayNativeReasoningRenderV1::ExactFields {+ protocol,+ fields: vec![GatewayNativeReasoningFieldAssignmentV1 {+ path: path.split('.').map(str::to_owned).collect(),+ value: value(enabled),+ }],+ },+ accounting: GatewayReasoningAccountingV1::WithinOutputCap,+ additional_reservation_tokens: 0,+ };+ let exact = ExactNativeReasoningV1::Toggle {+ parameter: parameter.into(),+ enabled,+ render_mode: ReasoningRenderModeV1::ExplicitNative,+ };+ assert!(+ reasoning_profile_matches(&profile, &exact, protocol),+ "{parameter} {protocol:?} {enabled}"+ );+ let other_protocol = if protocol == UpstreamProtocol::Responses {+ UpstreamProtocol::Messages+ } else {+ UpstreamProtocol::Responses+ };+ assert!(!reasoning_profile_matches(&profile, &exact, other_protocol));+ let GatewayNativeReasoningRenderV1::ExactFields { fields, .. } =+ &mut profile.render+ else {+ unreachable!()+ };+ fields[0].value = value(!enabled);+ assert!(!reasoning_profile_matches(&profile, &exact, protocol));+ let GatewayNativeReasoningRenderV1::ExactFields { fields, .. } =+ &mut profile.render+ else {+ unreachable!()+ };+ fields[0].value = value(enabled);+ fields[0].path = vec!["unrelated".into()];+ assert!(!reasoning_profile_matches(&profile, &exact, protocol));+ }+ }+ }}diff --git a/crates/gateway/src/adapters/ingress.rs b/crates/gateway/src/adapters/ingress.rsindex 2ed57fa4..c9cb4430 100644--- a/crates/gateway/src/adapters/ingress.rs+++ b/crates/gateway/src/adapters/ingress.rs@@ -178,7 +178,7 @@ fn decode_responses(if let Some(metadata) = internal_metadata {responses_internal_chat_message_metadata.insert(message_index, metadata);}- if item_type == Some("message")+ if matches!(item_type, Some("message") | None)&& let Some(phase) = responses_options::message_phase(context, item)?{responses_message_phases.insert(message_index, phase);diff --git a/crates/gateway/src/adapters/responses_ingress.rs b/crates/gateway/src/adapters/responses_ingress.rsindex e2fbfb6a..59bfbb1c 100644--- a/crates/gateway/src/adapters/responses_ingress.rs+++ b/crates/gateway/src/adapters/responses_ingress.rs@@ -9,7 +9,12 @@ pub(super) fn decode_responses_input(let object = value.as_object().ok_or(ModelIrError::InvalidField("input[]"))?;- let item_type = required_string(object, "type")?;+ // Responses EasyInputMessage omits this optional discriminator. The message arm+ // still validates role/content and unknown fields; explicit malformed types fail.+ let item_type = match object.get("type") {+ None => "message".to_owned(),+ Some(_) => required_string(object, "type")?,+ };match item_type.as_str() {"message" => {ensure_keys(diff --git a/crates/gateway/src/adapters/tests/native_responses.rs b/crates/gateway/src/adapters/tests/native_responses.rsindex 41d2b0ec..1d006327 100644--- a/crates/gateway/src/adapters/tests/native_responses.rs+++ b/crates/gateway/src/adapters/tests/native_responses.rs@@ -1,5 +1,45 @@use super::*;+#[test]+fn responses_easy_input_messages_preserve_the_same_context_as_explicit_messages() {+ let input = json!([+ {"role":"system","content":"routing rules"},+ {"role":"user","content":[{"type":"input_text","text":"inspect the file"}]},+ {"role":"assistant","content":"done","phase":"final_answer"}+ ]);+ let mut explicit = input.clone();+ for message in explicit.as_array_mut().unwrap() {+ message["type"] = "message".into();+ }+ let decode = |input| {+ decode_ingress_request(+ IngressProtocol::Responses,+ &json!({"model":"alias","input":input}),+ )+ };+ let mut easy = decode(input.clone()).unwrap();+ let mut typed = decode(explicit.clone()).unwrap();+ assert_eq!(+ easy.native_body.take(),+ Some(json!({"model":"alias","input":input}))+ );+ assert_eq!(+ typed.native_body.take(),+ Some(json!({"model":"alias","input":explicit}))+ );+ assert_eq!(+ easy, typed,+ "Equivalent messages preserve canonical context and metadata"+ );+ for invalid in [+ json!({"role":"user"}),+ json!({"content":"no role"}),+ json!({"type":null,"role":"user","content":"bad type"}),+ ] {+ assert!(decode(json!([invalid])).is_err());+ }+}+#[test]fn responses_previous_response_id_has_an_explicit_http_boundary() {for body in [diff --git a/crates/gateway/src/dispatch/run.rs b/crates/gateway/src/dispatch/run.rsindex e957b1d4..b34c85a7 100644--- a/crates/gateway/src/dispatch/run.rs+++ b/crates/gateway/src/dispatch/run.rs@@ -62,7 +62,10 @@ impl RunObservationMetadata {if value.plan_revision == 0|| !valid_observation_reference(&value.plan_id)|| !valid_observation_reference(&value.publication_ref)- || !matches!(value.harness_id.as_str(), "codex" | "claude" | "qoder")+ || !matches!(+ value.harness_id.as_str(),+ "codex" | "claude" | "qoder" | "pi"+ )|| [&value.native_session_id,&value.parent_context_ref,diff --git a/crates/gateway/src/profiles/reasoning.rs b/crates/gateway/src/profiles/reasoning.rsindex 525f01fb..7f8436a0 100644--- a/crates/gateway/src/profiles/reasoning.rs+++ b/crates/gateway/src/profiles/reasoning.rs@@ -20,24 +20,10 @@ pub enum ReasoningAccounting {Additive,}-/// A catalog-owned native value. Values are deliberately scalar so applying a-/// field assignment can never silently replace an unrelated native object.-#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]-#[serde(tag = "kind", content = "value", rename_all = "snake_case")]-pub enum NativeReasoningValue {- Bool(bool),- String(String),- U64(u64),-}--#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct NativeReasoningFieldAssignment {- /// Object path from the native request root, for example- /// `["thinking", "type"]`.- pub path: Vec<String>,- pub value: NativeReasoningValue,-}+pub use hiroute_domain::{+ GatewayNativeReasoningFieldAssignmentV1 as NativeReasoningFieldAssignment,+ GatewayNativeReasoningValueV1 as NativeReasoningValue,+};#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]@@ -110,10 +96,27 @@ impl ReasoningProfileCapability {|| self.accounting == ReasoningAccounting::Additive}(ReasoningControlKind::Toggle, NativeReasoningRender::ExactFields { fields, .. }) => {- !fields.is_empty()- && fields- .iter()- .any(|field| matches!(field.value, NativeReasoningValue::Bool(_)))+ let enabled = match self.profile_id.as_str() {+ "enabled" => true,+ "disabled" => false,+ // Existing custom Boolean profile names retain their contract;+ // protocol-owned strings require a precise binary identity.+ _ => {+ return fields+ .iter()+ .any(|field| matches!(field.value, NativeReasoningValue::Bool(_)));+ }+ };+ let protocol = match protocol {+ IngressProtocol::Responses => hiroute_domain::UpstreamProtocol::Responses,+ IngressProtocol::Messages => hiroute_domain::UpstreamProtocol::Messages,+ IngressProtocol::ChatCompletions => {+ hiroute_domain::UpstreamProtocol::ChatCompletions+ }+ };+ fields+ .iter()+ .any(|field| field.matches_toggle_wire(protocol, enabled))}(ReasoningControlKind::Discrete, NativeReasoningRender::ExactFields { fields, .. }) => {!fields.is_empty()@@ -173,3 +176,67 @@ fn reserved_request_field(field: &str) -> bool {| "max_tokens")}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn native_toggle_profiles_validate_protocol_switch_and_keep_custom_boolean_names() {+ for (protocol, path, values) in [+ (+ IngressProtocol::Responses,+ "reasoning.effort",+ ["none", "high"],+ ),+ (+ IngressProtocol::Messages,+ "thinking.type",+ ["disabled", "enabled"],+ ),+ (+ IngressProtocol::ChatCompletions,+ "thinking.type",+ ["disabled", "enabled"],+ ),+ ] {+ for enabled in [false, true] {+ let mut profile = ReasoningProfileCapability {+ profile_id: if enabled { "enabled" } else { "disabled" }.into(),+ control_kind: ReasoningControlKind::Toggle,+ render: NativeReasoningRender::ExactFields {+ protocol,+ fields: vec![NativeReasoningFieldAssignment {+ path: path.split('.').map(str::to_owned).collect(),+ value: NativeReasoningValue::String(+ values[usize::from(enabled)].into(),+ ),+ }],+ },+ accounting: ReasoningAccounting::WithinOutputCap,+ additional_reservation_tokens: 0,+ };+ assert!(profile.validate_for(protocol));+ profile.profile_id = if enabled { "disabled" } else { "enabled" }.into();+ assert!(!profile.validate_for(protocol));+ profile.profile_id = "custom-boolean-name".into();+ assert!(!profile.validate_for(protocol));+ let NativeReasoningRender::ExactFields { fields, .. } = &mut profile.render else {+ unreachable!()+ };+ fields[0] = NativeReasoningFieldAssignment {+ path: vec!["custom_toggle".into()],+ value: NativeReasoningValue::Bool(enabled),+ };+ assert!(profile.validate_for(protocol));+ profile.profile_id = if enabled { "enabled" } else { "disabled" }.into();+ assert!(profile.validate_for(protocol));+ let NativeReasoningRender::ExactFields { fields, .. } = &mut profile.render else {+ unreachable!()+ };+ fields[0].value = NativeReasoningValue::Bool(!enabled);+ assert!(!profile.validate_for(protocol));+ }+ }+ }+}diff --git a/crates/integrations/src/agents/qoder_native.rs b/crates/integrations/src/agents/additional_native.rssimilarity index 76%rename from crates/integrations/src/agents/qoder_native.rsrename to crates/integrations/src/agents/additional_native.rsindex bc54647b..f883a292 100644--- a/crates/integrations/src/agents/qoder_native.rs+++ b/crates/integrations/src/agents/additional_native.rs@@ -1,7 +1,9 @@//! Additional main-Agent providers. No native catalog import or default/purpose takeover.use std::collections::BTreeSet;-use hiroute_domain::{AgentAccessGrantMaterial, CanonicalDigest, QoderAdditionalModelV1};+use hiroute_domain::{+ AdditionalAgentModelV1, AgentAccessGrantMaterial, AgentKindV1, CanonicalDigest,+};use serde::{Deserialize, Serialize};use serde_json::Value;use zeroize::{Zeroize, Zeroizing};@@ -12,6 +14,10 @@ mod jsonc;use jsonc::Document;use jsonc::LIMIT;+pub(super) fn parse_native_jsonc(bytes: &[u8]) -> Result<Value, QoderNativeError> {+ Ok(Document::parse(bytes)?.root.value)+}+// This structure is serialized only into NativeAgentArtifactPort's encrypted restore envelope.// It deliberately has no Debug implementation or public JSON conversion.#[derive(Deserialize, Serialize)]@@ -38,11 +44,19 @@ pub(super) struct Edit {}pub(super) fn validate_declaration(+ kind: AgentKindV1,provider_id: &str,endpoint: &str,- models: &[QoderAdditionalModelV1],+ models: &[AdditionalAgentModelV1],) -> Result<(), QoderNativeError> {- qoder_provider::validate_model_route(provider_id, endpoint)?;+ if kind == AgentKindV1::Qoder {+ qoder_provider::validate_model_route(provider_id, endpoint)?;+ } else if kind != AgentKindV1::Pi+ || !endpoint.starts_with("http://")+ || !endpoint.ends_with("/v1")+ {+ return Err(qoder_error("additional endpoint"));+ }if provider_id.strip_prefix("hiroute-main-").is_none_or(|suffix| {@@ -59,9 +73,12 @@ pub(super) fn validate_declaration(return Err(qoder_error("additional models"));}for model in models {- model- .validate()- .map_err(|_| qoder_error("additional model"))?;+ (if kind == AgentKindV1::Pi {+ model.validate_pi()+ } else {+ model.validate()+ })+ .map_err(|_| qoder_error("additional model"))?;if !aliases.insert(&model.alias) {return Err(qoder_error("additional model alias"));}@@ -87,16 +104,20 @@ fn owned<'a>(}pub(super) fn validate_configuration(+ kind: AgentKindV1,current: Option<&[u8]>,provider_id: &str,endpoint: &str,- models: &[QoderAdditionalModelV1],+ models: &[AdditionalAgentModelV1],previous: Option<&Restore>,) -> Result<(), QoderNativeError> {- validate_declaration(provider_id, endpoint, models)?;+ validate_declaration(kind, provider_id, endpoint, models)?;let document = document(current)?;if let Some(previous) = previous {- if previous.provider_id != provider_id || !previous.applied(current)? {+ if previous.kind()? != kind+ || previous.provider_id != provider_id+ || !previous.applied(current)?+ {return Err(qoder_error("owned provider changed"));}let retain = models@@ -135,33 +156,44 @@ fn default_not_removed(}pub(super) fn configure(+ kind: AgentKindV1,current: Option<&[u8]>,provider_id: &str,endpoint: &str,- models: &[QoderAdditionalModelV1],+ models: &[AdditionalAgentModelV1],material: &AgentAccessGrantMaterial,previous: Option<&Restore>,) -> Result<Edit, QoderNativeError> {- validate_configuration(current, provider_id, endpoint, models, previous)?;+ validate_configuration(kind, current, provider_id, endpoint, models, previous)?;let base = match previous {Some(previous) => previous.remove_owned(current, false)?,None => current.map(|bytes| Zeroizing::new(bytes.to_vec())),};let credential =std::str::from_utf8(material.expose()).map_err(|_| qoder_error("local grant encoding"))?;- let models = models- .iter()- .map(|model| {- qoder_provider::model(- &model.alias,- Some(model.context_window_tokens),- model.max_output_tokens,- )- })- .collect::<Result<Vec<_>, _>>()?;- // Omit provider.model and routing. Qoder retains the selected model for auxiliary purposes;- // a multi-model provider must not redirect every purpose to its first entry.- let provider = qoder_provider::provider(endpoint, credential, models);+ let provider =+ if kind == AgentKindV1::Qoder {+ let models = models+ .iter()+ .map(|model| {+ qoder_provider::model(+ &model.alias,+ Some(model.context_window_tokens),+ model.max_output_tokens,+ )+ })+ .collect::<Result<Vec<_>, _>>()?;+ qoder_provider::provider(endpoint, credential, models)+ } else {+ let models = models.iter().map(|model| serde_json::json!({+ "id":model.alias,"name":model.alias,"reasoning":false,"input":["text"],+ "cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},+ "contextWindow":model.context_window_tokens,"maxTokens":model.max_output_tokens,+ })).collect::<Vec<_>>();+ // Pi's saved auth can replace its Bearer. The scoped custom header remains authoritative.+ serde_json::json!({"api":"openai-responses","baseUrl":endpoint,"apiKey":credential,+ "headers":{"X-HiRoute-Token":credential},"models":models})+ };let document = document(base.as_deref().map(Vec::as_slice))?;let bytes = if let Some(providers) = document.object(&document.root, "providers")? {document.edit(&providers, provider_id, Some(&provider))?@@ -173,7 +205,12 @@ pub(super) fn configure()?};let restore = Restore {- schema: "hiroute.qoder-native-restore/v1".into(),+ schema: if kind == AgentKindV1::Pi {+ "hiroute.pi-native-restore/v1"+ } else {+ "hiroute.qoder-native-restore/v1"+ }+ .into(),provider_id: provider_id.into(),provider_digest: digest(&provider)?,rendered_digest: CanonicalDigest::of_bytes(&bytes),@@ -184,6 +221,14 @@ pub(super) fn configure(}impl Restore {+ pub fn kind(&self) -> Result<AgentKindV1, QoderNativeError> {+ match self.schema.as_str() {+ "hiroute.qoder-native-restore/v1" => Ok(AgentKindV1::Qoder),+ "hiroute.pi-native-restore/v1" => Ok(AgentKindV1::Pi),+ _ => Err(qoder_error("restore schema")),+ }+ }+pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, QoderNativeError> {let header = serde_json::to_vec(self).map_err(|_| qoder_error("restore encoding"))?;let size = header@@ -211,7 +256,7 @@ impl Restore {let mut record: Self =serde_json::from_slice(&bytes[4..end]).map_err(|_| qoder_error("restore encoding"))?;record.original = bytes[end..].to_vec();- if record.schema != "hiroute.qoder-native-restore/v1"+ if record.kind().is_err()|| record.provider_id.strip_prefix("hiroute-main-")diff --git a/crates/integrations/src/agents/additional_native/README.md b/crates/integrations/src/agents/additional_native/README.mdnew file mode 100644index 00000000..d24bbddc--- /dev/null+++ b/crates/integrations/src/agents/additional_native/README.md@@ -0,0 +1,72 @@+# Additional native model routes++The shared adapter owns one `providers.hiroute-main-<context digest>` entry. The+application owns authorization, grants, publication and restore ordering; native+leaves 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) |++Main-Agent configuration adds only selected Plan aliases. It leaves native defaults,+purpose routing, extensions, hooks, MCP and Skills to their existing owners. The+Worker uses a different transient profile with one frozen route and exact budgets.+A native provider name alone never grants ownership of an existing user entry.++## Shared transaction and native leaves++- [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.+ Ambiguous duplicate keys, invalid JSON and oversized files fail closed. Line+ comments accept LF/CRLF; standalone CR and Unicode line separators are rejected+ because native readers disagree about where such comments end.+- [Artifact effects](../additional_native_effects.rs) reuse protected snapshots,+ encrypted restore records, sensitive staging and conditional replay.+- [Typed additional-model facts](../../../../daemon/src/control/runtime/settings_facts/additional_model.rs)+ assemble only dependencies used by the model intent. Collaboration-only requests+ never read the native model file or its defaults.+- [Daemon activation](../../../../daemon/src/control/runtime/native_additional_model.rs)+ checks independent native dependencies during staging, preparation, final+ activation and retry. Preview alone cannot protect against a concurrent default+ change in another file. This guard covers Pi's **user** settings; project defaults+ are native project configuration, outside the global default ownership contract.+- [Budget admission](../../../../daemon/src/control/runtime/additional_model_budget.rs)+ keeps installed declarations compatible with publication changes and blocks a+ second mutation while the original operation has a pending tail.++The prepared local grant is written only to the private native provider, mode+0600. Public journals contain no bearer or original native settings. Status reads+use the protected artifact port; restoration can still remove an owned secret+following permission drift. Preserve existing Qoder journal/restore wire strings+as registered recovery contracts; new Pi writes use its current closed kind.++## Adjustment and recovery++Reconfiguration requires the original authenticated restore record and unchanged+owned provider semantics. Unrelated user edits survive. An untouched file returns+to its exact former bytes; an edited file loses only the owned provider member.+New untouched files are removed, and harmless empty containers can remain to+preserve comments. Selecting an alias as the user default blocks removal until+that reference changes; retaining the alias while rotating a token remains valid.+A late dependency change blocks the file switch. A restore rejected before that+switch rolls back safely and needs a fresh operation. An operation whose service+activation was already sealed keeps its pending tail for retry.+Pending-tail retry requires the accepted dependency digest, including the original raw settings+bytes. A different safe default requires a fresh configuration operation; this+recovery guard does not silently authorize a revised user configuration.++The [public settings regression](../../../../daemon/src/control/runtime/settings_entry_qoder_model_tests.rs)+covers independent facets, permissions, grant secrecy, publication budgets and+late default changes. The shared [persisted-model product journey](../../../../daemon/tests/support/additional_model_product.py)+starts the actual native CLI from saved settings without provider/credential+arguments, rotates its grant, rejects removed routes, and restores model/Skill+facets separately. Unit fixtures do not prove native model calls. Neither native+protocol differences nor backend capability evidence require an extra user-facing+verification button or status badge.diff --git a/crates/integrations/src/agents/qoder_native_effects.rs b/crates/integrations/src/agents/additional_native_effects.rssimilarity index 82%rename from crates/integrations/src/agents/qoder_native_effects.rsrename to crates/integrations/src/agents/additional_native_effects.rsindex ef93cce9..5d7ebb83 100644--- a/crates/integrations/src/agents/qoder_native_effects.rs+++ b/crates/integrations/src/agents/additional_native_effects.rs@@ -1,32 +1,34 @@//! Qoder's additional provider uses the existing protected Operation artifact lifecycle.use hiroute_domain::{- AgentAccessGrantMaterial, CanonicalDigest, ExternalEffectIntentV1, NativeAgentArtifactPort,- OperationId, OwnedEffectV1, PortError, PortErrorCode, PortResult, QoderAdditionalModelV1,+ AdditionalAgentModelV1, AgentAccessGrantMaterial, AgentKindV1, CanonicalDigest,+ ExternalEffectIntentV1, NativeAgentArtifactPort, OperationId, OwnedEffectV1, PortError,+ PortErrorCode, PortResult,};use super::{QoderNativeError,+ additional_native::{self, Restore},native_effects::replay,- qoder_native::{self, Restore},};/// Only the executor receives material; this input deliberately cannot be serialized or logged.-pub struct QoderFileConfiguration<'a> {+pub struct AdditionalFileConfiguration<'a> {pub expected_content: &'a CanonicalDigest,pub provider_id: &'a str,pub endpoint: &'a str,- pub models: &'a [QoderAdditionalModelV1],+ pub models: &'a [AdditionalAgentModelV1],pub local_grant: &'a AgentAccessGrantMaterial,}/// Preview is read-only and never requires bearer bytes. The protected previous intent proves/// ownership; an identifier found in an arbitrary user document does not.-pub fn validate_qoder_configuration(+pub fn validate_additional_configuration(port: &dyn NativeAgentArtifactPort,+ kind: AgentKindV1,target: &str,provider_id: &str,endpoint: &str,- models: &[QoderAdditionalModelV1],+ models: &[AdditionalAgentModelV1],previous: Option<(&OperationId, &ExternalEffectIntentV1)>,) -> PortResult<()> {let previous = previous@@ -42,7 +44,8 @@ pub fn validate_qoder_configuration(} else {port.read_native_target(target)?};- qoder_native::validate_configuration(+ additional_native::validate_configuration(+ kind,current.as_deref().map(Vec::as_slice),provider_id,endpoint,@@ -52,8 +55,9 @@ pub fn validate_qoder_configuration(.map_err(fields_error)}-pub fn validate_qoder_restoration(+pub fn validate_additional_restoration(port: &dyn NativeAgentArtifactPort,+ kind: AgentKindV1,target: &str,original_operation: &OperationId,original_intent: &ExternalEffectIntentV1,@@ -62,13 +66,16 @@ pub fn validate_qoder_restoration(return Err(error(PortErrorCode::InvalidData, "qoder.original.target"));}let restore = load(port, original_operation, original_intent)?;+ if restore.kind().map_err(fields_error)? != kind {+ return Err(error(PortErrorCode::InvalidData, "additional.restore.kind"));+ }let current = port.read_native_target(target)?;restore.validate_restoration(current.as_deref().map(Vec::as_slice)).map_err(fields_error)}-pub fn qoder_native_configuration_is_applied(+pub fn additional_native_configuration_is_applied(port: &dyn NativeAgentArtifactPort,operation: &OperationId,intent: &ExternalEffectIntentV1,@@ -85,22 +92,22 @@ pub fn qoder_native_configuration_is_applied(.unwrap_or(false))}-pub fn stage_qoder_configuration(+pub fn stage_additional_configuration(port: &dyn NativeAgentArtifactPort,operation: &OperationId,intent: &ExternalEffectIntentV1,- configuration: QoderFileConfiguration<'_>,+ configuration: AdditionalFileConfiguration<'_>,) -> PortResult<OwnedEffectV1> {stage(port, operation, intent, configuration, None)}-pub fn stage_qoder_reconfiguration(+pub fn stage_additional_reconfiguration(port: &dyn NativeAgentArtifactPort,operation: &OperationId,intent: &ExternalEffectIntentV1,previous_operation: &OperationId,previous_intent: &ExternalEffectIntentV1,- configuration: QoderFileConfiguration<'_>,+ configuration: AdditionalFileConfiguration<'_>,) -> PortResult<OwnedEffectV1> {validate_binding(operation, intent, previous_operation, previous_intent)?;// Do not require an obsolete previous record for an already staged/applied replay.@@ -115,7 +122,7 @@ fn stage(port: &dyn NativeAgentArtifactPort,operation: &OperationId,intent: &ExternalEffectIntentV1,- configuration: QoderFileConfiguration<'_>,+ configuration: AdditionalFileConfiguration<'_>,previous: Option<&Restore>,) -> PortResult<OwnedEffectV1> {if intent.desired_mode() != 0o600 {@@ -134,7 +141,13 @@ fn stage({return Err(error(PortErrorCode::Conflict, "qoder.preview.changed"));}- let edit = qoder_native::configure(+ let kind = match intent.desired()["subject"]["agent_id"].as_str() {+ Some("agent_qoder_default") => AgentKindV1::Qoder,+ Some("agent_pi_default") => AgentKindV1::Pi,+ _ => return Err(error(PortErrorCode::InvalidData, "additional.native.kind")),+ };+ let edit = additional_native::configure(+ kind,current.as_deref().map(Vec::as_slice),configuration.provider_id,configuration.endpoint,@@ -151,7 +164,7 @@ fn stage(port.stage_native_target(operation, intent, Some(&edit.bytes), true)}-pub fn stage_qoder_restoration(+pub fn stage_additional_restoration(port: &dyn NativeAgentArtifactPort,operation: &OperationId,intent: &ExternalEffectIntentV1,diff --git a/crates/integrations/src/agents/filesystem.rs b/crates/integrations/src/agents/filesystem.rsindex dfb96de5..2a21c5b6 100644--- a/crates/integrations/src/agents/filesystem.rs+++ b/crates/integrations/src/agents/filesystem.rs@@ -33,8 +33,11 @@ use super::{mod claude_settings;#[path = "claude_observation.rs"]mod main_observation;+#[path = "pi_native.rs"]+mod pi_native;#[path = "qoder_discovery.rs"]mod qoder_discovery;+pub use pi_native::PiDefaultModel;#[path = "settings_discovery.rs"]mod settings_discovery;@@ -123,6 +126,8 @@ pub struct AgentFilesystemLayoutV1 {pub codex_desktop_executable: Option<PathBuf>,pub claude_executable: PathBuf,pub qoder_executable: PathBuf,+ pub pi_executable: PathBuf,+ pub pi_config_root: PathBuf,pub qoder_home: PathBuf,pub qoder_config_root: PathBuf,pub codex_user_config: PathBuf,@@ -166,6 +171,11 @@ impl AgentFilesystemLayoutV1 {codex_desktop_executable: None,claude_executable: PathBuf::from("claude"),qoder_executable: PathBuf::from("qoder"),+ pi_executable: PathBuf::from("pi"),+ pi_config_root: std::env::var_os("PI_CODING_AGENT_DIR")+ .filter(|v| !v.is_empty())+ .map(PathBuf::from)+ .unwrap_or_else(|| home.join(".pi/agent")),qoder_home: home.to_owned(),qoder_config_root: std::env::var_os("QODER_CONFIG_DIR").filter(|value| !value.is_empty())@@ -195,6 +205,8 @@ impl AgentFilesystemLayoutV1 {#[derive(Clone)]pub struct FilesystemAgentScannerV1 {+ pi_collaboration_cli:+ std::sync::Arc<std::sync::Mutex<Option<(PathBuf, hiroute_domain::CanonicalDigest)>>>,pub(super) layout: AgentFilesystemLayoutV1,registry: ClaudeRegistrationIndexV1,legacy_recovery_version: Option<String>,@@ -262,6 +274,7 @@ impl FilesystemAgentScannerV1 {claude_ingress: Default::default(),#[cfg(unix)]qoder_collaboration: Default::default(),+ pi_collaboration_cli: Default::default(),}}@@ -365,7 +378,11 @@ impl FilesystemAgentScannerV1 {}pub fn scan(&self) -> Vec<FilesystemAgentDiscoveryV1> {- let mut results = vec![self.scan_codex(), self.qoder_settings_discovery(false)];+ let mut results = vec![+ self.scan_codex(),+ self.qoder_settings_discovery(false),+ self.pi_settings_discovery(),+ ];match executable_probe(&self.layout.claude_executable) {ExecutableProbe::Installed(executable) => {results.push(self.scan_claude(Some(executable), None, false));@@ -399,7 +416,7 @@ impl FilesystemAgentScannerV1 {);self.layout.claude_executable.clone()}- AgentKindV1::Qoder => continue,+ AgentKindV1::Qoder | AgentKindV1::Pi => continue,};#[cfg(unix)]if installation.profile.kind == AgentKindV1::Codex@@ -467,6 +484,9 @@ impl FilesystemAgentScannerV1 {&self,descriptor: &DiscoveredCredentialRefV1,) -> Result<ProtectedSecret, AgentFilesystemScanError> {+ if descriptor.field_selector == "pi.api-key" {+ return self.read_pi_secret(descriptor);+ }validate_descriptor(descriptor)?;let source = self.claude_sources()@@ -530,7 +550,8 @@ impl FilesystemAgentScannerV1 {self.layout.codex_desktop_executable.clone()}hiroute_domain::AgentModelSurfaceV2::ClaudeCli- | hiroute_domain::AgentModelSurfaceV2::QoderCli => None,+ | hiroute_domain::AgentModelSurfaceV2::QoderCli+ | hiroute_domain::AgentModelSurfaceV2::PiCli => None,}}@@ -562,6 +583,9 @@ impl FilesystemAgentScannerV1 {.into_iter().collect()}+ "agent_pi_default" if self.pi_executable_target().is_some() => {+ [hiroute_domain::AgentModelSurfaceV2::PiCli].into()+ }"agent_qoder_default" if self.qoder_executable_target().is_some() => {[hiroute_domain::AgentModelSurfaceV2::QoderCli].into_iter()diff --git a/crates/integrations/src/agents/filesystem_tests.rs b/crates/integrations/src/agents/filesystem_tests.rsindex fcdb4a3a..fcd96433 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/pi.rs"]+mod pi;#[path = "filesystem_tests/qoder.rs"]mod qoder;@@ -81,6 +83,8 @@ fn layout_with_claude_version(root: &Path, claude_version: &str) -> AgentFilesyscodex_desktop_executable: None,claude_executable: claude,qoder_executable: bin.join("qoder-not-installed"),+ pi_executable: root.join("bin/pi"),+ pi_config_root: root.join("home/.pi/agent"),qoder_home: home.clone(),qoder_config_root: home.join(".qoder"),codex_user_config: home.join(".codex/config.toml"),@@ -108,7 +112,7 @@ fn filesystem_scanner_registers_claude_and_never_serializes_token() {);let scanner = FilesystemAgentScannerV1::new(layout, registry());let results = scanner.scan();- assert_eq!(results.len(), 3);+ assert_eq!(results.len(), 4);let claude = results.iter().find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")@@ -897,7 +901,7 @@ 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(), 3);+ assert_eq!(results.len(), 4);assert!(results.iter().any(|result| matches!(&result.outcome,AgentDiscoveryOutcomeV1::ReportOnly {diff --git a/crates/integrations/src/agents/filesystem_tests/pi.rs b/crates/integrations/src/agents/filesystem_tests/pi.rsnew file mode 100644index 00000000..55fae8a2--- /dev/null+++ b/crates/integrations/src/agents/filesystem_tests/pi.rs@@ -0,0 +1,345 @@+//! Passive native API discovery is documentation of the supported product boundary.+use super::*;++fn source_scanner(+ root: &Path,+ models: serde_json::Value,+ auth: serde_json::Value,+) -> FilesystemAgentScannerV1 {+ let layout = layout(root);+ write_secret_settings(&layout.pi_config_root.join("models.json"), models);+ write_secret_settings(&layout.pi_config_root.join("auth.json"), auth);+ FilesystemAgentScannerV1::new(layout, registry())+}+fn models() -> serde_json::Value {+ json!({"providers":{"private-api":{"baseUrl":"http://127.0.0.1:4222/v1","api":"openai-responses",+ "apiKey":"provider-fallback","models":[{"id":"native-model","contextWindow":16384,"maxTokens":4096,"input":["text"]}]}}})+}++#[test]+fn pi_static_api_import_uses_saved_credential_templates_and_rejects_changed_source() {+ let root = tempfile::tempdir().unwrap();+ let scanner = source_scanner(+ root.path(),+ models(),+ json!({"private-api":{"type":"api_key",+ "key":"prefix-${ACCEPTANCE_KEY}","env":{"ACCEPTANCE_KEY":"saved-token"}}}),+ );+ let sources = scanner.pi_api_sources().unwrap();+ assert_eq!(sources.len(), 1);+ let selected = &sources[0];+ assert_eq!(+ selected.protocol,+ Some(hiroute_domain::UpstreamProtocol::Responses)+ );+ let public = serde_json::to_string(selected).unwrap();+ assert!(!public.contains("saved-token") && !public.contains("127.0.0.1"));+ let (endpoint, secret) = scanner.read_pi_api_source(selected).unwrap();+ assert_eq!(endpoint.as_str(), "http://127.0.0.1:4222/v1");+ assert!(secret.expose() == b"prefix-saved-token");+ write_secret_settings(+ &scanner.layout.pi_config_root.join("auth.json"),+ json!({"private-api":{"type":"api_key","key":"rotated"}}),+ );+ assert!(matches!(+ scanner.read_pi_api_source(selected),+ Err(AgentFilesystemScanError::SourceChanged)+ ));+}++#[test]+fn pi_helpers_oauth_and_custom_header_auth_never_become_importable_static_keys() {+ for auth in [+ json!({"private-api":{"type":"api_key","key":"!exit 98"}}),+ json!({"private-api":{"type":"oauth","access":"must-not-import"}}),+ ] {+ let root = tempfile::tempdir().unwrap();+ let scanner = source_scanner(root.path(), models(), auth);+ let source = scanner.pi_api_sources().unwrap().remove(0);+ assert!(source.credential.is_none());+ assert!(scanner.read_pi_api_source(&source).is_err());+ }+ let root = tempfile::tempdir().unwrap();+ let mut declarations = models();+ declarations["providers"]["private-api"]["headers"] = json!({"x-special-auth":"!exit 99"});+ let scanner = source_scanner(root.path(), declarations, json!({}));+ assert!(!scanner.pi_api_sources().unwrap()[0].supported_auth);+}++#[test]+fn pi_static_templates_preserve_invalid_closed_references_and_native_escapes() {+ for (template, expected) in [+ ("${NOT-$PI_TEMPLATE_INNER}", "${NOT-$PI_TEMPLATE_INNER}"),+ (+ "${NOT-$PI_TEMPLATE_INNER}/$PI_TEMPLATE_OUTER",+ "${NOT-$PI_TEMPLATE_INNER}/outer",+ ),+ (+ "$$PI_TEMPLATE_INNER/$!literal",+ "$PI_TEMPLATE_INNER/!literal",+ ),+ ("$1/$PI_TEMPLATE_OUTER", "$1/outer"),+ ] {+ let root = tempfile::tempdir().unwrap();+ let scanner = source_scanner(+ root.path(),+ models(),+ json!({"private-api":{+ "type":"api_key","key":template,"env":{+ "PI_TEMPLATE_INNER":"must-not-expand","PI_TEMPLATE_OUTER":"outer"}}}),+ );+ let source = scanner.pi_api_sources().unwrap().remove(0);+ assert_eq!(+ scanner.read_pi_api_source(&source).unwrap().1.expose(),+ expected.as_bytes()+ );+ }+}++#[test]+fn pi_default_reference_is_protected_independently_of_provider_file() {+ let root = tempfile::tempdir().unwrap();+ let scanner = source_scanner(root.path(), models(), json!({}));+ let before = scanner.pi_default_model().unwrap();+ write_secret_settings(+ &scanner.layout.pi_config_root.join("settings.json"),+ json!({"defaultProvider":"hiroute-main-test","defaultModel":"selected","theme":"dark"}),+ );+ let settings = scanner.layout.pi_config_root.join("settings.json");+ let original = fs::read(&settings).unwrap();+ fs::write(&settings, [&[0xef, 0xbb, 0xbf][..], &original].concat()).unwrap();+ let current = scanner.pi_default_model().unwrap();+ assert_ne!(before.content_digest, current.content_digest);+ assert!(current.removes_default("hiroute-main-test", &[]));+ assert!(!current.removes_default("another-provider", &[]));+ assert!(!current.removes_default(+ "hiroute-main-test",+ &[hiroute_domain::AdditionalAgentModelV1 {+ alias: "selected".into(),+ context_window_tokens: 16384,+ max_output_tokens: 4096+ }]+ ));+}++#[test]+fn pi_import_observes_jsonc_bom_and_the_models_effective_endpoint_override() {+ let root = tempfile::tempdir().unwrap();+ let mut declarations = models();+ declarations["providers"]["private-api"]["models"][0]["baseUrl"] =+ json!("http://127.0.0.1:4333/v1");+ let scanner = source_scanner(root.path(), declarations.clone(), json!({}));+ let target = scanner.pi_user_models_target();+ fs::write(+ &target,+ format!(+ "\u{feff}// native Pi models support comments\n{}",+ declarations+ ),+ )+ .unwrap();+ let selected = scanner.pi_api_sources().unwrap().remove(0);+ assert_eq!(+ scanner.read_pi_api_source(&selected).unwrap().0.as_str(),+ "http://127.0.0.1:4333/v1"+ );+ declarations["providers"]["private-api"]["models"][0]["baseUrl"] =+ json!("http://127.0.0.1:4444/v1");+ write_secret_settings(&target, declarations);+ assert!(matches!(+ scanner.read_pi_api_source(&selected),+ Err(AgentFilesystemScanError::SourceChanged)+ ));+}++#[test]+fn pi_cli_release_labels_and_entry_layout_do_not_gate_settings() {+ let root = tempfile::tempdir().unwrap();+ let package = root.path().join("selected-pi");+ let cli = package.join("bin/pi.js");+ fs::create_dir_all(cli.parent().unwrap()).unwrap();+ write_executable(&cli, "native CLI must not run during metadata discovery");+ let mut selected = layout(root.path());+ selected.pi_executable = cli.clone();+ let scanner = FilesystemAgentScannerV1::new(selected, registry());+ for version in ["1.0.2", "1.0.3", "9.0.0-next"] {+ write_secret_settings(+ &package.join("package.json"),+ json!({+ "name":crate::PI_NPM_PACKAGE, "version":version, "bin":{"pi":"bin/pi.js"}+ }),+ );+ let installation = crate::pi_cli_installation(&cli).unwrap();+ assert_eq!(installation.version, version);+ assert_eq!(installation.package_root, package);+ // A missing Worker SDK does not prevent passive static discovery or settings identity.+ assert!(!package.join("dist/index.js").exists());+ assert!(matches!(+ scanner.pi_settings_discovery().outcome,+ AgentDiscoveryOutcomeV1::Supported { .. }+ ));+ }+ write_secret_settings(+ &package.join("package.json"),+ json!({+ "name":crate::PI_NPM_PACKAGE, "version":"1.0.3", "bin":{"pi":"../foreign.js"}+ }),+ );+ write_executable(&root.path().join("foreign.js"), "foreign CLI");+ assert!(crate::pi_cli_installation(&cli).is_err());+}++#[test]+fn pi_disabled_collaboration_skill_does_not_authorize_enable_or_reuse_a_stale_observation() {+ use hiroute_domain::{AgentCapability, CapabilityState};+ let root = tempfile::tempdir().unwrap();+ let mut layout = layout(root.path());+ let package = root.path().join("selected-pi");+ write_secret_settings(+ &package.join("package.json"),+ json!({"name": crate::PI_NPM_PACKAGE,+ "version":"1.0.2","bin":{"pi":"dist/bundle/cli.js"}}),+ );+ fs::create_dir_all(package.join("dist/bundle")).unwrap();+ write_executable(+ &package.join("dist/bundle/cli.js"),+ "must-not-execute-native-cli",+ );+ fs::write(package.join("dist/index.js"), b"test SDK location only").unwrap();+ layout.pi_executable = package.join("dist/bundle/cli.js");+ let scanner = FilesystemAgentScannerV1::new(layout, registry());+ // This case isolates native Skill exclusion after the local interface check.+ // SDK capability acceptance/rejection is exercised by pi_sdk_contract.test.mjs.+ *scanner.pi_collaboration_cli.lock().unwrap() = Some((+ root.path().join("trusted-hiroute"),+ crate::pi_cli_installation(&scanner.layout.pi_executable)+ .unwrap()+ .manifest_digest,+ ));+ let inspect = || {+ let discovery = scanner.pi_settings_discovery();+ let AgentDiscoveryOutcomeV1::Supported { installation } = discovery.outcome else {+ panic!("fixture installation was not located")+ };+ (+ installation.observation_digest,+ installation+ .capability_evidence+ .into_iter()+ .find(|e| e.capability == AgentCapability::SkillLoading)+ .unwrap()+ .state,+ )+ };+ let before = inspect();+ assert_eq!(before.1, CapabilityState::Proven);+ for rule in [+ "!**/hiroute-collaboration/**",+ "-skills",+ "!**/*",+ "!SKILL.md",+ "!skills/hirout[e]-collaboration/SKILL.md",+ "!SKILL\\.md",+ "!!unrelated-receipt",+ ] {+ write_secret_settings(+ &scanner.layout.pi_config_root.join("settings.json"),+ json!({"skills":[rule]}),+ );+ let excluded = inspect();+ assert_ne!(excluded.0, before.0);+ assert_ne!(excluded.1, CapabilityState::Proven);+ }+ write_secret_settings(+ &scanner.layout.pi_config_root.join("settings.json"),+ json!({"skills":["!unrelated-receipt"]}),+ );+ let settings = scanner.layout.pi_config_root.join("settings.json");+ let original = fs::read(&settings).unwrap();+ fs::write(&settings, [&[0xef, 0xbb, 0xbf][..], &original].concat()).unwrap();+ assert_eq!(inspect().1, CapabilityState::Proven);+ let manifest = package.join("package.json");+ let mut upgraded: serde_json::Value =+ serde_json::from_slice(&fs::read(&manifest).unwrap()).unwrap();+ upgraded["version"] = json!("1.0.3");+ write_secret_settings(&manifest, upgraded);+ assert_ne!(+ inspect().1,+ CapabilityState::Proven,+ "an upgraded CLI must recheck its local resource capability"+ );+ fs::write(&settings, b"[]").unwrap();+ assert_ne!(inspect().1, CapabilityState::Proven);+ assert!(scanner.pi_default_model().is_err());+}++#[test]+fn pi_builtin_provider_proxy_preserves_catalog_api_and_explicit_models_inherit_provider_api() {+ let root = tempfile::tempdir().unwrap();+ let package = root.path().join("selected-pi");+ let cli = package.join("bin/pi.js");+ fs::create_dir_all(cli.parent().unwrap()).unwrap();+ write_executable(&cli, "must not execute");+ write_secret_settings(+ &package.join("package.json"),+ json!({+ "name":crate::PI_NPM_PACKAGE,"version":"1.0.2","bin":{"pi":"bin/pi.js"}+ }),+ );+ let catalog =+ package.join("node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json");+ fs::create_dir_all(catalog.parent().unwrap()).unwrap();+ write_secret_settings(+ &catalog,+ json!({"openai-responses":{"native":{+ "type":"chat","id":"native","api":"openai-responses","baseUrl":"https://inherited.invalid/v1"+ }}}),+ );+ let mut scanner = source_scanner(+ root.path(),+ json!({"providers":{"openai":{+ "baseUrl":"https://user-proxy.invalid/v1","apiKey":"proxy-only-secret",+ "api":"openai-completions"+ }}}),+ json!({}),+ );+ scanner.layout.pi_executable = cli;+ let sources = scanner.pi_api_sources().unwrap();+ let source = sources.iter().find(|s| s.provider_id == "openai").unwrap();+ let (endpoint, secret) = scanner.read_pi_api_source(source).unwrap();+ assert_eq!(endpoint.as_str(), "https://user-proxy.invalid/v1");+ assert_eq!(secret.expose(), b"proxy-only-secret");+ assert_eq!(+ source.protocol,+ Some(hiroute_domain::UpstreamProtocol::Responses)+ );+ write_secret_settings(+ &scanner.layout.pi_config_root.join("models.json"),+ json!({"providers":{"openai":{+ "baseUrl":"https://user-proxy.invalid/v1","apiKey":"proxy-only-secret",+ "api":"openai-completions","models":[{"id":"explicit"}]+ }}}),+ );+ let sources = scanner.pi_api_sources().unwrap();+ let source = sources.iter().find(|s| s.provider_id == "openai").unwrap();+ assert_eq!(+ source.protocol,+ Some(hiroute_domain::UpstreamProtocol::ChatCompletions)+ );+ assert!(scanner.read_pi_api_source(source).is_ok());+}++#[test]+fn pi_additional_auth_header_is_reported_not_silently_imported() {+ for auth_header in [json!(true), json!("invalid")] {+ let root = tempfile::tempdir().unwrap();+ let mut declarations = models();+ declarations["providers"]["private-api"]["api"] = json!("anthropic-messages");+ declarations["providers"]["private-api"]["authHeader"] = auth_header;+ let scanner = source_scanner(root.path(), declarations, json!({}));+ let source = scanner.pi_api_sources().unwrap().remove(0);+ assert!(!source.supported_auth);+ assert!(source.credential.is_none());+ assert!(scanner.read_pi_api_source(&source).is_err());+ }+}diff --git a/crates/integrations/src/agents/mod.rs b/crates/integrations/src/agents/mod.rsindex 4071da6c..378e17d2 100644--- a/crates/integrations/src/agents/mod.rs+++ b/crates/integrations/src/agents/mod.rs@@ -30,11 +30,15 @@ mod native_probe_process;#[cfg(unix)]pub use native_probe_process::NativeProbeProcess;mod observed_capabilities;+mod pi_runtime;+mod pi_sources;+pub use pi_sources::PiApiSource;mod qoder;-mod qoder_native;-mod qoder_native_effects;+pub use pi_runtime::*;+mod additional_native;+mod additional_native_effects;mod qoder_provider;-pub use qoder_native_effects::*;+pub use additional_native_effects::*;#[cfg(unix)]mod qoder_probe;mod registration;diff --git a/crates/integrations/src/agents/pi_native.rs b/crates/integrations/src/agents/pi_native.rsnew file mode 100644index 00000000..b0997a10--- /dev/null+++ b/crates/integrations/src/agents/pi_native.rs@@ -0,0 +1,247 @@+//! Pi's effective user targets and bounded settings facts. No native process or helper is run.+use super::*;+use hiroute_domain::{AdditionalAgentModelV1, AgentCapability, CapabilityState};+use serde::Serialize;++fn settings_value(bytes: &[u8]) -> Result<serde_json::Value, AgentFilesystemScanError> {+ let bytes = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(bytes);+ let value = if bytes.is_empty() {+ serde_json::json!({})+ } else {+ serde_json::from_slice(bytes).map_err(|_| AgentFilesystemScanError::InvalidConfig)?+ };+ if !value.is_object() {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ Ok(value)+}++#[derive(Serialize)]+pub struct PiDefaultModel {+ pub content_digest: CanonicalDigest,+ provider: Option<String>,+ model: Option<String>,+}+impl PiDefaultModel {+ pub fn removes_default(&self, provider: &str, models: &[AdditionalAgentModelV1]) -> bool {+ self.provider.as_deref() == Some(provider)+ && self+ .model+ .as_ref()+ .is_none_or(|selected| !models.iter().any(|m| &m.alias == selected))+ }+}++impl FilesystemAgentScannerV1 {+ pub fn pi_user_models_target(&self) -> PathBuf {+ self.layout.pi_config_root.join("models.json")+ }+ pub fn pi_user_skill_target(&self) -> PathBuf {+ self.layout+ .pi_config_root+ .join("skills/hiroute-collaboration/SKILL.md")+ }+ pub fn pi_default_model(&self) -> Result<PiDefaultModel, AgentFilesystemScanError> {+ let observed = super::super::filesystem_config::read_validated_config_bytes(+ &self.layout.pi_config_root.join("settings.json"),+ )?;+ let bytes = observed+ .as_ref()+ .map_or(&[][..], |(bytes, _)| bytes.as_slice());+ let value = settings_value(bytes)?;+ let field = |key: &str| -> Result<Option<String>, AgentFilesystemScanError> {+ value+ .get(key)+ .map(|v| {+ v.as_str()+ .map(str::to_owned)+ .ok_or(AgentFilesystemScanError::InvalidConfig)+ })+ .transpose()+ };+ Ok(PiDefaultModel {+ content_digest: CanonicalDigest::of_bytes(bytes),+ provider: field("defaultProvider")?,+ model: field("defaultModel")?,+ })+ }+ pub fn pi_executable_target(&self) -> Option<PathBuf> {+ let selected = &self.layout.pi_executable;+ if selected.is_absolute() || selected.components().count() > 1 {+ return super::super::executable::resolve(selected).ok().flatten();+ }+ let mut paths = std::env::var_os("PATH")+ .map(|v| {+ std::env::split_paths(&v)+ .filter(|p| p.is_absolute())+ .collect::<Vec<_>>()+ })+ .unwrap_or_default();+ paths.extend([PathBuf::from("/usr/local/bin"), PathBuf::from("/usr/bin")]);+ #[cfg(target_os = "macos")]+ paths.push(PathBuf::from("/opt/homebrew/bin"));+ paths.into_iter().take(128).find_map(|p| {+ super::super::executable::resolve(&p.join(selected))+ .ok()+ .flatten()+ })+ }+ pub fn pi_settings_discovery(&self) -> FilesystemAgentDiscoveryV1 {+ let Some(executable) = self.pi_executable_target() else {+ return probe_report(+ "agent_pi_default",+ AgentKindV1::Pi,+ ExecutableProbe::NotFound,+ );+ };+ let installation = super::super::pi_cli_installation(&executable);+ if installation.is_err() || !self.layout.pi_config_root.is_absolute() {+ return report_only_agent(+ "agent_pi_default",+ AgentKindV1::Pi,+ "not-probed".into(),+ AgentReportOnlyReasonV1::ConfigUnavailable,+ );+ }+ let identity = installation.expect("checked CLI identity");+ let mut outcome = resolve_agent_observation(base_observation(+ "agent_pi_default",+ AgentKindV1::Pi,+ identity.version,+ ));+ let resource_settings = super::super::filesystem_config::read_validated_config_bytes(+ &self.layout.pi_config_root.join("settings.json"),+ )+ .and_then(|observed| {+ let bytes = observed.map(|(bytes, _)| bytes).unwrap_or_default();+ let settings = settings_value(&bytes)?;+ let rules = settings+ .get("skills")+ .map(|v| v.as_array().ok_or(AgentFilesystemScanError::InvalidConfig))+ .transpose()?;+ let excluded = rules.is_some_and(|rules| {+ rules.iter().any(|rule| {+ let Some(rule) = rule.as_str() else {+ return true;+ };+ let negative = rule.starts_with('!') || rule.starts_with('-');+ // Exact exclusions of unrelated Skills remain usable. Complex exclusion+ // patterns cannot be statically proven here and fail closed at Save.+ let pattern = &rule[usize::from(negative)..];+ negative+ && (!pattern+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b"._-/ ".contains(&b))+ || pattern.contains("hiroute-collaboration")+ || pattern.ends_with("SKILL.md")+ || pattern.trim_end_matches('/').ends_with("skills"))+ })+ });+ Ok((CanonicalDigest::of_bytes(&bytes), !excluded))+ });+ if let AgentDiscoveryOutcomeV1::Supported { installation } = &mut outcome {+ super::super::observed_capabilities::attach_file_capabilities(+ installation,+ &executable,+ &self.pi_user_skill_target(),+ );+ let resources_allowed = resource_settings+ .as_ref()+ .is_ok_and(|(_, allowed)| *allowed);+ if let Ok((settings_digest, _)) = &resource_settings {+ installation.observation_digest =+ CanonicalDigest::of(&(&installation.observation_digest, settings_digest))+ .expect("serializable native observation");+ for proof in &mut installation.capability_evidence {+ proof.dependency_digest = installation.observation_digest.clone();+ }+ }+ // Only a successful local resource/tool interface check authorizes Skill loading.+ // Model configuration does not depend on the Worker or history SDK contracts.+ let resource_contract = self.pi_collaboration_cli.lock().ok().is_some_and(|v| {+ v.as_ref()+ .is_some_and(|(_, digest)| *digest == identity.manifest_digest)+ });+ for proof in &mut installation.capability_evidence {+ if proof.capability == AgentCapability::SkillLoading+ && resources_allowed+ && resource_contract+ {+ proof.state = CapabilityState::Proven;+ proof.reason = None;+ proof.adapter_contract = "hiroute.pi-native-resources/v1".into();+ }+ if proof.capability == AgentCapability::TrustedCliExecution+ && self.pi_collaboration_cli.lock().ok().is_some_and(|v| {+ v.as_ref().is_some_and(|(cli, digest)| {+ *digest == identity.manifest_digest+ && super::super::executable::resolve(cli)+ .ok()+ .flatten()+ .as_ref()+ == Some(cli)+ })+ })+ {+ proof.state = CapabilityState::Proven;+ proof.reason = None;+ proof.adapter_contract = "hiroute.pi-local-cli/v1".into();+ }+ }+ }+ FilesystemAgentDiscoveryV1 {+ outcome,+ configuration_issue: None,+ claude_configuration: None,+ discovered_credential: None,+ permission_hardening: None,+ managed_launch: None,+ }+ }+ #[cfg(unix)]+ pub fn check_pi_collaboration(&self, cli: &Path) -> Result<(), AgentFilesystemScanError> {+ *self+ .pi_collaboration_cli+ .lock()+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)? = None;+ let executable = self+ .pi_executable_target()+ .ok_or(AgentFilesystemScanError::SourceUnavailable)?;+ let identity = super::super::pi_cli_installation(&executable)?;+ self.check_pi_capability(&executable, super::super::PiSdkCapability::Collaboration)?;+ if super::super::pi_cli_installation(&executable)?.manifest_digest+ != identity.manifest_digest+ {+ return Err(AgentFilesystemScanError::SourceChanged);+ }+ let cli = super::super::executable::resolve(cli)+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?+ .ok_or(AgentFilesystemScanError::SourceUnavailable)?;+ *self+ .pi_collaboration_cli+ .lock()+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)? =+ Some((cli, identity.manifest_digest));+ Ok(())+ }++ #[cfg(unix)]+ pub fn check_pi_model_configuration(&self) -> Result<(), AgentFilesystemScanError> {+ let executable = self+ .pi_executable_target()+ .ok_or(AgentFilesystemScanError::SourceUnavailable)?;+ self.check_pi_capability(&executable, super::super::PiSdkCapability::Models)+ }++ #[cfg(unix)]+ fn check_pi_capability(+ &self,+ executable: &Path,+ capability: super::super::PiSdkCapability,+ ) -> Result<(), AgentFilesystemScanError> {+ let node = super::super::executable::resolve(Path::new("node"))+ .map_err(|_| AgentFilesystemScanError::SourceUnavailable)?+ .ok_or(AgentFilesystemScanError::SourceUnavailable)?;+ super::super::check_pi_sdk_capability(executable, &node, capability)+ }+}diff --git a/crates/integrations/src/agents/pi_runtime.rs b/crates/integrations/src/agents/pi_runtime.rsnew file mode 100644index 00000000..ac9071db--- /dev/null+++ b/crates/integrations/src/agents/pi_runtime.rs@@ -0,0 +1,177 @@+//! CLI identity is independent of its release label and of path-specific SDK capabilities.+use std::path::{Path, PathBuf};++pub const PI_NPM_PACKAGE: &str = "@earendil-works/pi-coding-agent";+pub const PI_SDK_CONTRACT: &str = include_str!("pi_sdk_contract.mjs");++pub struct PiCliInstallation {+ pub package_root: PathBuf,+ pub version: String,+ pub manifest_digest: hiroute_domain::CanonicalDigest,+}++pub fn pi_cli_installation(+ cli: &Path,+) -> Result<PiCliInstallation, super::AgentFilesystemScanError> {+ use super::AgentFilesystemScanError::SourceUnavailable;+ let cli = std::fs::canonicalize(cli).map_err(|_| SourceUnavailable)?;+ // npm/pnpm may move the entry; the owning manifest, not a depth or filename,+ // must bind its declared bin to this exact canonical CLI.+ for root in cli.ancestors().skip(1).take(8) {+ let manifest = root.join("package.json");+ let Ok(metadata) = std::fs::metadata(&manifest) else {+ continue;+ };+ if !metadata.is_file() || metadata.len() > 64 * 1024 {+ continue;+ }+ let bytes = std::fs::read(&manifest).map_err(|_| SourceUnavailable)?;+ let package: serde_json::Value =+ serde_json::from_slice(&bytes).map_err(|_| SourceUnavailable)?;+ if package["name"] != PI_NPM_PACKAGE {+ continue;+ }+ let bin = package+ .pointer("/bin/pi")+ .and_then(serde_json::Value::as_str)+ .ok_or(SourceUnavailable)?;+ let entry = std::fs::canonicalize(root.join(bin)).map_err(|_| SourceUnavailable)?;+ let version = package["version"]+ .as_str()+ .filter(|v| !v.is_empty() && v.len() <= 128)+ .ok_or(SourceUnavailable)?;+ if entry != cli || !entry.starts_with(root) {+ return Err(SourceUnavailable);+ }+ return Ok(PiCliInstallation {+ package_root: root.to_owned(),+ version: version.into(),+ manifest_digest: hiroute_domain::CanonicalDigest::of_bytes(&bytes),+ });+ }+ Err(SourceUnavailable)+}++#[derive(Clone, Copy)]+pub enum PiSdkCapability {+ Models,+ Collaboration,+ Worker,+ Continue,+}++/// Load only the SDK exported by the selected CLI's package. No native prompt,+/// user credential store, helper, extension or network model refresh is used.+#[cfg(unix)]+pub fn check_pi_sdk_capability(+ cli: &Path,+ node: &Path,+ capability: PiSdkCapability,+) -> Result<(), super::AgentFilesystemScanError> {+ use super::AgentFilesystemScanError::SourceUnavailable;+ use std::io::Write;+ use std::os::unix::process::CommandExt;+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};+ pi_cli_installation(cli)?;+ validate_pi_node(node)?;+ let mut script = tempfile::Builder::new()+ .suffix(".mjs")+ .tempfile()+ .map_err(|_| SourceUnavailable)?;+ script+ .write_all(PI_SDK_CONTRACT.as_bytes())+ .map_err(|_| SourceUnavailable)?;+ let scope = match capability {+ PiSdkCapability::Models => "models",+ PiSdkCapability::Collaboration => "collaboration",+ PiSdkCapability::Worker => "worker",+ PiSdkCapability::Continue => "continue",+ };+ let capture = tempfile::NamedTempFile::new().map_err(|_| SourceUnavailable)?;+ let child = Command::new(node)+ .arg(script.path())+ .arg("--check")+ .arg(cli)+ .arg(scope)+ .env("PI_OFFLINE", "1")+ .env("PI_TELEMETRY", "0")+ .env_remove("NODE_OPTIONS")+ .env_remove("HIROUTE_RUN_TOKEN")+ .stdin(Stdio::null())+ .stdout(capture.reopen().map_err(|_| SourceUnavailable)?)+ .stderr(Stdio::null())+ .process_group(0)+ .spawn()+ .map_err(|_| SourceUnavailable)?;+ let mut child = super::NativeProbeProcess::new(child);+ let start = Instant::now();+ loop {+ match child.observe().map_err(|_| SourceUnavailable)? {+ Some(true) => break,+ Some(false) => return Err(SourceUnavailable),+ None => {}+ }+ if start.elapsed() > Duration::from_secs(5) {+ return Err(SourceUnavailable);+ }+ std::thread::sleep(Duration::from_millis(5));+ }+ let bytes = super::native_probe_process::read_bounded(capture.path(), 128)+ .map_err(|_| SourceUnavailable)?;+ child.stop().map_err(|_| SourceUnavailable)?;+ if bytes.as_slice() != b"hiroute.pi-sdk-capability/v1:ok\n" {+ return Err(SourceUnavailable);+ }+ Ok(())+}++pub const PI_NODE_MINIMUM: (u32, u32, u32) = (22, 19, 0);++/// One bounded native version read; neither stdout nor stderr reaches product diagnostics.+#[cfg(unix)]+pub fn validate_pi_node(node: &Path) -> Result<(), super::AgentFilesystemScanError> {+ use super::AgentFilesystemScanError::SourceUnavailable;+ use std::os::unix::process::CommandExt;+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};+ let capture = tempfile::NamedTempFile::new().map_err(|_| SourceUnavailable)?;+ let child = Command::new(node)+ .arg("--version")+ .stdin(Stdio::null())+ .stdout(capture.reopen().map_err(|_| SourceUnavailable)?)+ .stderr(Stdio::null())+ .process_group(0)+ .spawn()+ .map_err(|_| SourceUnavailable)?;+ let mut child = super::NativeProbeProcess::new(child);+ let start = Instant::now();+ loop {+ match child.observe().map_err(|_| SourceUnavailable)? {+ Some(true) => break,+ Some(false) => return Err(SourceUnavailable),+ None => {}+ }+ if start.elapsed() > Duration::from_secs(2) {+ return Err(SourceUnavailable);+ }+ std::thread::sleep(Duration::from_millis(5));+ }+ let bytes = super::native_probe_process::read_bounded(capture.path(), 64)+ .map_err(|_| SourceUnavailable)?;+ child.stop().map_err(|_| SourceUnavailable)?;+ let raw = std::str::from_utf8(&bytes)+ .map_err(|_| SourceUnavailable)?+ .trim()+ .strip_prefix('v')+ .ok_or(SourceUnavailable)?;+ let version = raw+ .split('.')+ .map(str::parse::<u32>)+ .collect::<Result<Vec<_>, _>>()+ .map_err(|_| SourceUnavailable)?;+ if version.len() != 3 || (version[0], version[1], version[2]) < PI_NODE_MINIMUM {+ return Err(SourceUnavailable);+ }+ Ok(())+}diff --git a/crates/integrations/src/agents/pi_sdk_contract.mjs b/crates/integrations/src/agents/pi_sdk_contract.mjsnew file mode 100644index 00000000..09dfae50--- /dev/null+++ b/crates/integrations/src/agents/pi_sdk_contract.mjs@@ -0,0 +1,103 @@+// Shared by bounded local admission and the managed Worker. Release labels are diagnostic.+import {readFileSync, realpathSync, statSync, mkdtempSync, mkdirSync, writeFileSync, rmSync} from 'node:fs';+import {dirname, join, sep} from 'node:path';+import {tmpdir} from 'node:os';+import {pathToFileURL, fileURLToPath} from 'node:url';++export async function loadPiSdk(selectedCli) {+ const cli = realpathSync(selectedCli);+ let root = dirname(cli);+ for (let depth = 0; depth < 8; depth++, root = dirname(root)) {+ const manifest = join(root, 'package.json');+ let pkg;+ try {+ if (statSync(manifest).size > 64 * 1024) throw new Error();+ pkg = JSON.parse(readFileSync(manifest, 'utf8'));+ } catch { continue; }+ if (pkg.name !== '@earendil-works/pi-coding-agent') continue;+ if (typeof pkg.version !== 'string' || !pkg.version || pkg.version.length > 128+ || typeof pkg.bin?.pi !== 'string' || realpathSync(join(root, pkg.bin.pi)) !== cli+ || !cli.startsWith(root + sep)) throw new Error('Pi CLI identity unavailable');+ const entry = typeof pkg.exports === 'string' ? pkg.exports : pkg.exports ? pkg.exports['.'] : pkg.main;+ const path = typeof entry === 'string' ? entry : entry?.import ?? entry?.default;+ if (typeof path !== 'string') throw new Error('Pi SDK export unavailable');+ const sdkPath = realpathSync(join(root, path));+ if (!sdkPath.startsWith(root + sep)) throw new Error('Pi SDK source mismatch');+ return {sdk: await import(pathToFileURL(sdkPath).href), pkg};+ }+ throw new Error('Pi CLI identity unavailable');+}++function methods(object, names) {+ if (names.some(name => typeof object?.[name] !== 'function')) throw new Error('Pi capability unavailable');+}++export function assertPiCapabilities(sdk, scope) {+ if (scope === 'models') {+ methods(sdk.ModelRuntime, ['create']);+ methods(sdk.ModelRuntime?.prototype, ['getModels']);+ return;+ }+ if (!['collaboration', 'worker', 'continue'].includes(scope)) throw new Error('Pi capability scope');+ methods(sdk.SettingsManager, ['fromStorage']);+ methods(sdk.DefaultResourceLoader?.prototype, ['reload', 'getSkills']);+ methods(sdk, ['createReadTool', 'createBashTool']);+ if (scope === 'collaboration') return;+ methods(sdk.SettingsManager, ['create']);+ methods(sdk.SettingsManager?.prototype, ['getGlobalSettings', 'getProjectSettings']);+ assertPiCapabilities(sdk, 'models');+ methods(sdk.ModelRuntime?.prototype, ['registerProvider', 'setRuntimeApiKey']);+ methods(sdk, ['createAgentSession']);+ methods(sdk.SessionManager, scope === 'continue' ? ['open'] : ['create']);+ methods(sdk.SessionManager?.prototype, ['getSessionId', 'getSessionFile', 'buildSessionContext']);+ if (scope === 'worker') methods(sdk.SessionManager?.prototype, ['setSessionFile']);+ methods(sdk.AgentSession?.prototype, ['setModel', 'subscribe', 'prompt', 'clearQueue', 'abort', 'dispose']);+ // The adapter owns a v3 history reader/writer contract; it never asks the SDK to migrate.+ if (sdk.CURRENT_SESSION_VERSION !== 3) throw new Error('Pi session format unavailable');+}++export async function probePiCapabilities(sdk, scope) {+ assertPiCapabilities(sdk, scope);+ const root = mkdtempSync(join(tmpdir(), 'hiroute-pi-cap-'));+ try {+ if (scope !== 'models') {+ const skill = join(root, 'skills/hiroute-capability/SKILL.md');+ mkdirSync(dirname(skill), {recursive:true, mode:0o700});+ writeFileSync(skill, '---\nname: hiroute-capability\ndescription: Local interface check\n---\nLocal receipt.\n', {mode:0o600});+ const settings = JSON.stringify({extensions:[], packages:[], retry:{enabled:false}, cacheWarming:'off'});+ const settingsManager = sdk.SettingsManager.fromStorage({withLock(_scope, fn){return fn(settings);}}, {projectTrusted:true});+ const loader = new sdk.DefaultResourceLoader({cwd:root, agentDir:root, settingsManager, noExtensions:true});+ await loader.reload();+ if (!loader.getSkills()?.skills?.some(value => value.name === 'hiroute-capability'+ && realpathSync(value.filePath) === realpathSync(skill))) throw new Error('Pi Skill loading unavailable');+ for (const [factory, name] of [[sdk.createReadTool, 'read'], [sdk.createBashTool, 'bash']]) {+ const tool = factory(root);+ if (tool.name !== name || typeof tool.execute !== 'function') throw new Error('Pi native tool unavailable');+ }+ return;+ }+ const model = {id:'capability', name:'Local capability', api:'openai-responses',+ contextWindow:16384, maxTokens:4096, input:['text'], reasoning:false};+ const path = join(root, 'models.json');+ writeFileSync(path, JSON.stringify({providers:{'hiroute-capability':{+ api:'openai-responses', baseUrl:'http://127.0.0.1:1/v1', apiKey:'local-noncredential', models:[model]+ }}}), {mode:0o600});+ const credentials = new Map();+ const runtime = await sdk.ModelRuntime.create({modelsPath:path, allowModelNetwork:false,+ refreshOnCreate:false, credentials:{async read(id){return credentials.get(id);},+ async list(){return [];},async modify(id,fn){return fn(credentials.get(id));},async delete(){}}});+ const observed = runtime.getModels('hiroute-capability').find(value => value.id === model.id);+ if (!observed || observed.provider !== 'hiroute-capability' || observed.api !== model.api+ || observed.baseUrl !== 'http://127.0.0.1:1/v1' || observed.contextWindow !== model.contextWindow+ || observed.maxTokens !== model.maxTokens) throw new Error('Pi model configuration unavailable');+ } finally {rmSync(root, {recursive:true, force:true});}+}++if (process.argv[2] === '--check' && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) {+ process.umask(0o077);+ try {+ const {sdk} = await loadPiSdk(process.argv[3]);+ await probePiCapabilities(sdk, process.argv[4]);+ process.stdout.write('hiroute.pi-sdk-capability/v1:ok\n');+ } catch {process.exitCode = 1;}+}diff --git a/crates/integrations/src/agents/pi_sdk_contract.test.mjs b/crates/integrations/src/agents/pi_sdk_contract.test.mjsnew file mode 100644index 00000000..f2399b42--- /dev/null+++ b/crates/integrations/src/agents/pi_sdk_contract.test.mjs@@ -0,0 +1,89 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {mkdtempSync, mkdirSync, writeFileSync, rmSync} from 'node:fs';+import {join} from 'node:path';+import {tmpdir} from 'node:os';+import {loadPiSdk, assertPiCapabilities, probePiCapabilities} from './pi_sdk_contract.mjs';++function sdk() {+ class ModelRuntime {+ static async create(options) {+ assert.equal(options.allowModelNetwork, false);+ assert.equal(options.refreshOnCreate, false);+ assert.deepEqual(await options.credentials.list(), []);+ return new ModelRuntime();+ }+ getModels(provider) {return [{provider, id:'capability', api:'openai-responses',+ baseUrl:'http://127.0.0.1:1/v1', contextWindow:16384, maxTokens:4096}];}+ registerProvider() {} setRuntimeApiKey() {}+ }+ class SettingsManager {static create() {} static fromStorage() {} getGlobalSettings() {} getProjectSettings() {}}+ class DefaultResourceLoader {reload() {} getSkills() {}}+ class SessionManager {static create() {} static open() {} getSessionId() {} getSessionFile() {} buildSessionContext() {} setSessionFile() {}}+ class AgentSession {setModel() {} subscribe() {} prompt() {} clearQueue() {} abort() {} dispose() {}}+ return {ModelRuntime, SettingsManager, DefaultResourceLoader, SessionManager, AgentSession,+ createAgentSession(){}, createReadTool(){}, createBashTool(){}, CURRENT_SESSION_VERSION:3};+}++test('the selected CLI owns its SDK after a version or npm entry-layout change', async () => {+ for (const version of ['1.0.2', '1.0.3', '9.0.0-next']) {+ const root = mkdtempSync(join(tmpdir(), 'hiroute-pi-sdk-test-'));+ try {+ mkdirSync(join(root, 'bin')); mkdirSync(join(root, 'sdk'));+ const cli = join(root, 'bin/pi.js');+ // Importing the SDK must never execute the selected CLI.+ writeFileSync(cli, 'throw new Error("native CLI executed during admission");');+ writeFileSync(join(root, 'sdk/index.mjs'), 'export const selected = "owned-SDK";');+ const pkg = {name:'@earendil-works/pi-coding-agent', version,+ bin:{pi:'bin/pi.js'}, exports:{'.':{import:'./sdk/index.mjs'}}};+ writeFileSync(join(root, 'package.json'), JSON.stringify(pkg));+ const loaded = await loadPiSdk(cli);+ assert.equal(loaded.pkg.version, version);+ assert.equal(loaded.sdk.selected, 'owned-SDK');+ pkg.exports['.'].import = '../../foreign-sdk.mjs';+ writeFileSync(join(root, 'package.json'), JSON.stringify(pkg));+ await assert.rejects(loadPiSdk(cli));+ pkg.bin.pi = 'bin/other.js';+ writeFileSync(join(root, 'package.json'), JSON.stringify(pkg));+ await assert.rejects(loadPiSdk(cli));+ } finally {rmSync(root, {recursive:true, force:true});}+ }+});++test('model routing checks native declarations without requiring Worker or history interfaces', async () => {+ const value = sdk();+ delete value.createAgentSession; delete value.SessionManager; delete value.SettingsManager;+ await probePiCapabilities(value, 'models');+ value.ModelRuntime.prototype.getModels = () => [];+ await assert.rejects(probePiCapabilities(value, 'models'), /configuration unavailable/);+ delete value.ModelRuntime.create;+ assert.throws(() => assertPiCapabilities(value, 'models'), /capability unavailable/);+});++test('task-route configuration requires resources and tools, independently of Worker SDK', () => {+ const value = sdk(); delete value.ModelRuntime; delete value.createAgentSession;+ delete value.SettingsManager.create;+ delete value.SettingsManager.prototype.getGlobalSettings;+ delete value.SettingsManager.prototype.getProjectSettings;+ assertPiCapabilities(value, 'collaboration');+ delete value.createBashTool;+ assert.throws(() => assertPiCapabilities(value, 'collaboration'), /capability unavailable/);+});++test('a new Worker does not require native open; Continue does', () => {+ const value = sdk(); delete value.SessionManager.open;+ assertPiCapabilities(value, 'worker');+ assert.throws(() => assertPiCapabilities(value, 'continue'), /capability unavailable/);+ delete value.AgentSession.prototype.abort;+ assert.throws(() => assertPiCapabilities(value, 'worker'), /capability unavailable/);+ const resume = sdk(); delete resume.SessionManager.create; delete resume.SessionManager.prototype.setSessionFile;+ assertPiCapabilities(resume, 'continue');+ assert.throws(() => assertPiCapabilities(resume, 'worker'), /capability unavailable/);+});++test('an unknown SDK history writer is refused without blocking model or task-route setup', () => {+ const value = sdk(); value.CURRENT_SESSION_VERSION = 4;+ assertPiCapabilities(value, 'models'); assertPiCapabilities(value, 'collaboration');+ assert.throws(() => assertPiCapabilities(value, 'worker'), /session format unavailable/);+ assert.throws(() => assertPiCapabilities(value, 'continue'), /session format unavailable/);+});diff --git a/crates/integrations/src/agents/pi_sources.rs b/crates/integrations/src/agents/pi_sources.rsnew file mode 100644index 00000000..896c7c83--- /dev/null+++ b/crates/integrations/src/agents/pi_sources.rs@@ -0,0 +1,396 @@+//! Passive Pi API sources. Only literal/static environment keys are imported; no commands/OAuth.+use super::{+ AgentFilesystemScanError as Error, DiscoveredAuthSource, DiscoveredCredentialRefV1,+ FILESYSTEM_AGENT_SCANNER_ID_V1, FILESYSTEM_AGENT_SCANNER_VERSION_V1, FilesystemAgentScannerV1,+};+use hiroute_domain::{CanonicalDigest, ProtectedSecret, UpstreamProtocol};+use serde::Serialize;+use serde_json::Value;+use std::collections::{BTreeMap, BTreeSet};+use zeroize::{Zeroize, Zeroizing};++#[derive(Clone, Eq, PartialEq, Serialize)]+pub struct PiApiSource {+ pub provider_id: String,+ pub model_id: String,+ pub protocol: Option<UpstreamProtocol>,+ pub display_name: String,+ pub context_tokens: Option<u64>,+ pub max_output_tokens: Option<u64>,+ pub vision: Option<bool>,+ pub reasoning: Option<bool>,+ pub authentication: DiscoveredAuthSource,+ pub source_ref: String,+ pub evidence_digest: CanonicalDigest,+ pub revision: u64,+ pub credential: Option<DiscoveredCredentialRefV1>,+ pub supported_auth: bool,+}+type PiSourceSnapshot = (+ Vec<PiApiSource>,+ Option<(Zeroizing<String>, ProtectedSecret)>,+);+/// Raw provider values stay privileged and are cleared after each bounded scan.+struct Document(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);+ }+}+fn read(path: &std::path::Path) -> Result<(Document, CanonicalDigest), Error> {+ let observed = super::filesystem_config::read_validated_config_bytes(path)?;+ let bytes = observed.as_ref().map_or(&[][..], |(b, _)| b.as_slice());+ let value = if bytes.is_empty() {+ serde_json::json!({})+ } else {+ if path.file_name().is_some_and(|v| v == "models.json") {+ super::additional_native::parse_native_jsonc(bytes).map_err(|_| Error::InvalidConfig)?+ } else {+ serde_json::from_slice(bytes).map_err(|_| Error::InvalidConfig)?+ }+ };+ if !value.is_object() {+ return Err(Error::InvalidConfig);+ }+ Ok((Document(value), CanonicalDigest::of_bytes(bytes)))+}+fn key(+ value: Option<&Value>,+ env: Option<&Value>,+) -> (DiscoveredAuthSource, Option<Zeroizing<String>>) {+ let Some(value) = value.and_then(Value::as_str).filter(|s| !s.is_empty()) else {+ return (DiscoveredAuthSource::Missing, None);+ };+ if value.starts_with('!') {+ return (DiscoveredAuthSource::HelperNeedsInput, None);+ }+ // Supported native key templates: $NAME/${NAME}, $$ and $!. Plain names are literal.+ // Resolve only referenced names, never evaluate a shell or enumerate the environment.+ let mut resolved = Zeroizing::new(String::new());+ let mut rest = value;+ let mut used_env = false;+ while let Some(index) = rest.find('$') {+ resolved.push_str(&rest[..index]);+ rest = &rest[index + 1..];+ if let Some(tail) = rest.strip_prefix('$').or_else(|| rest.strip_prefix('!')) {+ resolved.push(rest.chars().next().unwrap());+ rest = tail;+ continue;+ }+ let reference = if let Some(braced) = rest.strip_prefix('{') {+ braced.find('}').map(|end| (&braced[..end], end + 2))+ } else {+ let length = rest+ .bytes()+ .take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')+ .count();+ (length > 0).then(|| (&rest[..length], length))+ };+ let Some((name, consumed)) = reference.filter(|(name, _)| {+ name.bytes()+ .next()+ .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')+ && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')+ }) else {+ resolved.push('$');+ // Native templates consume a closed invalid ${...} as one literal,+ // including any inner '$'; only an unclosed brace resumes scanning.+ if rest.starts_with('{')+ && let Some(end) = rest.find('}')+ {+ resolved.push_str(&rest[..=end]);+ rest = &rest[end + 1..];+ }+ continue;+ };+ let configured = env+ .and_then(|v| v.get(name))+ .and_then(Value::as_str)+ .filter(|v| !v.is_empty());+ let process = configured+ .is_none()+ .then(|| std::env::var(name).ok())+ .flatten();+ let Some(material) = configured.or(process.as_deref()).filter(|v| !v.is_empty()) else {+ return (DiscoveredAuthSource::Missing, None);+ };+ resolved.push_str(material);+ used_env = true;+ rest = &rest[consumed..];+ }+ resolved.push_str(rest);+ if resolved.is_empty() || resolved.len() > 64 * 1024 {+ return (DiscoveredAuthSource::Missing, None);+ }+ (+ if used_env {+ DiscoveredAuthSource::EnvironmentKey+ } else {+ DiscoveredAuthSource::InlineToken+ },+ Some(resolved),+ )+}+fn bounded(value: &str) -> bool {+ !value.is_empty() && value.len() <= 256 && !value.chars().any(char::is_control)+}++impl FilesystemAgentScannerV1 {+ pub fn pi_api_sources(&self) -> Result<Vec<PiApiSource>, Error> {+ self.pi_sources_inner(None).map(|(items, _)| items)+ }+ pub fn read_pi_api_source(+ &self,+ selected: &PiApiSource,+ ) -> Result<(Zeroizing<String>, ProtectedSecret), Error> {+ let (current, material) = self.pi_sources_inner(Some(&selected.source_ref))?;+ if !current.iter().any(|item| item == selected) {+ return Err(Error::SourceChanged);+ }+ let material = material.ok_or(Error::SourceUnavailable)?;+ if !self.pi_api_sources()?.iter().any(|item| item == selected) {+ return Err(Error::SourceChanged);+ }+ Ok(material)+ }+ pub(super) fn read_pi_secret(+ &self,+ descriptor: &DiscoveredCredentialRefV1,+ ) -> Result<ProtectedSecret, Error> {+ let source = self+ .pi_api_sources()?+ .into_iter()+ .find(|s| s.credential.as_ref() == Some(descriptor))+ .ok_or(Error::SourceChanged)?;+ self.read_pi_api_source(&source).map(|(_, key)| key)+ }+ fn pi_sources_inner(&self, selected: Option<&str>) -> Result<PiSourceSnapshot, Error> {+ let (models, models_digest) = read(&self.pi_user_models_target())?;+ let (auth, auth_digest) = read(&self.layout.pi_config_root.join("auth.json"))?;+ let mut providers = models+ .0+ .get("providers")+ .map(|v| v.as_object().cloned().ok_or(Error::InvalidConfig))+ .transpose()?+ .unwrap_or_default();+ // Built-in API models come from the selected, pinned native package's JSON data,+ // not a second checked-in catalog or execution of user/provider JavaScript.+ let sdk = self+ .pi_executable_target()+ .and_then(|p| super::super::pi_cli_installation(&p).ok());+ let mut catalog_digests = BTreeMap::new();+ for (provider_id, variable) in [+ ("openai", "OPENAI_API_KEY"),+ ("anthropic", "ANTHROPIC_API_KEY"),+ ("deepseek", "DEEPSEEK_API_KEY"),+ ("groq", "GROQ_API_KEY"),+ ("mistral", "MISTRAL_API_KEY"),+ ("xai", "XAI_API_KEY"),+ ("cerebras", "CEREBRAS_API_KEY"),+ ] {+ if !providers.contains_key(provider_id)+ && auth.0.get(provider_id).is_none()+ && std::env::var(variable).ok().is_none_or(|v| v.is_empty())+ {+ continue;+ }+ let provider = providers+ .entry(provider_id)+ .or_insert_with(|| serde_json::json!({}));+ if !provider.is_object() {+ return Err(Error::InvalidConfig);+ }+ if provider.get("apiKey").is_none() {+ provider["apiKey"] = format!("${{{variable}}}").into();+ }+ if provider.get("models").is_none()+ && let Some(sdk) = &sdk+ {+ let nested = sdk.package_root.join("node_modules/@earendil-works/pi-ai");+ let sibling = sdk+ .package_root+ .parent()+ .ok_or(Error::SourceUnavailable)?+ .join("pi-ai");+ let root = if nested.is_dir() { nested } else { sibling };+ let bytes = super::filesystem_config::read_system_config_bytes(+ &root.join(format!("dist/providers/data/{provider_id}.json")),+ )?+ .ok_or(Error::SourceUnavailable)?+ .0;+ let catalog: Value =+ serde_json::from_slice(&bytes).map_err(|_| Error::InvalidConfig)?;+ let declarations = catalog+ .as_object()+ .ok_or(Error::InvalidConfig)?+ .values()+ .filter_map(Value::as_object)+ .flat_map(|api| api.values())+ .filter(|m| m["type"] == "chat")+ .cloned()+ .map(|mut model| {+ // Pi applies provider addresses to inherited models, but preserves+ // their API. Provider API defaults apply only to explicit models.+ if let Some(value) = provider.get("baseUrl") {+ model["baseUrl"] = value.clone();+ }+ model+ })+ .collect::<Vec<_>>();+ catalog_digests.insert(provider_id, CanonicalDigest::of_bytes(&bytes));+ provider["models"] = declarations.into();+ }+ }+ let providers = Document(providers.into());+ let providers = providers.0.as_object().ok_or(Error::InvalidConfig)?;+ if providers.len() > 256 {+ return Err(Error::ConfigTooLarge);+ }+ let mut items = Vec::new();+ let mut material = None;+ for (provider_id, provider) in providers {+ if provider_id.starts_with("hiroute-") {+ continue;+ }+ if !bounded(provider_id) {+ return Err(Error::InvalidConfig);+ }+ let native_auth = auth.0.get(provider_id);+ let (authentication, secret) = if native_auth.is_some_and(|v| v["type"] == "oauth") {+ (DiscoveredAuthSource::NativeSessionNeedsConfirmation, None)+ } else if native_auth.is_some_and(|v| v["type"] == "api_key") {+ key(+ native_auth.and_then(|v| v.get("key")),+ native_auth.and_then(|v| v.get("env")),+ )+ } else {+ key(provider.get("apiKey"), None)+ };+ let supported_auth = provider.get("oauth").is_none()+ // Additional Bearer headers are not represented by the import contract.+ && provider.get("authHeader").is_none_or(|v| v == &Value::Bool(false))+ && provider.get("modelOverrides").is_none()+ && provider+ .get("headers")+ .is_none_or(|v| v.as_object().is_some_and(|o| o.is_empty()));+ let unknown = vec![serde_json::json!({"id":"unavailable-native-models"})];+ let declarations = provider+ .get("models")+ .map(|v| v.as_array().ok_or(Error::InvalidConfig))+ .transpose()?+ .unwrap_or(&unknown);+ let mut seen = BTreeSet::new();+ for model in declarations {+ if items.len() >= 256 {+ return Err(Error::ConfigTooLarge);+ }+ let id = model+ .get("id")+ .and_then(Value::as_str)+ .filter(|v| bounded(v))+ .ok_or(Error::InvalidConfig)?;+ if !seen.insert(id) {+ return Err(Error::InvalidConfig);+ }+ let protocol = match model+ .get("api")+ .or_else(|| provider.get("api"))+ .and_then(Value::as_str)+ {+ Some("openai-responses") => Some(UpstreamProtocol::Responses),+ Some("openai-completions") => Some(UpstreamProtocol::ChatCompletions),+ Some("anthropic-messages") => Some(UpstreamProtocol::Messages),+ _ => None,+ };+ let endpoint = model+ .get("baseUrl")+ .or_else(|| provider.get("baseUrl"))+ .and_then(Value::as_str);+ let supported_auth = supported_auth+ && model.get("headers").is_none()+ && model.get("oauth").is_none()+ && model+ .get("compat")+ .is_none_or(|_| catalog_digests.contains_key(provider_id.as_str()));+ let source_digest = CanonicalDigest::of(&(+ "pi-api-source/v1",+ &self.layout.pi_config_root,+ provider_id,+ id,+ ))+ .map_err(|_| Error::InvalidConfig)?;+ let source_ref = format!("pi-source/{}", &source_digest.as_str()[7..]);+ let evidence_digest = CanonicalDigest::of(&(+ "pi-api-source-evidence/v1",+ &source_ref,+ &models_digest,+ &auth_digest,+ catalog_digests.get(provider_id.as_str()),+ 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(|_| supported_auth)+ .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: "pi.api-key".into(),+ observed_revision: revision,+ });+ if selected == Some(source_ref.as_str())+ && supported_auth+ && 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)?,+ ));+ }+ items.push(PiApiSource {+ provider_id: provider_id.clone(),+ model_id: id.into(),+ protocol,+ display_name: model+ .get("name")+ .and_then(Value::as_str)+ .filter(|v| bounded(v))+ .unwrap_or(id)+ .into(),+ context_tokens: model.get("contextWindow").and_then(Value::as_u64),+ max_output_tokens: model.get("maxTokens").and_then(Value::as_u64),+ vision: model+ .get("input")+ .and_then(Value::as_array)+ .map(|v| v.iter().any(|i| i == "image")),+ reasoning: model.get("reasoning").and_then(Value::as_bool),+ authentication,+ source_ref,+ evidence_digest,+ revision,+ credential,+ supported_auth: supported_auth && endpoint.is_some(),+ });+ }+ }+ items.sort_by(|a, b| (&a.provider_id, &a.model_id).cmp(&(&b.provider_id, &b.model_id)));+ Ok((items, material))+ }+}diff --git a/crates/integrations/src/agents/qoder.rs b/crates/integrations/src/agents/qoder.rsindex 3ce90773..f34ba0da 100644--- a/crates/integrations/src/agents/qoder.rs+++ b/crates/integrations/src/agents/qoder.rs@@ -8,7 +8,7 @@ use serde_json::{Value, json};#[path = "qoder_budget.rs"]mod budget;-pub use budget::{QoderTokenBudget, qoder_plan_token_budget};+pub use budget::{QoderTokenBudget, pi_plan_token_budget, qoder_plan_token_budget};#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]#[error("Qoder native check failed: {stage}")]diff --git a/crates/integrations/src/agents/qoder_budget.rs b/crates/integrations/src/agents/qoder_budget.rsindex 12f3ab6a..e0fce6d2 100644--- a/crates/integrations/src/agents/qoder_budget.rs+++ b/crates/integrations/src/agents/qoder_budget.rs@@ -12,8 +12,29 @@ pub(super) fn validate_output(tokens: u64) -> Result<(), QoderNativeError> {pub fn qoder_plan_token_budget(plan: &MaterializedAgentPlanV1,) -> Result<QoderTokenBudget, QoderNativeError> {- // Reuse the Plan policy, including total/output/reasoning reservations and- // an explicitly chosen smaller window. Do not reconstruct an input capacity.+ let (context, output) = plan_token_budgets(plan)?;+ QoderTokenBudget::new(context, output).map_err(Into::into)+}++pub fn pi_plan_token_budget(+ plan: &MaterializedAgentPlanV1,+) -> Result<QoderTokenBudget, QoderNativeError> {+ let (context, output) = plan_token_budgets(plan)?;+ let declaration = hiroute_domain::AdditionalAgentModelV1 {+ alias: "hiroute-budget".into(),+ context_window_tokens: context,+ max_output_tokens: output,+ };+ declaration+ .validate_pi()+ .map_err(|_| qoder_error("Pi frozen budget"))?;+ Ok(QoderTokenBudget {+ context_window_tokens: context,+ max_output_tokens: output,+ })+}++fn plan_token_budgets(plan: &MaterializedAgentPlanV1) -> Result<(u64, u64), QoderNativeError> {let context = plan.context_window_tokens().map_err(|_| qoder_error("frozen Plan context budget"))?;@@ -36,11 +57,10 @@ pub fn qoder_plan_token_budget(output = Some(output.map_or(current, |previous: u64| previous.min(current)));}}- QoderTokenBudget::new(+ Ok((context,output.ok_or_else(|| qoder_error("frozen Plan output budget"))?,- )- .map_err(Into::into)+ ))}#[cfg(test)]diff --git a/crates/integrations/src/agents/qoder_native/README.md b/crates/integrations/src/agents/qoder_native/README.mddeleted file mode 100644index ec9e2c5c..00000000--- a/crates/integrations/src/agents/qoder_native/README.md+++ /dev/null@@ -1,94 +0,0 @@-# Qoder additional model routes--This adapter owns one `providers.hiroute-main-<context digest>` entry in the-selected Qoder user settings file. It adds the selected HiRoute Plan aliases to-Qoder's native model selector. It does not import native accounts/models or write-`model.name`, model overrides, purpose routing, hooks, MCP, or Skills.--See the [Agent capability map](../../../../../docs/code-map/README.md) for production owners and representative tests.-The native `providers` shape is tested against Qoder 1.1.65; its public CLI docs-direct users to the `/model` wizard. Treat an upgraded native release as a real-capability/verification boundary, not an automatically compatible configuration API.--## Responsibilities--- [Provider projection](../qoder_provider.rs) shares only the actual provider/model- fields with the transient Worker/probe renderer. Main-Agent configuration omits- the Worker's default model, fixed purpose mapping and extension restrictions.-- [Native edits](../qoder_native.rs) enforce the independent provider namespace,- exact model budgets, semantic ownership and default-reference conflicts.-- [JSON-with-comments edits](../qoder_jsonc.rs) preserve unrelated bytes, including- comments. Ambiguous duplicate keys, invalid JSON and oversized files fail closed.- Line comments support LF and CRLF. Standalone CR and Unicode line separators- inside line comments are rejected because Qoder's settings readers disagree on- their interpretation; no foreign field may be hidden by that disagreement.-- [Operation effects](../qoder_native_effects.rs) use the existing protected- artifact port for snapshot comparison, encrypted restore records, replay and- sensitive staging. The application owns authorization, grants, publication and- restore-first ordering; these functions do not start their own transaction.--`QoderFileConfiguration` receives the prepared connection grant only during-execution. Native `apiKey` contains that local bearer because ordinary Qoder-launches do not inherit a HiRoute token environment variable. The target mode is-0600. Status and reconfiguration use the artifact port’s private reader, which checks-0600 on the same opened file descriptor; restoration may still remove an owned-secret after a permission change. Public Operation payloads contain only the provider, endpoint, aliases and-budgets. Protected restore records must never enter public diagnostics or journals.--Qoder's provider supports fixed native authentication headers, not arbitrary-headers. Its persistent provider therefore uses the explicit local base path-`/_hiroute/qoder/v1`: standard bearer authenticates the current model grant on-`responses` and `models`. This entry reuses Gateway publication, execution and-receipts; it rejects unissued account tokens, run credentials and mixed headers.-The ordinary `/v1/responses` entry retains its separate `X-HiRoute-Token` channel.-Transient Worker and capability-probe settings still use `/v1` with their existing-run/challenge authority. Do not replace this distinction with a global bearer-fallback or a new proxy service.--## Adjustment and recovery--An existing provider cannot be adopted by matching its name. Reconfiguration-requires the preceding Operation's authenticated restore record and unchanged-owned provider semantics. Unrelated user edits survive adjustment and restoration.-An untouched file returns to its exact previous bytes; a changed file loses only-the owned provider member. A harmless empty `providers` container may remain to-preserve user comments. Newly created, untouched files are removed on restoration.--If `model.name` selects an alias being removed, Preview returns-`qoder.default.in-use`. The user must select a different native default first.-Keeping that alias while adjusting other routes or rotating the token is allowed.-Foreign changes inside the owned provider return `qoder.native.fields`; no user-value is included in that diagnostic.--The daemon must bind installed model declarations to the exact settings Operation-and grant, and apply the publication budget compatibility check. These static-native declarations do not refresh themselves when a Plan changes. The pure-`QoderTokenBudget` rule is domain-owned; `qoder_plan_token_budget` projects the-exact compiled Plan, including all active candidate/protocol bounds and existing-context/reasoning reservations. A positive compaction threshold is not a promise-that every prompt or Skill fits.--Backend ownership follows the existing settings transaction; start here when-changing a model route or diagnosing a parked native write:--| Behavior | Owner | Representative evidence |-| --- | --- | --- |-| Preview, independent facets and current installed declaration | [Qoder settings facts](../../../../daemon/src/control/runtime/settings_facts/qoder_model.rs) | Public configure / independent Restore in [settings journeys](../../../../daemon/src/control/runtime/settings_entry_qoder_model_tests.rs) |-| Protected native file execution and original Operation binding | [Qoder native effects](../../../../daemon/src/control/runtime/native_qoder_model.rs) | Journal secrecy, permission drift and conditional restoration in the same journeys |-| Installed budgets constrain publication admission and Install; parked tails retain Control ownership | [Budget and pending-operation guards](../../../../daemon/src/control/runtime/qoder_model_budget.rs) | Budget shrink rollback and exact parked-operation retry in the same journeys |-| Retry the original authorized settings Operation | [Settings retry](../../../../daemon/src/control/runtime/settings_retry.rs) | A second mutation is refused until the original tail completes |-| Real native session matched to Gateway receipts | [Qoder live checks](../../../../daemon/src/control/runtime/agent_live_check_qoder.rs) | [Ordinary startup product journey](../../../../daemon/tests/support/qoder_model_product.py), independent of Worker overlays |-| Persist the verified client surface without rewriting earlier results | [Current surface storage](../../../../local-storage/src/control/surface_check_tests.rs), [surface migration](../../../../local-storage/src/migrations/agent_surface_checks_v25.rs) | Every supported native surface is written through the real repository port; production startup retains earlier raw rows and the key |--## Representative checks--[Native contract tests](../qoder_native_tests.rs) cover preserving native defaults-and foreign providers, two selectable aliases, token rotation with unrelated edits,-conditional restoration, selected-default removal refusal, foreign provider-collision, and malformed/ambiguous JSON. [Plan budget tests](../qoder_budget_tests.rs)-retain the mixed-route, unknown-output and reservation contracts.--These tests do not prove native model calls. Product verification must launch the-installed Qoder against the saved settings without a transient provider/token-overlay, match its session identity to actual Gateway receipts, and preserve the-independent collaboration facet. Login and account capability remain Qoder-owned.diff --git a/crates/integrations/src/agents/qoder_native_tests.rs b/crates/integrations/src/agents/qoder_native_tests.rsindex c5c2d15e..2a224d14 100644--- a/crates/integrations/src/agents/qoder_native_tests.rs+++ b/crates/integrations/src/agents/qoder_native_tests.rs@@ -5,10 +5,10 @@ const PROVIDER: &str ="hiroute-main-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";const ENDPOINT: &str = "http://127.0.0.1:4321/_hiroute/qoder/v1";-fn models() -> Vec<QoderAdditionalModelV1> {+fn models() -> Vec<AdditionalAgentModelV1> {["plan-branch-cheap", "hiroute/0011223344556677"].into_iter()- .map(|alias| QoderAdditionalModelV1 {+ .map(|alias| AdditionalAgentModelV1 {alias: alias.into(),context_window_tokens: 32_768,max_output_tokens: 4096,@@ -21,7 +21,16 @@ fn token(byte: u8) -> AgentAccessGrantMaterial {}fn install(bytes: Option<&[u8]>) -> Edit {- configure(bytes, PROVIDER, ENDPOINT, &models(), &token(3), None).unwrap()+ configure(+ hiroute_domain::AgentKindV1::Qoder,+ bytes,+ PROVIDER,+ ENDPOINT,+ &models(),+ &token(3),+ None,+ )+ .unwrap()}fn value(bytes: &[u8]) -> Value {@@ -86,6 +95,7 @@ fn unrelated_edits_survive_rotation_and_final_restore_without_adopting_owned_dri.replace("\"unrelated\":1", "\"unrelated\":2 /* user changed this */");assert!(first.restore.applied(Some(edited.as_bytes())).unwrap());let rotated = configure(+ hiroute_domain::AgentKindV1::Qoder,Some(edited.as_bytes()),PROVIDER,ENDPOINT,@@ -118,6 +128,7 @@ fn unrelated_edits_survive_rotation_and_final_restore_without_adopting_owned_driassert!(rotated.restore.restore(Some(&drift)).is_err());assert!(configure(+ hiroute_domain::AgentKindV1::Qoder,Some(&drift),PROVIDER,ENDPOINT,@@ -145,6 +156,7 @@ fn removing_selected_native_default_requires_user_switch_but_retaining_it_is_all);assert_eq!(validate_configuration(+ hiroute_domain::AgentKindV1::Qoder,Some(¤t),PROVIDER,ENDPOINT,@@ -156,6 +168,7 @@ fn removing_selected_native_default_requires_user_switch_but_retaining_it_is_all"default in use");let adjusted = configure(+ hiroute_domain::AgentKindV1::Qoder,Some(¤t),PROVIDER,ENDPOINT,@@ -186,6 +199,7 @@ fn existing_provider_is_never_claimed_by_name_and_missing_original_is_removed_exlet first = install(None);assert!(configure(+ hiroute_domain::AgentKindV1::Qoder,Some(&first.bytes),PROVIDER,ENDPOINT,@@ -280,7 +294,18 @@ fn ambiguous_or_malformed_documents_fail_without_normalizing_foreign_settings()br#"{"providers":[]}"#,br#"{"model":{"name":"auto"}} trailing"#,] {- assert!(configure(Some(bytes), PROVIDER, ENDPOINT, &models(), &token(3), None).is_err());+ assert!(+ configure(+ hiroute_domain::AgentKindV1::Qoder,+ Some(bytes),+ PROVIDER,+ ENDPOINT,+ &models(),+ &token(3),+ None+ )+ .is_err()+ );}for separator in ["\r", "\u{2028}", "\u{2029}"] {let ambiguous = format!(@@ -288,6 +313,7 @@ fn ambiguous_or_malformed_documents_fail_without_normalizing_foreign_settings());assert!(configure(+ hiroute_domain::AgentKindV1::Qoder,Some(ambiguous.as_bytes()),PROVIDER,ENDPOINT,@@ -319,11 +345,45 @@ fn ambiguous_or_malformed_documents_fail_without_normalizing_foreign_settings()fn declarations_reject_unknown_budget_duplicate_alias_and_unowned_namespace() {let mut selected = models();selected.push(selected[0].clone());- assert!(validate_declaration(PROVIDER, ENDPOINT, &selected).is_err());- assert!(validate_declaration("hiroute-worker-123", ENDPOINT, &models()).is_err());- assert!(validate_declaration(PROVIDER, "https://external.example/v1", &models()).is_err());+ assert!(+ validate_declaration(+ hiroute_domain::AgentKindV1::Qoder,+ PROVIDER,+ ENDPOINT,+ &selected+ )+ .is_err()+ );+ assert!(+ validate_declaration(+ hiroute_domain::AgentKindV1::Qoder,+ "hiroute-worker-123",+ ENDPOINT,+ &models()+ )+ .is_err()+ );+ assert!(+ validate_declaration(+ hiroute_domain::AgentKindV1::Qoder,+ PROVIDER,+ "https://external.example/v1",+ &models()+ )+ .is_err()+ );selected = models();selected[0].max_output_tokens = 32_000; // the exact 32K/32K zero-threshold regression- assert!(validate_declaration(PROVIDER, ENDPOINT, &selected).is_err());- assert!(validate_declaration(PROVIDER, ENDPOINT, &[]).is_err());+ assert!(+ validate_declaration(+ hiroute_domain::AgentKindV1::Qoder,+ PROVIDER,+ ENDPOINT,+ &selected+ )+ .is_err()+ );+ assert!(+ validate_declaration(hiroute_domain::AgentKindV1::Qoder, PROVIDER, ENDPOINT, &[]).is_err()+ );}diff --git a/crates/integrations/src/agents/registry.rs b/crates/integrations/src/agents/registry.rsindex d9370228..22829072 100644--- a/crates/integrations/src/agents/registry.rs+++ b/crates/integrations/src/agents/registry.rs@@ -22,6 +22,7 @@ pub fn builtin_agent_profiles() -> Vec<AgentProfileV1> {codex_profile_v1(),claude_code_profile_v1(),qoder_collaboration_profile_v1(),+ pi_profile_v1(),]}@@ -113,6 +114,28 @@ pub fn qoder_collaboration_profile_v1() -> AgentProfileV1 {}}+/// Pi owns a single additional provider in models.json; defaults and auth stay native.+pub const PI_PROFILE_ID_V1: &str = "pi-responses-v1";+pub const PI_INTEGRATION_PROFILE_REF_V1: &str = "builtin/pi-responses/v1";++pub fn pi_profile_v1() -> AgentProfileV1 {+ AgentProfileV1 {+ schema: AGENT_PROFILE_SCHEMA_V1.into(),+ profile_id: "pi-responses-v1".into(),+ integration_profile_ref: "builtin/pi-responses/v1".into(),+ kind: AgentKindV1::Pi,+ legacy_exact_versions: BTreeSet::new(),+ ingress_protocol: Some(AgentIngressProtocolV1::Responses),+ config_precedence: AgentKindV1::Pi.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 e5d707c6..b47b36ef 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(), 3);+ assert_eq!(profiles.len(), 4);for profile in &profiles {profile.validate().unwrap();}diff --git a/crates/integrations/src/model_connections/mod.rs b/crates/integrations/src/model_connections/mod.rsindex 3aa5485b..56eb2b07 100644--- a/crates/integrations/src/model_connections/mod.rs+++ b/crates/integrations/src/model_connections/mod.rs@@ -317,6 +317,64 @@ where{return Err(NativeModelConnectionErrorV1::InvalidDraft);}+ self.prepare_static_discovery(draft, credential, discovery_evidence)+ }++ /// Closed native discovery from a trusted scanner. Native observations retain their own+ /// fact bases and do not inherit catalog provenance, prices or subscription qualification.+ pub fn prepare_observed_discovery(+ &self,+ draft: NativeModelConnectionDraftV1,+ credential: NativeModelConnectionCredentialV1<'_>,+ discovery_evidence: CanonicalDigest,+ ) -> Result<ComputeCandidateViewV2, NativeModelConnectionErrorV1> {+ if !matches!(+ &draft.provenance,+ NativeConnectionProvenanceInputV1::UserConfigured { .. }+ ) || draft.models.iter().any(|model| {+ model.catalog_configuration_id.is_some()+ || model.membership != ComputeModelMembershipV2::Observed+ || [+ model.capabilities.tool.basis,+ model.capabilities.vision.basis,+ model.capabilities.streaming.basis,+ model.capabilities.context_tokens.basis,+ model.capabilities.max_output_tokens.basis,+ model.capabilities.native_reasoning.basis,+ ]+ .iter()+ .any(|basis| {+ !matches!(+ basis,+ NativeCandidateFactBasisV1::Observed | NativeCandidateFactBasisV1::Unknown+ )+ })+ }) {+ return Err(NativeModelConnectionErrorV1::InvalidDraft);+ }+ self.prepare_static_discovery(draft, credential, discovery_evidence)+ }++ fn prepare_static_discovery(+ &self,+ draft: NativeModelConnectionDraftV1,+ credential: NativeModelConnectionCredentialV1<'_>,+ discovery_evidence: CanonicalDigest,+ ) -> Result<ComputeCandidateViewV2, NativeModelConnectionErrorV1> {+ if discovery_evidence == CanonicalDigest::of_bytes(&[])+ || draft.candidate_ref.is_none()+ || draft.existing_source_id.is_some()+ || draft.trusted_lineage_digest.is_some()+ || !matches!(+ &credential,+ NativeModelConnectionCredentialV1::Protected {+ descriptor: ProtectedInputSourceDescriptorV1::DiscoveredConfig { .. },+ ..+ }+ )+ {+ return Err(NativeModelConnectionErrorV1::InvalidDraft);+ }validate_draft(&draft, &credential)?;let (candidate_ref, revision) = self.issue_candidate(draft.candidate_ref.as_deref())?;let target = normalize_model_connection_target(ModelConnectionTargetInputV1 {@@ -350,13 +408,22 @@ wheretrue,&draft.runtime_fallback_denied_model_ids,)?;- let NativeConnectionProvenanceInputV1::Registered {- connection_option_id,- registry_version,- catalog_digest,- } = draft.provenance- else {- return Err(NativeModelConnectionErrorV1::InvalidDraft);+ let provenance = match draft.provenance {+ NativeConnectionProvenanceInputV1::Registered {+ connection_option_id,+ registry_version,+ catalog_digest,+ } => ComputeCandidateProvenanceV2::Registered {+ connection_option_id,+ registry_version,+ catalog_digest,+ },+ NativeConnectionProvenanceInputV1::UserConfigured {+ configuration_revision,+ } => ComputeCandidateProvenanceV2::UserConfigured {+ configuration_revision,+ evidence_digest: input_digest.clone(),+ },};let facts = ComputeCandidateFactsV2 {candidate: ComputeCandidateRefV2 {@@ -375,11 +442,7 @@ wheredisplay_name: draft.display_name,existing_source_id: None,evidence_digest: discovery_evidence.clone(),- provenance: ComputeCandidateProvenanceV2::Registered {- connection_option_id,- registry_version,- catalog_digest,- },+ provenance,target: Some(target.candidate_target),authentication: Some(draft.authentication),models,diff --git a/crates/local-storage/src/control/compute/management/tests.rs b/crates/local-storage/src/control/compute/management/tests.rsindex fb2e7c0e..29bc20db 100644--- a/crates/local-storage/src/control/compute/management/tests.rs+++ b/crates/local-storage/src/control/compute/management/tests.rs@@ -332,14 +332,14 @@ fn discovery_change(}}-fn apply_preview(+fn apply_preview<I: ProtectedInputPort>(_stores: &LocalStorageSet,planner: &ComputeManagementPlanner<'_,TrustedComputeCandidateRegistry,ControlStore,LocalSecretStore,- ProtectedInput,+ I,>,coordinator: &TransactionCoordinator<'_,@@ -347,7 +347,7 @@ fn apply_preview(LocalSecretStore,RuntimeStore,NoExternal,- ProtectedInput,+ I,>,workspace: &WorkspaceId,preview: ComputeManagementPreparedPreviewV2,@@ -845,4 +845,97 @@ fn discovered_candidate_config_change_between_preview_and_apply_is_stale_before_);}+#[test]+fn reimport_of_saved_native_source_still_rejects_changed_discovery_without_key_edits() {+ let directory = tempdir().unwrap();+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();+ let workspace = WorkspaceId::default();+ let registry = TrustedComputeCandidateRegistry::new();+ let evidence = CanonicalDigest::of_bytes(b"static-native-source/v1");+ let mut facts = discovered_candidate(evidence.clone());+ facts.provenance = ComputeCandidateProvenanceV2::UserConfigured {+ configuration_revision: 1,+ evidence_digest: facts.evidence_digest.clone(),+ };+ registry.register_compute_candidate(facts.clone()).unwrap();+ let input = DiscoveryProtectedInput::new(evidence);+ let planner =+ ComputeManagementPlanner::new(®istry, stores.control(), stores.secrets(), &input);+ let runtime = TransactionRuntime::default();+ let external = NoExternal;+ let coordinator = TransactionCoordinator::new(+ stores.control(),+ stores.secrets(),+ stores.runtime(),+ &external,+ &input,+ &runtime,+ );+ coordinator.reconcile_startup_and_open().unwrap();+ let snapshot = || {+ hiroute_domain::ComputeManagementRepositoryPort::compute_management_snapshot(+ stores.control(),+ &workspace,+ )+ .unwrap()+ };+ let first = planner+ .preview(discovery_change(&facts, snapshot().revisions))+ .unwrap();+ apply_preview(+ &stores,+ &planner,+ &coordinator,+ &workspace,+ first,+ "native-source-first-save",+ );+ let before = snapshot();+ // A no-key-edit reimport with the same evidence remains a valid product save.+ let repeat = planner+ .preview(discovery_change(&facts, before.revisions))+ .unwrap();+ apply_preview(+ &stores,+ &planner,+ &coordinator,+ &workspace,+ repeat,+ "native-source-unchanged-reimport",+ );+ assert_eq!(+ snapshot().sources[0].credentials,+ before.sources[0].credentials+ );+ let before = snapshot();+ let change = discovery_change(&facts, before.revisions.clone());+ let preview = planner.preview(change.clone()).unwrap();+ let request = ComputeConnectionApplyRequestV1 {+ spec: preview.result.spec,+ accept_digest: preview.result.accept_digest,+ expected_revisions: preview.result.expected_revisions,+ idempotency_key: "native-source-reimport".into(),+ };+ let prepared = planner.prepare_apply(request.clone()).unwrap();+ input.evidence_valid.store(false, Ordering::Release);+ assert!(matches!(+ planner.preview(change),+ Err(ComputeManagementPlanningErrorV2::PreviewStale)+ ));+ assert!(matches!(+ planner.prepare_apply(request),+ Err(ComputeManagementPlanningErrorV2::PreviewStale)+ ));+ assert!(matches!(+ coordinator.accept_prepared(+ &workspace,+ &VerifiedPrincipal::for_local_control(),+ prepared+ ),+ Err(TransactionError::ChangePreviewStale)+ ));+ assert_eq!(snapshot().sources, before.sources);+ assert_eq!(snapshot().revisions, before.revisions);+}+mod disabled;diff --git a/crates/local-storage/src/control/worker_dependencies.rs b/crates/local-storage/src/control/worker_dependencies.rsindex af4843bc..98acfc52 100644--- a/crates/local-storage/src/control/worker_dependencies.rs+++ b/crates/local-storage/src/control/worker_dependencies.rs@@ -628,6 +628,7 @@ pub(super) const fn harness_key(harness: WorkerHarnessV1) -> &'static str {WorkerHarnessV1::CodexCli => "codex_cli",WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",+ WorkerHarnessV1::Pi => "pi",}}@@ -636,6 +637,7 @@ fn parse_harness(value: &str) -> PortResult<WorkerHarnessV1> {"codex_cli" => Ok(WorkerHarnessV1::CodexCli),"claude_code" => Ok(WorkerHarnessV1::ClaudeCode),"qoder_cli" => Ok(WorkerHarnessV1::QoderCli),+ "pi" => Ok(WorkerHarnessV1::Pi),_ => 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 609af68d..981ac411 100644--- a/crates/local-storage/src/control/worker_dependencies_tests.rs+++ b/crates/local-storage/src/control/worker_dependencies_tests.rs@@ -33,6 +33,7 @@ fn selection_operation(WorkerHarnessV1::CodexCli => "codex_cli",WorkerHarnessV1::ClaudeCode => "claude_code",WorkerHarnessV1::QoderCli => "qoder_cli",+ WorkerHarnessV1::Pi => "pi",};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 66e29dba..c85bc134 100644--- a/crates/local-storage/src/migrations/mod.rs+++ b/crates/local-storage/src/migrations/mod.rs@@ -40,6 +40,7 @@ mod worker_dependencies_v20;mod worker_dependencies_v24;#[cfg(test)]mod worker_dependencies_v24_tests;+mod worker_dependencies_v26;mod worker_instance_v19;#[cfg(test)]@@ -48,7 +49,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 = 25;+pub const LATEST_SCHEMA_VERSION: u32 = 26;#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub enum DatabaseKind {@@ -451,7 +452,7 @@ impl MigrationSetCoordinator {LATEST_SCHEMA_VERSION,)?};- if !matches!(set.target_schema_version(), 24 | LATEST_SCHEMA_VERSION)+ if !matches!(set.target_schema_version(), 24 | 25 | LATEST_SCHEMA_VERSION)|| (set.target_schema_version() == 24&& [set.control.manifest(),@@ -700,27 +701,33 @@ fn validate_live_database(}let at_target = version == target_schema_version;if !at_target {- // Only the published stable 23 -> 25 chain has a supported intermediate commit.- // Its original source/target and next-store phase must all agree; arbitrary mixed- // versions are not migration sources. Version 24 must have its real committed ledger.+ // A store may have committed any contiguous step of the published stable chain.+ // The original source/target, current phase and exact ledger must still agree.+ let first = source.schema_version + 1;if recorded_phase != store_phase- || source.schema_version != 23- || target_schema_version != 25- || version != 24+ || !(23..=25).contains(&source.schema_version)+ || !(24..=LATEST_SCHEMA_VERSION).contains(&target_schema_version)+ || version <= source.schema_version+ || version >= target_schema_version|| connection.query_row(- "SELECT COUNT(*) FROM schema_migrations WHERE version >= 24",- [],+ "SELECT COUNT(*) FROM schema_migrations WHERE version >= ?1",+ [first],|row| row.get::<_, u32>(0),- )? != 1- || !connection.query_row(- "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = 24)",- [],- |row| row.get::<_, bool>(0),- )?+ )? != version - source.schema_version{return Err(LocalStorageError::InvalidData);}+ for step in first..=version {+ if !connection.query_row(+ "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = ?1)",+ [step],+ |row| row.get::<_, bool>(0),+ )? {+ return Err(LocalStorageError::InvalidData);+ }+ }}+match kind {DatabaseKind::Control | DatabaseKind::Runtime => {let binding = connection@@ -832,6 +839,8 @@ fn migration_sql(kind: DatabaseKind, version: u32) -> Result<&'static str, Local(DatabaseKind::Runtime | DatabaseKind::Secrets, 24) => Ok(NOOP_V9),(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),_ => Err(LocalStorageError::InvalidData),}}diff --git a/crates/local-storage/src/migrations/startup_format.rs b/crates/local-storage/src/migrations/startup_format.rsindex 925edd94..56587ca3 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 | LATEST_SCHEMA_VERSION) {+ if !matches!(version, 23 | 24 | 25 | LATEST_SCHEMA_VERSION) {return Err(LocalStorageError::UpgradeSourceUnsupported);}let marker = connection.query_row(diff --git a/crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs b/crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rsindex 5a5d1f2d..f657a0a9 100644--- a/crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs+++ b/crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs@@ -82,43 +82,51 @@ fn missing_original_backup_for_old_mixed_versions_refuses_without_adopting_data(}#[test]-fn prior_target24_batch_finishes_and_archives_before_a_new_current_batch() {- for persist_phase in [false, true] {- let directory = crate::test_tempdir().unwrap();- let root = directory.path().join("storage");- let mut set = source_batch(&root, 24);- let backup = set.directory().to_owned();- let source_bytes = fs::read(backup.join("control.db")).unwrap();- let old_id = set.set_id().to_owned();- let key = fs::read(root.join("master-key")).unwrap();- commit_step(&root.join("live/control.db"), DatabaseKind::Control, 24);- if persist_phase {- set.persist_phase(&test_writer_barrier(), BackupSetPhase::ControlMigrated)- .unwrap();- }- drop(set);- assert_latest_and_preserved(&root, &key);- let archived = backup- .parent()- .unwrap()- .join(format!("migration-set.{old_id}"));- let previous = BackupSet::open(&crate::test_storage_authority(), &archived).unwrap();- assert_eq!(previous.target_schema_version(), 24);- assert_eq!(previous.phase(), BackupSetPhase::Completed);- assert_eq!(previous.set_id(), old_id);- assert_eq!(fs::read(archived.join("control.db")).unwrap(), source_bytes);- let current = BackupSet::open(&crate::test_storage_authority(), &backup).unwrap();- assert_ne!(current.set_id(), old_id);- assert_eq!(current.control.manifest().schema_version, 24);- assert_eq!(current.target_schema_version(), LATEST_SCHEMA_VERSION);- assert_eq!(current.phase(), BackupSetPhase::Completed);- assert_latest_and_preserved(&root, &key);- assert_eq!(- BackupSet::open(&crate::test_storage_authority(), backup)+fn prior_target24_or25_batch_finishes_and_archives_before_a_new_current_batch() {+ for target in [24, 25] {+ for persist_phase in [false, true] {+ let directory = crate::test_tempdir().unwrap();+ let root = directory.path().join("storage");+ let mut set = source_batch(&root, target);+ let backup = set.directory().to_owned();+ let source_bytes = fs::read(backup.join("control.db")).unwrap();+ let old_id = set.set_id().to_owned();+ let key = fs::read(root.join("master-key")).unwrap();+ for version in 24..=target {+ commit_step(+ &root.join("live/control.db"),+ DatabaseKind::Control,+ version,+ );+ }+ if persist_phase {+ set.persist_phase(&test_writer_barrier(), BackupSetPhase::ControlMigrated)+ .unwrap();+ }+ drop(set);+ assert_latest_and_preserved(&root, &key);+ let archived = backup+ .parent().unwrap()- .set_id(),- current.set_id()- );+ .join(format!("migration-set.{old_id}"));+ let previous = BackupSet::open(&crate::test_storage_authority(), &archived).unwrap();+ assert_eq!(previous.target_schema_version(), target);+ assert_eq!(previous.phase(), BackupSetPhase::Completed);+ assert_eq!(previous.set_id(), old_id);+ assert_eq!(fs::read(archived.join("control.db")).unwrap(), source_bytes);+ let current = BackupSet::open(&crate::test_storage_authority(), &backup).unwrap();+ assert_ne!(current.set_id(), old_id);+ assert_eq!(current.control.manifest().schema_version, target);+ assert_eq!(current.target_schema_version(), LATEST_SCHEMA_VERSION);+ assert_eq!(current.phase(), BackupSetPhase::Completed);+ assert_latest_and_preserved(&root, &key);+ assert_eq!(+ BackupSet::open(&crate::test_storage_authority(), backup)+ .unwrap()+ .set_id(),+ current.set_id()+ );+ }}}@@ -127,7 +135,7 @@ fn current_batch_resumes_schema24_commit_for_each_recorded_next_store() {for next in 0..3 {let directory = crate::test_tempdir().unwrap();let root = directory.path().join("storage");- let mut set = source_batch(&root, 25);+ let mut set = source_batch(&root, LATEST_SCHEMA_VERSION);let backup = set.directory().to_owned();let id = set.set_id().to_owned();let source_bytes = fs::read(backup.join("control.db")).unwrap();@@ -144,7 +152,9 @@ fn current_batch_resumes_schema24_commit_for_each_recorded_next_store() {{commit_step(&paths[index], kind, 24);if index < next {- commit_step(&paths[index], kind, 25);+ for version in 25..=LATEST_SCHEMA_VERSION {+ commit_step(&paths[index], kind, version);+ }let phase = [BackupSetPhase::ControlMigrated,BackupSetPhase::RuntimeMigrated,diff --git a/crates/local-storage/src/migrations/worker_dependencies_v26.rs b/crates/local-storage/src/migrations/worker_dependencies_v26.rsnew file mode 100644index 00000000..7f775336--- /dev/null+++ b/crates/local-storage/src/migrations/worker_dependencies_v26.rs@@ -0,0 +1,45 @@+//! Extend SDK Worker installation support without decoding or reserializing stored journals.++pub(super) const CONTROL: &str = r#"+CREATE TABLE worker_dependency_selections_v26 (+ workspace_id TEXT NOT NULL,+ harness TEXT NOT NULL CHECK(harness IN ('codex_cli','claude_code','qoder_cli','pi')),+ 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_v26 (+ 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')),+ 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_v26+ SELECT workspace_id, harness, revision, selection_json, owner_operation_id, updated_at+ FROM worker_dependency_selections;+INSERT INTO worker_dependency_selection_effects_v26+ 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_v26 RENAME TO worker_dependency_selections;+ALTER TABLE worker_dependency_selection_effects_v26 RENAME TO worker_dependency_selection_effects;+CREATE INDEX worker_dependency_selection_effects_state+ ON worker_dependency_selection_effects(activated, compensated, operation_id);+"#;diff --git a/docs/code-map/README.md b/docs/code-map/README.mdindex 6b86c049..a24bae6b 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 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/qoder_native/README.md), [Desktop model editor](../../apps/desktop/src/features/agents/QoderModelEditor.tsx) | [Ordinary native startup journey](../../crates/daemon/tests/support/qoder_model_product.py), [five Qoder journeys and evidence limits](../../tools/product-e2e/tests/QODER_DELEGATION.md) |+| 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 || 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) |@@ -23,6 +23,35 @@ Read [architecture and ownership](architecture.md) for cross-module changes,For later decision features, read the [provider and consumer boundaries](decision-foundation.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)+and [closed candidate prepare](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs).+The [Desktop scan projection](../../apps/desktop/src-tauri/src/bridge/model_connection_web.rs)+keeps provider/model identifiers visible while omitting privileged discovery material.+Adding a safe scan field also requires this projection and its existing privacy/visibility+test: a successful machine scan or native compile does not prove that its row reaches the UI.+Provider/model pairs remain distinct; auth commands and OAuth are reported without execution/import.+After save, follow [capability qualification](../../crates/application/src/compute_management/compilation.rs)+and [candidate materialization](../../crates/daemon/src/control/runtime/candidate_execution.rs)+into the compiler's source-local authority and the published Plan. Native-observed+facts retain their provenance and observed budgets; they are not a catalog match+or a runtime fallback. The required saved-source route case in+[Pi acceptance](../../tools/product-e2e/tests/PI_INTEGRATION.md) covers this path with+an ordinary native request, including the case where the UI can display a source+that was not yet usable by Plan consumers.++Native reasoning fields have one current wire owner in+[Domain](../../crates/domain/src/routing/gateway_execution.rs).+[Daemon profile rendering](../../crates/daemon/src/control/runtime/candidate_protocol_profiles.rs)+and [Gateway ingestion](../../crates/gateway/src/profiles/reasoning.rs) reuse its+paths and toggle semantics. The existing producer/consumer test in+[candidate materialization tests](../../crates/daemon/src/control/runtime/candidate_execution_tests.rs)+follows materialization → compilation → Gateway validation across supported+protocols and parameter aliases. Keep that assertion at the boundary when adding+a protocol; duplicating local DTOs or testing only the renderer misses drift.++Shared settings facts have common transaction inputs plus typed Codex, Claude and additional-provider+facts; native model/catalog policies belong to those typed leaves.+For an Agent implementation task, first identify the capability, its state owner,and the failing or representative scenario. Give parallel contributors disjointfile ownership; reserve shared contracts, manifests and generated registries fordiff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex e942b265..fa5df22d 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -51,13 +51,19 @@ not authorize writes or imply Worker support. Start a new ecosystem in its nativadapter and the [Agent feature](../../apps/desktop/src/features/agents/README.md);reuse the existing Application transaction and confirmation contracts. Verifyreal configuration precedence and restoration semantics before generalizing.+For Pi discovery, provider `baseUrl` overrides inherited catalog addresses;+inherited models retain their own API. Provider `api` supplies the default for+explicit model declarations only. The scanner regression in+[filesystem tests](../../crates/integrations/src/agents/filesystem_tests/pi.rs)+checks both cases together; do not generalize all provider fields into one+inheritance rule.Qoder illustrates why these capabilities stay separate. Its main-Agent selectionadds explicit Plan routes without importing native models or taking over thenative default. Its collaboration Skill remains independent, and Worker routinguses transient frozen-task overrides rather than the persistent model provider.The [shared selection](../../crates/domain/src/agents/settings.rs) defines user-intent; the [native budget policy](../../crates/domain/src/agents/qoder_model.rs)+intent; the [native budget policy](../../crates/domain/src/agents/additional_model.rs)is shared by persistent models and Workers. Do not duplicate that policy in arenderer or turn a successful Skill check into model verification. Native livechecks must bind the original client session to the Gateway's receipt authority.@@ -70,7 +76,7 @@ entry; ordinary Responses and transient Worker authority keep their existingauthentication channels. See [Gateway ingress authentication](../../crates/gateway/src/core_runtime/inbound_auth_tests.rs)and [real listener authority](../../tools/e2e-harness/tests/p0_gateway_request_authority.rs)before changing a native provider's endpoint.-The [native provider guide](../../crates/integrations/src/agents/qoder_native/README.md)+The [native provider guide](../../crates/integrations/src/agents/additional_native/README.md)maps JSONC ownership, protected credential delivery and conditional restoration;the [persisted-model journey](../../crates/daemon/tests/support/qoder_model_product.py)documents the normal startup path independently of Worker overrides.diff --git a/docs/code-map/maintenance.md b/docs/code-map/maintenance.mdindex 3ba0d847..d9afe6b3 100644--- a/docs/code-map/maintenance.md+++ b/docs/code-map/maintenance.md@@ -21,11 +21,15 @@ broad rewrite. Test churn alone does not establish redundancy or code decay.| Area | First foundation batch | Next bounded step / exit criterion || --- | --- | --- |-| Agent UI ownership | Group current ecosystem forms, state and request construction under one feature; make dispatch explicit | Use the Qoder integration to assess shared boundaries before adding another adapter abstraction; preserve connect/restore scenarios |+| Agent UI ownership | Group current ecosystem forms, state and request construction under one feature; make dispatch explicit. Pi now reuses Qoder's additional-route editor and native settings transaction | Add native differences in the typed leaf; preserve independent model/Skill configure, edit and restore scenarios without new verification controls |+| Settings facts | Pi separates common transaction facts from typed Codex, Claude and additional-provider facts | Keep capability/catalog requirements in the matching leaf; changing one native ecosystem must not add irrelevant requirements to another |+| Saved native sources | Pi acceptance now follows saved discovery through eligibility, source-local authority, Plan publication and ordinary native startup | Keep a real saved-source route witness when extending discovery; scan visibility or successful save alone does not prove usability |+| Native reasoning wire | Domain owns current field DTOs, protocol paths and binary toggle semantics; daemon and Gateway reuse them | Extend the existing materializer → compiler → Gateway assertion for new wire shapes; retain accepted parameter aliases and custom Bool profile compatibility || Worker native context | [Native user-context reuse and skill inheritance](worker-context.md) | For each new ecosystem, verify native context and per-run overrides; preserve exact continuation, configuration non-pollution, ownership and retention || Decision coupling | Separate existing Jev pure policy from HTTP hosting; give Gateway name resolution a narrow owner | [Separate provider transport from routing/tool policies](decision-foundation.md); future tasks own built-in Jev, provider configuration, natural-language branches and ContextHold tool selection || False-green checks | Bind schema convergence to the authoritative production source; select required browser scenarios by stable identity | Gate tests must reject missing or changed production facts even when a fixture still contains the expected token || Test discovery and layout | Add a product map; replace selected dynamic source-shape checks with behavioral coverage | Consolidate only after recording preserved unique assertions and the layer that owns each one |+| Product runtime binding | Pi reuses native model, collaboration, context, cancellation and compaction journeys across ecosystems | Let shared fixtures accept an explicit production runtime directory: Desktop uses `run/`, while the existing headless fixture uses `runtime/`. Preserve socket ownership/readiness checks and independent receipt assertions; do not encode a second native resource HOME or copy the journey || Large control assembly | Document `LocalControlAdapter` and runtime owners | Extract one cohesive port/consumer during a real feature; avoid a facade-wide rewrite || Worker and observation | Correct stale local ownership docs | Review embedded fixtures, shared process harnesses and constant-only assertions independently; preserve lease, cleanup and content-visibility fault cases || Recovery and compatibility | Document current Configure/Edit, ordinary Disable and legacy-tail distinctions | Keep recent recovery code stable; change only with a concrete failing lifecycle scenario |diff --git a/docs/code-map/testing.md b/docs/code-map/testing.mdindex 42db74e5..d58b2332 100644--- a/docs/code-map/testing.md+++ b/docs/code-map/testing.md@@ -56,6 +56,12 @@ and unique identities, rather than freeze the total number of registered Agents.Keep exact inventory completeness checks at the registry/catalog boundary. Addingan ecosystem should extend its own product assertions without forcing unrelatedprocess, privacy or configuration journeys to change their expected list length.+When adding an Agent profile, update the [built-in registry](../../crates/integrations/src/agents/registry.rs)+and [bundle source](../../assets/agent-profiles/current/profile-seed.json) together.+The [bundle producer](../../assets/release-facts/current/prepare-bundle.py) must reproduce+the committed artifacts without changes on two successive runs. The test planner+selects its `--check` gate for catalog changes and full plans, including integration+preflight; Rust catalog checks alone do not exercise this Python producer.For Agent settings, start from the shared enable/adjust/disable and blocked-actionrecovery journeys in the [feature guide](../../apps/desktop/src/features/agents/README.md).Compare an added ecosystem's interactions with existing ones before turning a newdiff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.mdindex 52ba0e9b..7dd2cd19 100644--- a/docs/code-map/worker-context.md+++ b/docs/code-map/worker-context.md@@ -5,21 +5,96 @@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 history. This page locates those responsibilities. Executable tests define the boundaries described here; validation reports must+configuration and borrowed history; Pi owns its task transcript separately. This page locates those responsibilities. Executable tests define the boundaries described here; validation reports mustrecord their exact revision, environment and scenario outcomes.++## Resource ownership is separate from session ownership++| Ecosystem | Resource discovery | Worker transport | Native history |+| --- | --- | --- | --- |+| 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 |+| 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+empty in-memory credential store, not the user's auth.json: initializing that+native store can execute unrelated credential commands. Only the frozen run's+provider/model, credential and compaction budget enter the SDK runtime. Its+resource settings are read into scope-preserving in-memory snapshots; offline+package discovery retains installed Skills and does not install/update packages.+Extensions and MCP remain excluded from this Worker contract.++Pi native differences live in [SDK rendering](../../crates/daemon/src/delegation/profile/pi.rs),+[protocol bridge](../../crates/daemon/src/delegation/profile/pi_worker_bridge.mjs),+and [selected runtime contract](../../crates/integrations/src/agents/pi_runtime.rs).+Admission, process ownership, cancellation, observation, retention and cleanup+remain the shared owners above. Adding an ecosystem is not a reason to duplicate+their lifecycle or to use Qoder's compaction margin for a different native client.++Use [Pi product entry](../../tools/product-e2e/tests/pi_delegation.rs) and+[shared native context journeys](../../crates/daemon/tests/support/native_context_product.py).+[Pi fixture facts](../../crates/daemon/tests/support/pi_native_context.py) add only+package resources, credential-helper traps and task-owned native history.+The shared boundary journey retains total model POST counts, concurrent native+children, exact Continue and neighbor preservation; missing/corrupt history must+produce zero model calls without repair or replacement.++## Pi compatibility is a capability contract++The acceptance fixture pins a reproducible release; production never compares a+Pi release label with that pin or a version allowlist. The selected CLI's owning+manifest binds its declared `bin.pi` and exported SDK entry. Both are resolved+inside the same package; neither npm directory depth nor an unrelated global SDK+establishes compatibility. See the shared [SDK contract](../../crates/integrations/src/agents/pi_sdk_contract.mjs)+and [local runner](../../crates/integrations/src/agents/pi_runtime.rs).++| User operation | Required local contract | Independent boundary |+| --- | --- | --- |+| Import an explicit static API | Supported native models/auth declarations and credential precedence | No Worker SDK, prompt, helper or OAuth refresh |+| Configure model routes | Offline native model configuration reader preserves the declared API, endpoint and token budgets | No Skill, task session or history interface; Restore remains available after an SDK incompatibility |+| Configure task routing | Native resource loader finds a private Skill; read/bash tool interfaces and the sibling HiRoute CLI are available | No model runtime or Worker session prerequisite; CLI manifest changes invalidate cached resource proof |+| Confirm dependencies / execute a Worker | Selected Node, runtime provider/key binding, resource and new-session interfaces | No native open prerequisite for a new task; actual execution keeps the frozen route and isolated in-memory credentials |+| Continue | Native open plus the exact owned v3 transcript and context/session identity | No new-session create/set-file prerequisite; CLI compatibility does not authorize an unknown history format, migration, row repair or a replacement conversation |++Local checks use private temporary files and empty credentials, disable model+network refresh and extensions, and never prompt a model. Required missing+interfaces or mismatched configuration fail on their own operation; UI keeps the+shared enable/adjust/disable flow. Structural interface checks do not certify all+future releases' semantics. Preserve runtime guards and run the [same native product+journeys](../../tools/product-e2e/tests/PI_INTEGRATION.md) against another explicit+official release before claiming it was actually validated.++The [bridge lifecycle regressions](../../crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs)+exercise the shipped subprocess with a controlled SDK: overlapping session creation,+model rejection, cancellation before history exists, disconnect during creation,+malformed input and a closed output pipe. They do not substitute for native journeys.+Only cancellation can overtake an active request. Disconnect aborts and disposes even+an asynchronously created session; the daemon retains final process-group authority.+The bridge returns `hiroute.pi-worker-failure/v1` with a closed stage vocabulary;+[ACP ingestion](../../crates/daemon/src/delegation/acp/pi_failure.rs) maps those stages+to existing dependency, capability, resume and prompt errors. Raw native exception+messages never enter task results. Startup errors remain correlated with initialize,+because Worker stderr is intentionally discarded. Extend these shared failure cases+when changing the bridge, rather than adding another complete native fixture.++For later ecosystems, separate an acceptance pin, an adapter capability contract+and each persisted history format. Reuse shared lifecycle/fixture owners; extend+only the native leaf and capability regression when the startup protocol differs.+## Follow a task through its owners| 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; 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), [upgrade](../../crates/local-storage/src/migrations/worker_dependencies_v24.rs) | Harness chooses native ACP or adapter ACP. Preserve previous selection and Operation bytes during migration; resume interrupted upgrades only through the existing complete three-store backup coordinator. |+| 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. |+| 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 Qoder main Agent prove it can use task routing? | [Metadata discovery and checks](../../crates/integrations/src/agents/qoder_discovery.rs), [native Skill/CLI verification](../../crates/integrations/src/agents/qoder_probe.rs), [product journey](../../tools/product-e2e/tests/QODER_DELEGATION.md) | A pre-install capability check does not prove the installed user Skill; either scoped check is distinct from actual delegation. Installed-Skill evidence binds the actual user target and trusted CLI result; failed rechecks invalidate prior evidence. These backend facts do not require 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 or QODER_CONFIG_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) | 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. |-| 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/qoder_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. |+| 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. |+| 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. || What exactly does Continue restore? | [Native history binding](../../crates/daemon/src/delegation/profile/native_history.rs), [resume](../../crates/daemon/src/delegation/executor/resume.rs) | Bind exact context and native ID, then restore that session with a fresh run credential. Never adopt the newest file or silently create a replacement session. |@@ -35,7 +110,7 @@ launchers. Neither root grants ownership of the borrowed HOME/config tree.Continue reads the original descriptor instead of today's service environment.Claude requires its exact transcript to be published before successful completion;Codex and Qoder restoration are confirmed by the native ACP load operation,-without scanning the user's history store.+without scanning the user's history store. Pi validates its task-owned v3 transcript before native open; malformed bodies or old headers are rejected without migration, repair or a replacement session.Old Codex/Claude tasks without a borrowed-context descriptor keep their existing private-rootrecovery and cleanup behavior. This one recovery reader is registered in the@@ -87,11 +162,11 @@ successful product check.| Behavior to understand | Representative executable evidence || --- | --- || Select one executable Qoder CLI without adapter placeholders; reject invalid components and preserve the exact confirmed selection | [Native installation boundary tests](../../apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rs), alongside the React `qoder.installation.single-cli` scenario in [Desktop tests](../../apps/desktop/tests/README.md). The native tests also retain window ownership, one-shot use, replacement and expiry guarantees. |-| Enable or restore a main Agent's collaboration without configuring its models; preserve Skill ownership and report drift | [Independent collaboration facts](../../crates/daemon/src/control/runtime/settings_facts/qoder.rs), [public settings transaction scenarios](../../crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs) (historically registered beneath native_model tests; these are collaboration tests) |+| Enable or restore a main Agent's collaboration without configuring its models; preserve Skill ownership and report drift | [Independent collaboration facts](../../crates/daemon/src/control/runtime/settings_facts/additional_model.rs), [public settings transaction scenarios](../../crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs) (historically registered beneath native_model tests; these are collaboration tests) || Upgrade an existing CLI selection while an operation is staged, activated or complete; replay and conditionally restore its owner | [Original producer fixture and provenance](../../crates/local-storage/src/migrations/fixtures/README.md), [production startup upgrade scenarios](../../crates/local-storage/src/migrations/worker_dependencies_v24_tests.rs) || Discover and invoke user/project skills; Continue the same session after restart and replacement of the Plan's source/model | [Real installed native Worker entry](../../tools/product-e2e/tests/worker_native_context.rs), [core journey](../../crates/daemon/tests/support/native_context_product.py) || Route simultaneous tasks independently in one native context; cancel one native tool while its neighbor completes; refuse Continue when its exact transcript is missing | [Boundary journey](../../crates/daemon/tests/support/native_context_boundaries.py), [boundary assertion guide](../../crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md) |-| Keep native tool summaries and automatic compaction on the frozen route, then Continue the same compacted session | [Qoder auxiliary-route journey](../../crates/daemon/tests/support/qoder_compaction_product.py), [version-pinned evidence limits](../../tools/product-e2e/tests/QODER_DELEGATION.md) |+| Keep native tool summaries and automatic compaction on the frozen route, then Continue the same compacted session | [Qoder auxiliary-route journey](../../crates/daemon/tests/support/qoder_compaction_product.py), [shared native compaction journey](../../crates/daemon/tests/support/native_compaction_product.py), version-pinned [Qoder](../../tools/product-e2e/tests/QODER_DELEGATION.md) / [Pi](../../tools/product-e2e/tests/PI_INTEGRATION.md) limits || Token-free native startup, shared settings unchanged, restricted tools preserved | [Profile tests](../../crates/daemon/src/delegation/profile/tests.rs), [native context tests](../../crates/daemon/src/delegation/profile/native_context.rs) || Exact history identity and borrowed/owned retention | [History contracts](../../crates/daemon/src/delegation/profile/native_history_tests.rs), [material lifetime tests](../../crates/daemon/src/delegation/profile/materials_tests.rs) || Model selection must succeed before prompt | [ACP boundary](../../crates/daemon/src/delegation/acp/mod.rs) and its model/session tests |@@ -112,6 +187,11 @@ cross-routing, fabricated child completion and replacement native history.These checks validate the test inputs and verdicts without claiming native-clientor Desktop behavior; keep them separate from the product assertions above.+The [shared native installation fixture](../../crates/daemon/tests/support/agent_product_support.py)+exposes the selected CLI and Pi's selected Node in the product's private PATH.+Passing Node only to a Worker argv does not make that runtime available to main+Agent model or collaboration checks; keep both paths bound to the same installation.+Use the [test planner](../../scripts/test-plan.py) for affected checks and explicitreal-Agent commands. The normal Rust suite compiles ignored native targets butdoes not execute them. Linux headless and macOS Desktop use real daemon, Gateway,@@ -128,6 +208,10 @@ Pilot includes `desktop-runtime`; without runtime the native bridge is excluded.and Linux backend checks cannot establish that the typed Desktop consumer compiles.The installation unit-test filter is `bridge::worker_tasks::tests`; real Desktopselection and task execution remain separate Pilot acceptance evidence.+Native route prerequisite checks are registered under `session::checks::tests`;+model scan projection checks are under `bridge::model_connection_web::tests`.+Use the actual module filters and retain selected-test counts: a zero-selected+Rust success cannot satisfy a required behavior gate.## Adding an ecosystem@@ -150,3 +234,15 @@ Worker change does not implement built-in Jev.The implementation retainsHiRoute's explicit environment and ownership contracts rather than importing anentire daemon environment or copying a user's configuration tree.++Pi discovery preserves provider `baseUrl`/`api` overrides on inherited catalog models;+explicit model overrides retain their precedence. Additional `authHeader` authentication+is reported as not importable until the import contract can preserve it. A valid Claude+prepare does not depend on unrelated Pi configuration being readable.++Pi v3 history accepts validated branch-local `context_edit` omissions/replacements,+including native overflow recovery, without rewriting original messages. Unknown formats,+missing targets and invalid replacement content still fail closed. The Pi native product+suite covers both threshold compaction and recoverable-length compaction followed by exact+Continue. Concurrent-route acceptance checks rejected HTTP attempts as well as accepted+model receipts, so a rejected wrong credential/endpoint/model cannot disappear from evidence.diff --git a/scripts/check-contract-convergence.py b/scripts/check-contract-convergence.pyindex 659e6043..284736cc 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 = 25+EXPECTED_DATABASE_SCHEMA_VERSION = 26VERSION_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 fc4f67e3..1e22077a 100755--- a/scripts/ci-shards.py+++ b/scripts/ci-shards.py@@ -82,6 +82,7 @@ INTEGRATION_SHARDS = {("hiroute-product-e2e", "cpa_connector"),("hiroute-product-e2e", "gateway_adapter_contract"),("hiroute-product-e2e", "local_observation"),+ ("hiroute-product-e2e", "pi_delegation"),("hiroute-product-e2e", "product_oracle"),("hiroute-product-e2e", "qoder_delegation"),("hiroute-product-e2e", "routing_plans"),diff --git a/scripts/desktop-pilot.py b/scripts/desktop-pilot.pyindex 697d1e8d..fa909562 100755--- a/scripts/desktop-pilot.py+++ b/scripts/desktop-pilot.py@@ -113,6 +113,8 @@ def launch_environment("CODEX_CONFIG", "CODEX_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "GEMINI_API_KEY","OPENROUTER_API_KEY", "HIROUTE_RUN_TOKEN", "CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY",+ "DEEPSEEK_API_KEY", "GROQ_API_KEY", "MISTRAL_API_KEY", "XAI_API_KEY",+ "CEREBRAS_API_KEY",):environment.pop(key)environment["HOME"] = str(process_home)@@ -121,6 +123,7 @@ def launch_environment(environment["CODEX_HOME"] = str(process_home / ".codex")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")if diagnostic_override is not None:environment[DIAGNOSTIC_LEVEL_ENV] = diagnostic_overridereturn environmentdiff --git a/scripts/test-agent-product-support.py b/scripts/test-agent-product-support.pyindex 291893d6..7a2bc9ce 100644--- a/scripts/test-agent-product-support.py+++ b/scripts/test-agent-product-support.py@@ -1,6 +1,7 @@#!/usr/bin/env python3"""Shared native product-fixture mechanics; no native Agent or product acceptance claim."""import os+import shutilfrom pathlib import Pathimport subprocessimport sys@@ -10,7 +11,23 @@ import unittestsys.dont_write_bytecode = Truesys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'crates/daemon/tests/support'))-from agent_product_support import apply_settings, run_native_command+from agent_product_support import apply_settings, run_native_command, expose_native_installation+++class NativeInstallationTests(unittest.TestCase):+ def test_selected_cli_and_required_runtime_share_the_private_fixture_path(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ (root / 'bin').mkdir()+ cli = root / 'selected-cli'; cli.write_text('fixture'); cli.chmod(0o700)+ node = root / 'selected-node'; node.write_text('fixture'); node.chmod(0o700)+ product = SimpleNamespace(root=root)+ with self.assertRaisesRegex(AssertionError, 'requires its selected Node'):+ expose_native_installation(product, 'pi', cli)+ self.assertFalse((root / 'bin/pi').exists())+ expose_native_installation(product, 'pi', cli, node)+ self.assertEqual(Path(shutil.which('pi', path=str(root / 'bin'))).resolve(), cli)+ self.assertEqual(Path(shutil.which('node', path=str(root / 'bin'))).resolve(), node)class SettingsJourneyTests(unittest.TestCase):diff --git a/scripts/test-contract-convergence.py b/scripts/test-contract-convergence.pyindex 502a8ee1..a0a57d9e 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 = 25;\n"+ "pub const LATEST_SCHEMA_VERSION: u32 = 26;\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, 26):+ for version in (17, 22, 23, 24, 25, 27):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 = 25;",+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 26;",})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 = 25;\n}\n",- "/*\npub const LATEST_SCHEMA_VERSION: u32 = 25;\n*/\n",- "pub const LATEST_SCHEMA_VERSION: u32 = 25;\npub const LATEST_SCHEMA_VERSION: u32 = 26;\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",):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 = 25;",+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 26;",})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 = 25;\n"+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 26;\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 = 25;\n"+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 26;\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 = 25;\n"+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 26;\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 = 25;+pub const LATEST_SCHEMA_VERSION: u32 = 26;'''self.assertEqual(self.run_audit({"legacy.rs": '"hiroute.sample/v1"',diff --git a/scripts/test-desktop-pilot.py b/scripts/test-desktop-pilot.pyindex 241997f4..5f76446a 100644--- a/scripts/test-desktop-pilot.py+++ b/scripts/test-desktop-pilot.py@@ -589,13 +589,15 @@ class ExistingDataRootTests(unittest.TestCase):with mock.patch.dict(os.environ, {"HOME": "/real-user-home","CODEX_HOME": "/daily-codex","CLAUDE_CONFIG_DIR": "/daily-claude",- "QODER_CONFIG_DIR": "/daily-qoder"}):+ "QODER_CONFIG_DIR": "/daily-qoder",+ "PI_CODING_AGENT_DIR": "/daily-pi"}):environment = pilot.launch_environment(runtime, temporary, self.data, self.data)self.assertEqual(os.environ["CODEX_HOME"], "/daily-codex")self.assertEqual(environment["HOME"], str(self.data))self.assertEqual(environment["CODEX_HOME"], str(self.data / ".codex"))self.assertEqual(environment["CLAUDE_CONFIG_DIR"], str(self.data / ".claude"))self.assertEqual(environment["QODER_CONFIG_DIR"], str(self.data / ".qoder"))+ self.assertEqual(environment["PI_CODING_AGENT_DIR"], str(self.data / ".pi/agent"))self.assertEqual(environment["HIROUTE_DESKTOP_TEST_ROOT"], str(self.data))self.assertEqual(environment["XDG_RUNTIME_DIR"], str(runtime))self.assertEqual(environment["TMPDIR"], str(temporary))@@ -606,7 +608,8 @@ class ExistingDataRootTests(unittest.TestCase):'CODEX_CONFIG', 'CODEX_API_KEY', 'AWS_PROFILE', 'GOOGLE_APPLICATION_CREDENTIALS','OPENROUTER_API_KEY', 'AZURE_OPENAI_API_KEY', 'HIROUTE_RUN_TOKEN','CLAUDE_CODE_USE_BEDROCK', 'QODER_PERSONAL_ACCESS_TOKEN', 'QODER_MODEL',- 'QODER_SUBAGENT_MODEL')}+ 'QODER_SUBAGENT_MODEL', 'DEEPSEEK_API_KEY', 'GROQ_API_KEY', 'MISTRAL_API_KEY',+ 'XAI_API_KEY', 'CEREBRAS_API_KEY')}with mock.patch.dict(os.environ, variables):isolated = pilot.launch_environment(self.session, self.session, self.data, self.data)ordinary = pilot.launch_environment(self.session, self.session, self.data, None)diff --git a/scripts/test-native-context-boundaries.py b/scripts/test-native-context-boundaries.pyindex 74d58a1a..606c793d 100644--- a/scripts/test-native-context-boundaries.py+++ b/scripts/test-native-context-boundaries.py@@ -41,6 +41,30 @@ class NativeBoundaryTests(unittest.TestCase):for key in ('contents', 'executed'))})return body+ def test_rejected_wrong_route_attempt_cannot_hide_behind_accepted_ledger(self):+ from native_context_fixture import NativeContextUpstream+ for path, token, model in [('/v1/responses', 'wrong', 'gpt-5.4'),+ ('/wrong', NativeContextUpstream.token, 'gpt-5.4'),+ ('/v1/responses', NativeContextUpstream.token, 'wrong')]:+ with self.subTest(path=path, model=model):+ source = NativeContextUpstream(self.root)+ try:+ ledger = self.root / 'native-context-events.jsonl'+ ledger.write_text(json.dumps({'state':'green', 'model':source.model}) + '\n')+ boundary.assert_source_routing(source)+ connection = http.client.HTTPConnection(*source.server.server_address)+ connection.request('POST', path, json.dumps({'model':model}),+ {'Authorization':'Bearer ' + token})+ response = connection.getresponse()+ self.assertGreaterEqual(response.status, 400)+ response.read()+ connection.close()+ self.assertEqual(len(boundary.source_events(source)), 1)+ with self.assertRaisesRegex(AssertionError, 'rejected model request'):+ boundary.assert_source_routing(source)+ finally:+ source.close()+def test_cross_routed_request_fails_before_tool_execution(self):target = boundary.prepare_heartbeat(self.fixture, 'target')body = self.body(target)diff --git a/scripts/test-native-context-product.py b/scripts/test-native-context-product.pyindex 25b536b1..454f92de 100644--- a/scripts/test-native-context-product.py+++ b/scripts/test-native-context-product.py@@ -218,6 +218,12 @@ class NativeContextOracleTests(unittest.TestCase):'CLAUDE_CODE_OAUTH_TOKEN': 'synthetic-parent-token','CODEX_CONFIG': 'synthetic-parent-config', 'AWS_PROFILE': 'daily','QODER_CONFIG_DIR': '/daily/qoder',+ 'PI_CODING_AGENT_DIR': '/daily/pi',+ 'DEEPSEEK_API_KEY': 'synthetic-deepseek-secret',+ 'GROQ_API_KEY': 'synthetic-groq-secret',+ 'MISTRAL_API_KEY': 'synthetic-mistral-secret',+ 'XAI_API_KEY': 'synthetic-xai-secret',+ 'CEREBRAS_API_KEY': 'synthetic-cerebras-secret','HIROUTE_WORKER_RECEIPT_DIR': '/daily/worker-receipts','QODER_PERSONAL_ACCESS_TOKEN': 'synthetic-qoder-secret'}):product = Product(REPO, root=self.root / 'product')@@ -225,6 +231,7 @@ class NativeContextOracleTests(unittest.TestCase):self.assertEqual(product.env['CODEX_HOME'], str(home / '.codex'))self.assertEqual(product.env['CLAUDE_CONFIG_DIR'], str(home / '.claude'))self.assertEqual(product.env['QODER_CONFIG_DIR'], str(home / '.qoder'))+ self.assertEqual(product.env['PI_CODING_AGENT_DIR'], str(home / '.pi/agent'))receipt_root = str(product.root / 'worker-receipts')self.assertEqual(product.env['HIROUTE_WORKER_RECEIPT_DIR'], receipt_root)# Borrowing a normally logged-in native HOME must not borrow HiRoute's@@ -234,7 +241,8 @@ class NativeContextOracleTests(unittest.TestCase):neighbor = Product(REPO, root=self.root / 'neighbor-product')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'):+ for key in ('CLAUDE_CODE_OAUTH_TOKEN', 'CODEX_CONFIG', 'AWS_PROFILE', 'QODER_PERSONAL_ACCESS_TOKEN',+ 'DEEPSEEK_API_KEY', 'GROQ_API_KEY', 'MISTRAL_API_KEY', 'XAI_API_KEY', 'CEREBRAS_API_KEY'):self.assertNotIn(key, product.env)def test_proxy_trap_records_any_method_without_request_content(self):diff --git a/scripts/test-plan.py b/scripts/test-plan.pyindex 807ab5e9..2f3ceb88 100644--- a/scripts/test-plan.py+++ b/scripts/test-plan.py@@ -40,6 +40,8 @@ WORKER_FIXTURE_TOOLING = {"scripts/test-agent-product-support.py","scripts/test-native-context-boundaries.py","scripts/test-qoder-product.py"}WORKER_BOOTSTRAP_TEST = "crates/daemon/src/delegation/profile/claude_adapter_bootstrap.test.mjs"+PI_WORKER_BRIDGE_TEST = "crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs"+PI_SDK_CONTRACT_TEST = "crates/integrations/src/agents/pi_sdk_contract.test.mjs"INTEGRATION_SKILL = ".agents/skills/hiroute-integrate/SKILL.md"WEBSITE_TOOLING = {".github/workflows/website.yml", ".github/workflows/release.yml"}WEBSITE_PREFIXES = ("apps/website/", ".github/scripts/", "news/", "experiments/")@@ -131,6 +133,20 @@ WORKER_PRODUCT_CHECKS = {"HIROUTE_QODER_MODEL_CONTEXT_HOME", "HIROUTE_QODER_MODEL_CONFIG_DIR"],"missing_environment": "fail",},+ "pi_delegation": {+ "id": "pi.delegation", "harnesses": ["pi"],+ "guide": "tools/product-e2e/tests/PI_INTEGRATION.md",+ "required_tests": [+ "pi_worker_uses_native_skills_and_continues_the_frozen_task",+ "pi_workers_route_independently_and_reject_missing_or_corrupt_history",+ "pi_agent_saved_model_routes_preserve_defaults_and_restore_independently",+ "pi_agent_uses_installed_user_skill_to_delegate_through_public_cli",+ "pi_worker_compaction_uses_frozen_route_and_continues_exact_history",+ "pi_worker_recovers_length_overflow_and_continues_edited_history",+ "pi_static_api_discovery_imports_effective_source_and_rejects_stale_save"],+ "required_environment": ["HIROUTE_PRODUCT_CANDIDATE_SHA", "HIROUTE_WORKER_PI_BINARY", "HIROUTE_WORKER_NODE"],+ "missing_environment": "fail",+ },}OPT_IN_WORKER_TARGETS = set(WORKER_PRODUCT_CHECKS)PRODUCT_GUIDES = {entry["guide"] for entry in WORKER_PRODUCT_CHECKS.values()} | {@@ -165,6 +181,24 @@ QODER_PRODUCT_PATHS = {"crates/integrations/src/agents/settings_discovery.rs","crates/integrations/src/agents/executable.rs",}+PI_PRODUCT_PREFIXES = (+ "crates/integrations/src/agents/pi", "crates/daemon/src/delegation/profile/pi",+ "crates/daemon/src/control/runtime/model_connections/pi",+ "crates/integrations/src/agents/filesystem_tests/pi",+)+ADDITIONAL_MODEL_PREFIXES = (+ "crates/integrations/src/agents/additional_native",+ "crates/application/src/agent_connection/additional_model",+ "crates/domain/src/agents/additional_model",+ "crates/daemon/src/control/runtime/native_additional_model",+ "crates/daemon/src/control/runtime/additional_model",+ "crates/daemon/src/control/runtime/settings_facts/additional_model",+)+ADDITIONAL_NATIVE_FIXTURE_PREFIXES = (+ "crates/daemon/tests/support/additional_model_",+ "crates/daemon/tests/support/collaboration_",+ "crates/daemon/tests/support/native_compaction_",+)# These helpers also serve publication/model journeys. Add the known real Worker gates# without pretending their complete ordinary-test dependency graph is bounded here.SHARED_WORKER_FIXTURES = {@@ -180,8 +214,12 @@ 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")]- if path == "crates/daemon/tests/support/agent_product_support.py" or path.startswith("crates/daemon/tests/support/qoder_"):+ return [("hiroute-product-e2e", name) for name in ("worker_native_context", "qoder_delegation", "pi_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")]+ if path.startswith("crates/daemon/tests/support/pi_"):+ return [("hiroute-product-e2e", "pi_delegation")]+ if path.startswith("crates/daemon/tests/support/qoder_"):return [("hiroute-product-e2e", "qoder_delegation")]if path == "tools/e2e-harness/tests/p0_gateway_runtime.rs" or path.startswith("tools/e2e-harness/tests/p0_gateway_runtime/"):return [("hiroute-e2e", "p0_gateway_runtime"), ("hiroute-e2e", "p0_gateway_protocol"),@@ -213,8 +251,14 @@ 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 in QODER_PRODUCT_PATHS or path.startswith(QODER_PRODUCT_PREFIXES):+ if path.startswith(PI_PRODUCT_PREFIXES):+ selected.add("pi_delegation")+ elif path.startswith(ADDITIONAL_MODEL_PREFIXES):+ selected.update(("qoder_delegation", "pi_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")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)@@ -342,6 +386,13 @@ def select(paths, full=False):(feature_flags if target == "p0_gateway_runtime" else []) +(["--", "--test-threads=1"] if target in PROCESS_TARGETS else []))rust = bool(commands)+ if full or any(path.startswith(("assets/agent-profiles/", "assets/release-facts/",+ "tools/release-facts/"))+ or path == "crates/integrations/src/agents/registry.rs"+ for path in paths):+ # Rust catalog tests use builtin profiles; the Python bundle producer+ # also consumes profile-seed.json. Check that path before integration.+ commands.append(["python3", "assets/release-facts/current/prepare-bundle.py", "--check"])if "diagnostics" in groups and not full:reasons.append("diagnostic implementation: expand if caller API, protocol, routing or Worker behavior changes")commands.append(["python3", "scripts/test-desktop-pilot.py"])@@ -360,6 +411,10 @@ def select(paths, full=False):commands.append(["python3", "scripts/test-qoder-product.py"])if full or any(path.startswith("crates/daemon/src/delegation/profile/") for path in paths):commands.append(["node", "--test", WORKER_BOOTSTRAP_TEST])+ if full or any(path.startswith(("crates/integrations/src/agents/pi_",+ "crates/daemon/src/delegation/profile/pi")) for path in paths):+ commands.append(["node", "--test", PI_SDK_CONTRACT_TEST])+ commands.append(["node", "--test", PI_WORKER_BRIDGE_TEST])if full or release_contract_tooling:commands.extend([["python3", "scripts/test-release-contracts.py"],["python3", "scripts/test-release-contract-pr.py"],diff --git a/scripts/test-qoder-product.py b/scripts/test-qoder-product.pyindex d01cd378..52c5f88a 100644--- a/scripts/test-qoder-product.py+++ b/scripts/test-qoder-product.py@@ -18,11 +18,11 @@ REPO = Path(__file__).resolve().parents[1]sys.path.insert(0, str(REPO / 'crates/daemon/tests/support'))import native_context_fixture as oracleimport qoder_native_context as qoder-import qoder_collaboration_product as collaboration-from qoder_collaboration_fixture import MainAgentOracle, worker_decision, output_envelope-from qoder_compaction_product import CompactionOracle, PRESSURE_TOKENS, assert_native_compaction-import qoder_model_fixture as model_fixture-import qoder_model_product as model_product+import collaboration_product as collaboration+from collaboration_fixture import MainAgentOracle, worker_decision, output_envelope+from native_compaction_product import CompactionOracle, PRESSURE_TOKENS, assert_native_compaction+import additional_model_fixture as model_fixture+import additional_model_product as model_productclass QoderFixtureContext:diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.pyindex 129b84f6..34ec98b7 100644--- a/scripts/test-test-plan.py+++ b/scripts/test-test-plan.py@@ -20,6 +20,35 @@ runner_spec.loader.exec_module(runner)class SelectionTests(unittest.TestCase):+ def test_pi_runtime_contract_changes_select_local_capability_regressions(self):+ check = ['node', '--test', plan.PI_SDK_CONTRACT_TEST]+ for path in ('crates/integrations/src/agents/pi_runtime.rs',+ 'crates/integrations/src/agents/pi_sdk_contract.mjs',+ 'crates/daemon/src/delegation/profile/pi_worker_bridge.mjs'):+ with self.subTest(path=path):+ result = plan.select([path])+ self.assertIn(check, result['commands'])+ self.assertIn(['node', '--test', plan.PI_WORKER_BRIDGE_TEST], result['commands'])+ self.assertIn(check, plan.integration_preflight(result)['commands'])+ self.assertIn(check, plan.select([], full=True)['commands'])+ self.assertNotIn(check, plan.select(['apps/desktop/src/ui/assets/pi.svg'])['commands'])++ def test_agent_catalog_changes_select_the_source_to_bundle_check(self):+ command = ['python3', 'assets/release-facts/current/prepare-bundle.py', '--check']+ for path in (+ 'assets/agent-profiles/current/profile-seed.json',+ 'assets/release-facts/current/bundle/agent-profiles.json',+ 'assets/release-facts/current/prepare-bundle.py',+ 'crates/integrations/src/agents/registry.rs',+ 'tools/release-facts/src/lib.rs',+ ):+ with self.subTest(path=path):+ result = plan.select([path])+ self.assertIn(command, result['commands'])+ self.assertIn(command, plan.integration_preflight(result)['commands'])+ self.assertIn(command, plan.select([], full=True)['commands'])+ self.assertNotIn(command, plan.select(['docs/code-map/testing.md'])['commands'])+def test_worker_contract_alone_requires_feature_enabled_mac_consumers(self):for path in ('crates/application-api/src/worker.rs','crates/domain/src/delegation/mod.rs',@@ -85,7 +114,7 @@ class SelectionTests(unittest.TestCase):self.assertFalse(result['native_required'])self.assertFalse(any('--ignored' in command for command in result['commands']))- def test_qoder_leaf_and_shared_collaboration_changes_select_only_qoder_gate(self):+ def test_native_leaves_and_shared_collaboration_select_their_real_consumers(self):for path in ('crates/daemon/tests/support/qoder_native_context.py','crates/daemon/tests/support/qoder_collaboration_product.py',@@ -107,8 +136,8 @@ class SelectionTests(unittest.TestCase):):with self.subTest(path=path):result = plan.select([path])- self.assertEqual([check['command'][6] for check in result['product_checks']],- ['qoder_delegation'])+ 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']+ 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.self.assertEqual(plan.select([@@ -119,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'])+ self.assertEqual([check['command'][6] for check in result['product_checks']], ['qoder_delegation', 'pi_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'], [])@@ -133,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'})+ {'worker_native_context', 'qoder_delegation', 'pi_delegation'})def test_qoder_production_gates_preserve_ordinary_owner_checks_and_deduplicate(self):result = plan.select(['crates/integrations/src/agents/qoder.rs',@@ -149,6 +178,19 @@ class SelectionTests(unittest.TestCase):plan.OPT_IN_WORKER_TARGETS)self.assertEqual(plan.select(['scripts/test-qoder-product.py'])['product_checks'], [])+ def test_shared_native_model_and_collaboration_journeys_select_both_consumers(self):+ for path in ('crates/daemon/tests/support/additional_model_product.py',+ 'crates/daemon/tests/support/collaboration_fixture.py',+ 'crates/daemon/tests/support/native_compaction_product.py',+ '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'})+ 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'])+ self.assertEqual(checks[0]['missing_environment'], 'fail')+def test_qoder_guide_and_settings_docs_do_not_expand_product_scope(self):result = plan.select(['tools/product-e2e/tests/QODER_DELEGATION.md','docs/test-selection.md'])@@ -163,7 +205,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 4)+ self.assertEqual(len(required), 1 if path.endswith('worker_native_context.rs') else 5)self.assertEqual(required[0]['id'], 'worker.native-context')self.assertEqual(required[0]['harnesses'], ['codex', 'claude'])self.assertIn('--ignored', required[0]['command'])@@ -206,7 +248,7 @@ class SelectionTests(unittest.TestCase):self.assertFalse(result['frontend'])targets = plan.e2e_consumers('tools/product-e2e/tests/worker_product_support/mod.rs')self.assertEqual({target for _, target in targets},- {'worker_delegation', 'worker_read', 'worker_native_context', 'qoder_delegation'})+ plan.OPT_IN_WORKER_TARGETS)self.assertIn(['cargo', 'clippy', '--locked', '-p', 'hiroute-product-e2e','--all-targets', '--all-features', '--', '-D', 'warnings'], result['commands'])self.assertFalse(any(command[:2] == ['cargo', 'test'] for command in result['commands']))diff --git a/tools/product-e2e/tests/PI_INTEGRATION.md b/tools/product-e2e/tests/PI_INTEGRATION.mdnew file mode 100644index 00000000..04c8deb4--- /dev/null+++ b/tools/product-e2e/tests/PI_INTEGRATION.md@@ -0,0 +1,104 @@+# Pi product acceptance++[Product test map](../../../docs/code-map/testing.md) · [Worker owners](../../../docs/code-map/worker-context.md)++Pi reuses the product's settings, publication, Worker lifecycle and Gateway.+Its native leaves implement official npm SDK discovery, effective static API+sources, resource loading and one exact task transcript. There is no subscription+or OAuth import, separate user verification action, or native extension/MCP claim.++## Run contract++Use the Linux or Mac test environment described in the+[product test map](../../../docs/code-map/testing.md).+[Hosted CI](../../../docs/github-actions-validation.md) does not execute these+installed native clients. Select an exact committed+candidate and an explicitly installed official `@earendil-works/pi-coding-agent`+CLI with Node >=22.19. The reproducible reference fixture uses 1.0.2; compatibility+runs may select another exact release, including 1.0.1, without changing the journeys.+This acceptance pin is not production admission: the+[operation-specific contract](../../../docs/code-map/worker-context.md#pi-compatibility-is-a-capability-contract)+checks actual required interfaces and local behavior. The SDK must be exported by+the selected CLI's own package; an unrelated global SDK is not a substitute.+Set absolute `HIROUTE_WORKER_PI_BINARY`, `HIROUTE_WORKER_NODE` and full+`HIROUTE_PRODUCT_CANDIDATE_SHA`. Missing inputs fail instead of skipping silently.++```sh+cargo test --locked -p hiroute-product-e2e --test pi_delegation -- \+ --ignored --nocapture --test-threads=1+```++This starts production `hirouted`, public `hiroute`, Gateway and official Pi.+Only the model upstreams are deterministic. The fixture creates a private native+HOME/config/project for the scenario; production Workers borrow the calling+instance's effective HOME and `PI_CODING_AGENT_DIR`, never a replacement task HOME.+User, project and already installed package Skills retain their native precedence.++## Product outcomes and their witnesses++| User outcome | Shared journey / Pi difference | Required witness |+| --- | --- | --- |+| Run and Continue the original delegated task after restart and Plan replacement | [Native context](../../../crates/daemon/tests/support/native_context_product.py); [Pi resources/history](../../../crates/daemon/tests/support/pi_native_context.py) | Actual user/project/package Skill read and shell receipts; exact native session, old frozen route, no replay POST; 16,384/4,096 context/output boundary |+| Concurrent routes stay separate; cancellation stops only its native child | [Native boundaries](../../../crates/daemon/tests/support/native_context_boundaries.py) | Two actual route/tool starts, owned child stop and surviving neighbor; distinct native IDs |+| Missing or corrupt history never starts a replacement conversation | Same boundary journey | Missing file, truncated JSON, valid JSON missing message content, unsupported session version; zero model POSTs and no native repair for each independent task |+| Saved additional model routes work without CLI provider/credential overrides | [Additional models](../../../crates/daemon/tests/support/additional_model_product.py), [native file/result leaf](../../../crates/daemon/tests/support/additional_model_fixture.py) | Actual ordinary Pi output/session, restart, credential rotation, removed-route refusal, preserved defaults/unknown fields, independent model/Skill restoration |+| A main Agent reads its installed user collaboration Skill and delegates | [Collaboration](../../../crates/daemon/tests/support/collaboration_product.py), [role oracle](../../../crates/daemon/tests/support/collaboration_fixture.py) | Actual installed Skill body, public plans/exec/wait/result, distinct main/Worker sources, successful Worker output and independent disk artifact; owned Skill restoration |+| Native automatic compaction and Continue retain the frozen route | [Native compaction](../../../crates/daemon/tests/support/native_compaction_product.py) | Actual tool receipt in native summary request, independently returned summary in task transcript and subsequent prompt, exact same session, no foreign route |+| Import an effective static provider/model and use the saved source in a route | [Static discovery](../../../crates/daemon/tests/support/pi_discovery_product.py) | BOM/JSONC configuration, model endpoint override, saved credential precedence; public scan/prepare/save/restart with unchanged native files; stale source save refused; zero model POSTs during passive import, then exactly one ordinary native Pi request through the saved source and published Plan; restore owned settings |++Ordinary tests compile these ignored targets without executing them. The test+planner registers all seven required native tests explicitly. Cheap shared oracle+checks are in `scripts/test-agent-product-support.py`,+`scripts/test-qoder-product.py`, `scripts/test-native-context-product.py` and+`scripts/test-native-context-boundaries.py`; they cannot prove native support.+Keep security/ownership assertions separate when a product journey cannot cover+that failure branch precisely.++## Ownership and evidence limits++The Worker uses an empty in-memory credential store so native authentication+helpers cannot execute during runtime initialization. Installed package resources+are resolved offline; missing packages are not installed. Extensions are disabled.+Native model/default/auth files are borrowed and must remain byte-for-byte intact.+Only the task's `native-pi.jsonl` is owned. Validate its current v3 shape before+native open, because the SDK can otherwise skip malformed rows or migrate history.+SDK release and transcript format compatibility are separate. Missing native open+only blocks Continue; an unknown SDK writer or existing transcript format blocks+Worker execution/restoration without changing unrelated model or task-route setup.+Cheap local interface/ownership regressions are in+`crates/integrations/src/agents/pi_sdk_contract.test.mjs`; synthetic release labels+prove admission behavior, not actual future-release compatibility.++Main-Agent model settings own only one provider member in `models.json` and the+local grant inside that private file. Pi's separate user `settings.json` default+is a transaction dependency checked again at activation/retry. Project defaults+are native project configuration outside this global default ownership contract.+A helper or OAuth key can be reported but never imported by executing it.++The stored-source journey has three required outcomes: passive import, stale+source refusal, and saved-source route use. The first two make no model request.+The last publishes the imported binding, saves an additional Pi route and invokes+ordinary Pi without endpoint or credential overrides; an independent source+receipt proves the one resulting model request. This guards the whole saved+source → capability qualification → Plan → native settings path, rather than+treating a successful scan or save as usable routing.++The native journeys prove routing, tools, context and restoration using+deterministic sources. They do not prove arbitrary+live-provider behavior, native OAuth, restrictions not implemented by the SDK+bridge, Windows, or every plugin/extension. Record platform, candidate SHA,+fixture revision, selected cases and verdicts together.++macOS additionally requires the current real Desktop/Pilot entry: scan/import a+source, select Pi CLI and Node, publish a Pi Worker Plan, enable/adjust/disable+model and task routes through the page, invoke the saved route, inspect a task and+Continue/cancel actual native work. API setup and a successful toast cannot replace+those UI actions. Continue is a public Worker CLI action followed by observing+the updated task/run in Desktop; Desktop has no separate Continue control for any+ecosystem. Cancellation must use Desktop's task detail and confirmation, followed+by real child-stop and live-neighbor witnesses. Leave the validated client open+only when handing it to the user.++Recovery acceptance also forces a recoverable length stop through the real Pi SDK,+requires its persisted `context_edit` omission, and continues the exact recovered session.+This is separate from threshold compaction; fixture-only history parsing is not native recovery proof.diff --git a/tools/product-e2e/tests/control_shell.rs b/tools/product-e2e/tests/control_shell.rsindex ffaa56d7..ea73390c 100644--- a/tools/product-e2e/tests/control_shell.rs+++ b/tools/product-e2e/tests/control_shell.rs@@ -351,6 +351,7 @@ fn assert_discovery_agent_ids(agents: &[Value]) {"agent_codex_default","agent_claude_default","agent_qoder_default",+ "agent_pi_default",] {assert!(ids.contains(required), "missing required Agent: {required}");}diff --git a/tools/product-e2e/tests/pi_delegation.rs b/tools/product-e2e/tests/pi_delegation.rsnew file mode 100644index 00000000..1646ebad--- /dev/null+++ b/tools/product-e2e/tests/pi_delegation.rs@@ -0,0 +1,63 @@+#![cfg(unix)]+mod worker_product_support;++#[test]+#[ignore = "requires the selected official Pi SDK/Node and real production binaries"]+fn pi_worker_uses_native_skills_and_continues_the_frozen_task() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_PI_CORE",+ "worker-native-context-core",+ );+}+#[test]+#[ignore = "requires the selected official Pi SDK/Node and real production binaries"]+fn pi_workers_route_independently_and_reject_missing_or_corrupt_history() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_PI_BOUNDARIES",+ "worker-native-context-boundaries",+ );+}++#[test]+#[ignore = "requires the selected official Pi SDK/Node and real production binaries"]+fn pi_agent_saved_model_routes_preserve_defaults_and_restore_independently() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_PI_MODELS",+ "pi-persisted-model-routes",+ );+}++#[test]+#[ignore = "requires the selected official Pi SDK/Node and real production binaries"]+fn pi_agent_uses_installed_user_skill_to_delegate_through_public_cli() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_PI_MAIN",+ "pi-main-agent-delegation",+ );+}+#[test]+#[ignore = "requires the selected official Pi SDK/Node and real production binaries"]+fn pi_worker_compaction_uses_frozen_route_and_continues_exact_history() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_PI_COMPACTION",+ "pi-worker-compaction-route",+ );+}++#[test]+#[ignore = "requires the selected official Pi installation and real production binaries"]+fn pi_static_api_discovery_imports_effective_source_and_rejects_stale_save() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_PI_DISCOVERY",+ "pi-static-source-import",+ );+}++#[test]+#[ignore = "requires the selected official Pi SDK/Node and real production binaries"]+fn pi_worker_recovers_length_overflow_and_continues_edited_history() {+ worker_product_support::run_real_worker_scenario(+ "HIROUTE_PRODUCT_PI_RECOVERY",+ "pi-worker-compaction-route",+ );+}diff --git a/tools/product-e2e/tests/worker_product_support/mod.rs b/tools/product-e2e/tests/worker_product_support/mod.rsindex 8e2fe393..ea613e56 100644--- a/tools/product-e2e/tests/worker_product_support/mod.rs+++ b/tools/product-e2e/tests/worker_product_support/mod.rs@@ -15,6 +15,27 @@ const REQUIRED_INSTALLATIONS: [&str; 5] = [];pub fn run_real_worker_scenario(mode: &str, expected_scenario: &str) {+ let pi_script = match mode {+ "HIROUTE_PRODUCT_PI_CORE" => Some("native_context_product.py"),+ "HIROUTE_PRODUCT_PI_BOUNDARIES" => Some("native_context_boundaries.py"),+ "HIROUTE_PRODUCT_PI_MODELS" => Some("additional_model_product.py"),+ "HIROUTE_PRODUCT_PI_MAIN" => Some("collaboration_product.py"),+ "HIROUTE_PRODUCT_PI_COMPACTION" | "HIROUTE_PRODUCT_PI_RECOVERY" => {+ Some("native_compaction_product.py")+ }+ "HIROUTE_PRODUCT_PI_DISCOVERY" => Some("pi_discovery_product.py"),+ _ => None,+ };+ if let Some(script) = pi_script {+ run_scenario(+ script,+ mode,+ expected_scenario,+ &["pi"],+ &["HIROUTE_WORKER_PI_BINARY", "HIROUTE_WORKER_NODE"],+ );+ return;+ }let qoder_script = match mode {"HIROUTE_PRODUCT_QODER_MAIN" => Some("qoder_collaboration_product.py"),"HIROUTE_PRODUCT_QODER_CORE" => Some("native_context_product.py"),@@ -162,12 +183,18 @@ fn assert_scenario(output: Output, scenario: &str, harness: &str, candidate: &st"worker.context.tool-summary-route","worker.context.compaction-route",],- "qoder-main-agent-delegation" => &[+ "pi-worker-compaction-route" => &["worker.context.compaction-route"],+ "pi-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" => &["agent.collaboration.user-skill","agent.collaboration.public-worker-delegation","agent.collaboration.disable-owned-skill",],- "qoder-persisted-model-routes" => &[+ "qoder-persisted-model-routes" | "pi-persisted-model-routes" => &["agent.models.persisted-routes","agent.models.credential-rotation","agent.models.independent-restore",